summaryrefslogtreecommitdiff
path: root/cpp/src/Ice/SslSystemOpenSSL.cpp
blob: aada4c7bff9a8647d3fb602e25762cc0d074521c (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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
// **********************************************************************
//
// Copyright (c) 2001
// MutableRealms, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************
#ifdef WIN32
#pragma warning(disable:4786)
#endif

#include <sstream>
#include <openssl/err.h>
#include <openssl/e_os.h>
#include <openssl/rand.h>
#include <Ice/Security.h>
#include <Ice/SslSystem.h>
#include <Ice/SecurityException.h>
#include <Ice/SslConnectionOpenSSLClient.h>
#include <Ice/SslConnectionOpenSSLServer.h>
#include <Ice/SslConfig.h>

using namespace std;

namespace IceSecurity
{

namespace Ssl
{

namespace OpenSSL
{

//
// TODO: These Diffie-Hellman params have been blatantly stolen from
//       OpenSSL's demo programs.  We SHOULD define our own here, but
//       these will suffice for testing purposes.  Please note, these
//       are not keys themselves, simply a DH Group that allows OpenSSL
//       to create Diffie-Hellman keys.
//

// Instantiation of temporary Diffie-Hellman 512bit key.
unsigned char System::_tempDiffieHellman512p[] =
{
    0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
    0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
    0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
    0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
    0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
    0x47,0x74,0xE8,0x33,
};

unsigned char System::_tempDiffieHellman512g[] =
{
    0x02,
};

// TODO: Very possibly a problem later if we have mutliple loggers going on simultaneously.
// This is a horrible necessity in order to make the trace levels
// and logger available to the bio_dump_cb() callback function.
// Otherwise, we would have to jump through hoops, creating a mapping
// from BIO pointers to the relevent System object.  The system object
// will initialize these.  NOTE: If we SHOULD have multiple loggers
// going on simultaneously, this will definitely cause a problem.
TraceLevelsPtr System::_globalTraceLevels = 0;
Ice::LoggerPtr System::_globalLogger = 0;

}

}

}

using IceSecurity::Ssl::OpenSSL::ContextException;

//
// NOTE: The following (mon, getGeneralizedTime, getUTCTime and getASN1time are routines that
//       have been abducted from the OpenSSL X509 library, and modified to work with the STL
//       basic_string template.

static const char *mon[12]=
{
    "Jan","Feb","Mar","Apr","May","Jun",
    "Jul","Aug","Sep","Oct","Nov","Dec"
};

string
getGeneralizedTime(ASN1_GENERALIZEDTIME *tm)
{
    char buf[30];
    char *v;
    int gmt=0;
    int i;
    int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;

    i = tm->length;
    v = (char *) tm->data;

    if (i < 12)
    {
        goto err;
    }

    if (v[i-1] == 'Z')
    {
        gmt=1;
    }

    for (i=0; i<12; i++)
    {
        if ((v[i] > '9') || (v[i] < '0'))
        {
            goto err;
        }
    }

    y = (v[0] - '0') * 1000 + (v[1] - '0') * 100 + (v[2] - '0') * 10 + (v[3] - '0');
    M = (v[4] - '0') * 10 + (v[5] - '0');

    if ((M > 12) || (M < 1))
    {
        goto err;
    }

    d = (v[6] - '0') * 10 + (v[7] - '0');
    h = (v[8] - '0') * 10 + (v[9] - '0');
    m = (v[10] - '0') * 10 + (v[11] - '0');

    if ((v[12] >= '0') && (v[12] <= '9') &&
        (v[13] >= '0') && (v[13] <= '9'))
    {
        s = (v[12] - '0') * 10 + (v[13] - '0');
    }

    sprintf(buf, "%s %2d %02d:%02d:%02d %d%s", mon[M-1], d, h, m, s, y, (gmt)?" GMT":"");
    return string(buf);

err:
    return string("Bad time value");
}

string
getUTCTime(ASN1_UTCTIME *tm)
{
    char buf[30];
    char *v;
    int gmt=0;
    int i;
    int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;

    i = tm->length;
    v = (char *) tm->data;

    if (i < 10)
    { 
        goto err;
    }

    if (v[i-1] == 'Z')
    {
        gmt=1;
    }

    for (i = 0; i < 10; i++)
    {
        if ((v[i] > '9') || (v[i] < '0'))
        {
            goto err;
        }
    }

    y = (v[0] - '0') * 10 + (v[1] - '0');

    if (y < 50)
    {
        y+=100;
    }

    M = (v[2] - '0') * 10 + (v[3] - '0');

    if ((M > 12) || (M < 1))
    {
        goto err;
    }

    d = (v[4] - '0') * 10 + (v[5] - '0');
    h = (v[6] - '0') * 10 + (v[7] - '0');
    m = (v[8] - '0') * 10 + (v[9] - '0');

    if ((v[10] >= '0') && (v[10] <= '9') && (v[11] >= '0') && (v[11] <= '9'))
    {
        s = (v[10] - '0') * 10 + (v[11] - '0');
    }

    sprintf(buf, "%s %2d %02d:%02d:%02d %d%s", mon[M-1], d, h, m, s, y+1900, (gmt)?" GMT":"");
    return string(buf);

err:
    return string("Bad time value");
}

string
getASN1time(ASN1_TIME *tm)
{
    string theTime;

    switch (tm->type)
    {
        case V_ASN1_UTCTIME :
        {
            theTime = getUTCTime(tm);
        }

        case V_ASN1_GENERALIZEDTIME :
        {
	    theTime = getGeneralizedTime(tm);
        }

        default :
        {
            theTime = "Bad time value";
        }
    }

    return theTime;
}

extern "C"
{

RSA*
tmpRSACallback(SSL *s, int isExport, int keyLength)
{
    IceSecurity::Ssl::System* sslSystem = IceSecurity::Ssl::Factory::getSystemFromHandle(s);

    IceSecurity::Ssl::OpenSSL::System* openSslSystem = dynamic_cast<IceSecurity::Ssl::OpenSSL::System*>(sslSystem);

    RSA* rsaKey = openSslSystem->getRSAKey(s, isExport, keyLength);

    IceSecurity::Ssl::Factory::releaseSystemFromHandle(s, sslSystem);

    return rsaKey;
}

DH*
tmpDHCallback(SSL *s, int isExport, int keyLength)
{
    IceSecurity::Ssl::System* sslSystem = IceSecurity::Ssl::Factory::getSystemFromHandle(s);

    IceSecurity::Ssl::OpenSSL::System* openSslSystem = dynamic_cast<IceSecurity::Ssl::OpenSSL::System*>(sslSystem);

    DH* dh = openSslSystem->getDHParams(s, isExport, keyLength);

    IceSecurity::Ssl::Factory::releaseSystemFromHandle(s, sslSystem);

    return dh;
}

// verifyCallback - Certificate Verification callback function.
int
verifyCallback(int ok, X509_STORE_CTX *ctx)
{
    X509* err_cert = X509_STORE_CTX_get_current_cert(ctx);
    int verifyError = X509_STORE_CTX_get_error(ctx);
    int depth = X509_STORE_CTX_get_error_depth(ctx);

    // If we have no errors so far, and the certificate chain is too long
    if ((verifyError != X509_V_OK) && (10 < depth))
    {
        verifyError = X509_V_ERR_CERT_CHAIN_TOO_LONG;
    }

    if (verifyError != X509_V_OK)
    {
        // If we have ANY errors, we bail out.
        ok = 0;
    }

    // Only if ICE_PROTOCOL level logging is on do we worry about this.
    if (ICE_SECURITY_LEVEL_PROTOCOL_GLOBAL)
    {
        char buf[256];

        X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));

        ostringstream outStringStream;

        outStringStream << "depth = " << depth << ":" << buf << endl;

        if (!ok)
        {
            outStringStream << "verify error: num = " << verifyError << " : "  << X509_verify_cert_error_string(verifyError) << endl;

        }

        switch (verifyError)
        {
            case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
            {
                X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf));
                outStringStream << "issuer = " << buf << endl;
                break;
            }

            case X509_V_ERR_CERT_NOT_YET_VALID:
            case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
            {
                outStringStream << "notBefore =" << getASN1time(X509_get_notBefore(ctx->current_cert)) << endl;
                break;
            }

            case X509_V_ERR_CERT_HAS_EXPIRED:
            case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
            {
                outStringStream << "notAfter =" << getASN1time(X509_get_notAfter(ctx->current_cert)) << endl;
                break;
            }
        }

        outStringStream << "verify return = " << ok << endl;

        IceSecurity::Ssl::OpenSSL::System::_globalLogger->trace(IceSecurity::Ssl::OpenSSL::System::_globalTraceLevels->securityCat, outStringStream.str());
    }

    return ok;
}

// This code duplicates functionality that existed in the BIO library of
// OpenSSL, but outputs to a Logger compatible source (ostringstream).
void
dump(ostringstream& outStringStream, const char* s, int len)
{
    unsigned char ch;
    char hexStr[8];

    int trunc = 0;
	
    // Calculate how much white space we're truncating.
    for(; (len > 0) && ((s[len - 1] == ' ') || (s[len - 1] == '\0')); len--) 
    {
        trunc++;
    }

    int dump_width = 12;

    int rows = len / dump_width;

    if ((rows * dump_width) < len)
    {
	rows++;
    }

    if (rows > 0)
    {
        outStringStream << endl;
    }

    for(int i = 0; i < rows; i++)
    {
        // Would like to have not used sprintf(), but
        // I could not find an appropriate STL methodology
        // for preserving the field width.
        sprintf(hexStr,"%04x",(i * dump_width));
        outStringStream << hexStr << " - ";

        int j;

        // Hex Dump
        for(j = 0; j < dump_width; j++)
	{
	    if (((i * dump_width) + j) >= len)
	    {
                outStringStream << "   ";
	    }
            else
	    {
                char sep = (j == 7 ? '-' : ' ');

                // Get a character from the dump we've been handed.
                ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff;

                // Would like to have not used sprintf(), but
                // I could not find an appropriate STL methodology
                // for preserving the field width.
                sprintf(hexStr,"%02x",ch);
                outStringStream << hexStr << sep;
	    }
	}

        outStringStream << "  ";

        // Printable characters dump.
        for(j = 0; j < dump_width; j++)
	{
	    if (((i * dump_width) + j) >= len)
            {
		break;
            }

            ch = ((unsigned char) * (s + i * dump_width + j)) & 0xff;

            // Print printables only.
            ch = ((ch >= ' ') && (ch <= '~')) ? ch : '.';

            outStringStream << ch;
	}

        outStringStream << endl;
    }

    if (trunc > 0)
    {
        outStringStream << hex << (len + trunc) << " - " << "<SPACES/NULS>" << endl;
    }
}

long
bio_dump_cb(BIO *bio, int cmd, const char *argp, int argi, long argl, long ret)
{
    if (IceSecurity::Ssl::OpenSSL::System::_globalTraceLevels->security >= IceSecurity::SECURITY_PROTOCOL)
    {
        ostringstream outStringStream;

        if (cmd == (BIO_CB_READ|BIO_CB_RETURN))
        {
            outStringStream << "PTC Thread(" << dec << GETTHREADID << ") ";
            outStringStream << "read from " << hex << (void *)bio << " [" << hex << (void *)argp;
            outStringStream << "] (" << dec << argi << " bytes => " << ret << " (0x";
            outStringStream << hex << ret << "))";
            dump(outStringStream, argp,(int)ret);
        }
        else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
        {
            outStringStream << "PTC Thread(" << dec << GETTHREADID << ") ";
            outStringStream << "write to " << hex << (void *)bio << " [" << hex << (void *)argp;
            outStringStream << "] (" << dec << argi << " bytes => " << ret << " (0x";
            outStringStream << hex << ret << "))";
            dump(outStringStream, argp,(int)ret);
        }

        if (cmd == (BIO_CB_READ|BIO_CB_RETURN) || cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
        {
            IceSecurity::Ssl::OpenSSL::System::_globalLogger->trace(IceSecurity::Ssl::OpenSSL::System::_globalTraceLevels->securityCat, outStringStream.str());
        }
    }

    return ret;
}

}

void
IceSecurity::Ssl::OpenSSL::System::printContextInfo(SSL_CTX* context)
{
    if (ICE_SECURITY_LEVEL_PROTOCOL)
    {
        ostringstream s;

        s << endl;
        s << "SSL_CTX Structure" << endl;
        s << "=================" << endl;
        s << "options: 0x" << hex << context->options << endl;
        s << "mode:    0x" << hex << context->mode << endl;

        s << "session_cache_size: " << context->session_cache_size << endl;
        s << "session_cache_mode: 0x" << hex << context->session_cache_mode << endl;
        s << "session_timeout:    " << Int(context->session_timeout) << endl << endl;

        s << "Stats" << endl;
        s << "Connect:      " << context->stats.sess_connect << "  (New Connect Started)" << endl;
        s << "Renegotiate:  " << context->stats.sess_connect_renegotiate << " (Renegotiation Requested)" << endl;
        s << "Connect Good: " << context->stats.sess_connect_good << " (Connect/Renegotiation finished)";
        s << endl << endl;

        s << "Accept:       " << context->stats.sess_accept << " (New Accept Started)" << endl;
        s << "Renegotiate:  " << context->stats.sess_accept_renegotiate << " (Renegotiation Requested)" << endl;
        s << "Accept Good:  " << context->stats.sess_accept_good << " (Accept/Renegotiation finished)";
        s << endl << endl;

        s << "Miss:         " << context->stats.sess_miss << " (Session Lookup Misses)" << endl;
        s << "Timeout:      " << context->stats.sess_timeout << " (Reuse attempt on Timeouted Session)" << endl;
        s << "Cache Full:   " << context->stats.sess_cache_full << " (Session Removed due to full cache)" << endl;
        s << "Hit:          " << context->stats.sess_hit << " (Session Reuse actually done.)" << endl;
        s << "CB Hit:       " << context->stats.sess_cb_hit << " (Session ID supplied by Callback)" << endl;

        s << "read_ahead:   " << context->read_ahead << endl;
        s << "verify_mode:  0x" << hex << context->verify_mode << endl;
        s << "verify_depth: " << Int(context->verify_depth) << endl;

        ICE_PROTOCOL(s.str());
    }
}

IceSecurity::Ssl::Connection*
IceSecurity::Ssl::OpenSSL::System::createServerConnection(int socket)
{
    ICE_METHOD_INV("OpenSSL::System::createServerConnection()");

    if (_sslServerContext == 0)
    {
        ContextException contextEx(__FILE__, __LINE__);

        contextEx._message = "Server context has not been set up - ";
        contextEx._message += "please specify an SSL server configuration file.";

        ICE_EXCEPTION(contextEx._message);

	throw contextEx;
    }

    SSL* sslConnection = createConnection(_sslServerContext, socket);

    // Set the Accept Connection state for this connection.
    SSL_set_accept_state(sslConnection);

    Connection* connection = new ServerConnection(sslConnection, _systemID);

    commonConnectionSetup(connection);

    ICE_METHOD_RET("OpenSSL::System::createServerConnection()");

    return connection;
}

IceSecurity::Ssl::Connection*
IceSecurity::Ssl::OpenSSL::System::createClientConnection(int socket)
{
    ICE_METHOD_INV("OpenSSL::System::createClientConnection()");

    if (_sslClientContext == 0)
    {
        ContextException contextEx(__FILE__, __LINE__);

        contextEx._message = "Client context has not been set up - ";
        contextEx._message += "please specify an SSL client configuration file.";

        ICE_EXCEPTION(contextEx._message);

	throw contextEx;
    }

    SSL* sslConnection = createConnection(_sslClientContext, socket);

    // Set the Connect Connection state for this connection.
    SSL_set_connect_state(sslConnection);

    Connection* connection = new ClientConnection(sslConnection, _systemID);

    commonConnectionSetup(connection);

    ICE_METHOD_RET("OpenSSL::System::createClientConnection()");

    return connection;
}

void
IceSecurity::Ssl::OpenSSL::System::shutdown()
{
    ICE_METHOD_INV("OpenSSL::System::shutdown()");

    if (_sslServerContext != 0)
    {
        SSL_CTX_free(_sslServerContext);

        _sslServerContext = 0;
    }

    if (_sslClientContext != 0)
    {
        SSL_CTX_free(_sslClientContext);

        _sslClientContext = 0;
    }

    // Free our temporary RSA keys.
    RSAMap::iterator iRSA = _tempRSAKeys.begin();
    RSAMap::iterator eRSA = _tempRSAKeys.end();

    while (iRSA != eRSA)
    {
        RSA_free((*iRSA).second);
        iRSA++;
    }

    // Free our temporary DH params.
    DHMap::iterator iDH = _tempDHKeys.begin();
    DHMap::iterator eDH = _tempDHKeys.end();

    while (iDH != eDH)
    {
        DH_free((*iDH).second);
        iDH++;
    }

    ICE_METHOD_RET("OpenSSL::System::shutdown()");
}

bool
IceSecurity::Ssl::OpenSSL::System::isConfigLoaded()
{
    ICE_METHOD_INS("OpenSSL::System::isConfigLoaded()");

    return _configLoaded;
}

void
IceSecurity::Ssl::OpenSSL::System::loadConfig()
{
    ICE_METHOD_INV("OpenSSL::System::loadConfig()");

    // This step is required in order to supply callback functions
    // with access to the TraceLevels and Logger.
    if (_globalTraceLevels == 0)
    {
        _globalTraceLevels = _traceLevels;
        _globalLogger = _logger;
    }

    string configFile = _properties->getProperty("Ice.Security.Ssl.Config");
    string certificatePath = _properties->getProperty("Ice.Security.Ssl.CertPath");
    Parser sslConfig(configFile, certificatePath);

    sslConfig.setTrace(_traceLevels);
    sslConfig.setLogger(_logger);

    // Actually parse the file now.
    sslConfig.process();

    GeneralConfig clientGeneral;
    CertificateAuthority clientCertAuth;
    BaseCertificates clientBaseCerts;

    // Walk the parse tree, get the Client configuration.
    if (sslConfig.loadClientConfig(clientGeneral, clientCertAuth, clientBaseCerts))
    {
        if (ICE_SECURITY_LEVEL_PROTOCOL)
        {
            ostringstream s;

            s << endl;
            s << "General Configuration - Client" << endl;
            s << "------------------------------" << endl;
            s << clientGeneral << endl << endl;

            s << "Base Certificates - Client" << endl;
            s << "--------------------------" << endl;
            s << clientBaseCerts << endl;

            ICE_PROTOCOL(s.str());
        }

        initClient(clientGeneral, clientCertAuth, clientBaseCerts);
    }

    GeneralConfig serverGeneral;
    CertificateAuthority serverCertAuth;
    BaseCertificates serverBaseCerts;
    TempCertificates serverTempCerts;

    // Walk the parse tree, get the Server configuration.
    if (sslConfig.loadServerConfig(serverGeneral, serverCertAuth, serverBaseCerts, serverTempCerts))
    {
        if (ICE_SECURITY_LEVEL_PROTOCOL)
        {
            ostringstream s;

            s << endl;
            s << "General Configuration - Server" << endl;
            s << "------------------------------" << endl;
            s << serverGeneral   << endl << endl;

            s << "Base Certificates - Server" << endl;
            s << "--------------------------" << endl;
            s << serverBaseCerts << endl << endl;

            s << "Temp Certificates - Server" << endl;
            s << "--------------------------" << endl;
            s << serverTempCerts << endl;

            ICE_PROTOCOL(s.str());
        }

        initServer(serverGeneral, serverCertAuth, serverBaseCerts, serverTempCerts);
    }

    ICE_METHOD_RET("OpenSSL::System::loadConfig()");
}

RSA*
IceSecurity::Ssl::OpenSSL::System::getRSAKey(SSL *s, int isExport, int keyLength)
{
    ICE_METHOD_INV("OpenSSL::System::getRSAKey()");

    JTCSyncT<JTCMutex> sync(_tempRSAKeysMutex);

    RSA* rsa_tmp = 0;

    RSAMap::iterator retVal = _tempRSAKeys.find(keyLength);

    // Does the key already exist?
    if (retVal != _tempRSAKeys.end())
    {
        // Yes!  Use it.
        rsa_tmp = (*retVal).second;
    }
    else
    {
        const RSACertMap::iterator& it = _tempRSAFileMap.find(keyLength);

        if (it != _tempRSAFileMap.end())
        {
            CertificateDesc& rsaKeyCert = (*it).second;

            const string& privKeyFile = rsaKeyCert.getPrivate().getFileName();
            const string& pubCertFile = rsaKeyCert.getPublic().getFileName();

            RSA* rsaCert = 0;
            RSA* rsaKey = 0;
            BIO* bio = 0;

            if ((bio = BIO_new_file(pubCertFile.c_str(), "r")) != 0)
            {
                rsaCert = PEM_read_bio_RSAPublicKey(bio, 0, 0, 0);

                BIO_free(bio);
                bio = 0;
            }

            if (rsaCert != 0)
            {
                if ((bio = BIO_new_file(privKeyFile.c_str(), "r")) != 0)
                {
                    rsaKey = PEM_read_bio_RSAPrivateKey(bio, &rsaCert, 0, 0);

                    BIO_free(bio);
                    bio = 0;
                }
            }

            // Now, if all was well, the Certificate and Key should both be loaded into
            // rsaCert. We check to ensure that both are not 0, because if either are,
            // one of the reads failed.

            if ((rsaCert != 0) && (rsaKey != 0))
            {
                rsa_tmp = rsaCert;
            }
            else
            {
                RSA_free(rsaCert);
                rsaCert = 0;
            }
        }

        // Last ditch effort - generate a key on the fly.
        if (rsa_tmp == 0)
        {
            rsa_tmp = RSA_generate_key(keyLength, RSA_F4, 0, 0);
        }

        // Save in our temporary key cache.
        if (rsa_tmp == 0)
        {
            _tempRSAKeys[keyLength] = rsa_tmp;
        }
    }

    ICE_METHOD_RET("OpenSSL::System::getRSAKey()");

    return rsa_tmp;
}

DH*
IceSecurity::Ssl::OpenSSL::System::getDHParams(SSL *s, int isExport, int keyLength)
{
    ICE_METHOD_INV("OpenSSL::System::getDHParams()");

    JTCSyncT<JTCMutex> sync(_tempDHKeysMutex);

    DH *dh_tmp = 0;

    const DHMap::iterator& retVal = _tempDHKeys.find(keyLength);

    // Does the key already exist?
    if (retVal != _tempDHKeys.end())
    {
        // Yes!  Use it.
        dh_tmp = (*retVal).second;
    }
    else
    {
        const DHParamsMap::iterator& it = _tempDHParamsFileMap.find(keyLength);

        if (it != _tempDHParamsFileMap.end())
        {
            DiffieHellmanParamsFile& dhParamsFile = (*it).second;

            string dhFile = dhParamsFile.getFileName();

            dh_tmp = loadDHParam(dhFile.c_str());

            if (dh_tmp != 0)
            {
                _tempDHKeys[keyLength] = dh_tmp;
            }
        }
    }

    ICE_METHOD_RET("OpenSSL::System::getDHParams()");

    return dh_tmp;
}

//
// Protected
//

IceSecurity::Ssl::OpenSSL::System::System(string& systemID) :
                                  IceSecurity::Ssl::System(systemID)
{
    _configLoaded = false;

    _sessionContext = "iceServer";

    _sslServerContext = 0;
    _sslClientContext = 0;

    SSL_load_error_strings();

    OpenSSL_add_ssl_algorithms();
}

IceSecurity::Ssl::OpenSSL::System::~System()
{
    ICE_METHOD_INV("OpenSSL::~System()");

    shutdown();

    ICE_METHOD_RET("OpenSSL::~System()");
}

//
// Private
//

void
IceSecurity::Ssl::OpenSSL::System::initClient(GeneralConfig& general,
                                              CertificateAuthority& certAuth,
                                              BaseCertificates& baseCerts)
{
    ICE_METHOD_INV("OpenSSL::System::initClient()");

    // Init the Random Number System.
    initRandSystem(general.getRandomBytesFiles());

    // Create an SSL Context based on the context params.
    _sslClientContext = createContext(general.getProtocol());

    // Begin setting up the SSL Context.
    if (_sslClientContext != 0)
    {
        // Get the cipherlist and set it in the context.
        setCipherList(_sslClientContext, general.getCipherList());

        // Set the certificate verification mode.
        SSL_CTX_set_verify(_sslClientContext, general.getVerifyMode(), verifyCallback);

        // Set the certificate verify depth to 10 deep.
        SSL_CTX_set_verify_depth(_sslClientContext, general.getVerifyDepth());

        // Process the RSA Certificate (if present).
        if (baseCerts.getRSACert().getKeySize() != 0)
        {
            processCertificate(_sslClientContext, baseCerts.getRSACert());
        }

        // Process the DSA Certificate (if present).
        if (baseCerts.getDSACert().getKeySize() != 0)
        {
            processCertificate(_sslClientContext, baseCerts.getDSACert());
        }

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

        // Load the Certificate Authority files, and check them.
        loadCAFiles(_sslClientContext, certAuth);
    }

    ICE_METHOD_RET("OpenSSL::System::initClient()");
}

void
IceSecurity::Ssl::OpenSSL::System::initServer(GeneralConfig& general,
                                              CertificateAuthority& certAuth,
                                              BaseCertificates& baseCerts,
                                              TempCertificates& tempCerts)
{
    ICE_METHOD_INV("OpenSSL::System::initServer()");

    // Init the Random Number System.
    initRandSystem(general.getRandomBytesFiles());

    // Create an SSL Context based on the context params.
    _sslServerContext = createContext(general.getProtocol());

    // Begin setting up the SSL Context.
    if (_sslServerContext != 0)
    {
        // On servers, Attempt to use non-export (strong) encryption
        // first.  This option does not always work, and in the OpenSSL
        // documentation is declared as 'broken'.
        // SSL_CTX_set_options(_sslServerContext,SSL_OP_NON_EXPORT_FIRST);

        // Always use a new DH key when using Diffie-Hellman key agreement.
        SSL_CTX_set_options(_sslServerContext, SSL_OP_SINGLE_DH_USE);

        loadTempCerts(tempCerts);

        // Load the Certificate Authority files, and check them.
        loadAndCheckCAFiles(_sslServerContext, certAuth);

        // Process the RSA Certificate (if present).
        if (baseCerts.getRSACert().getKeySize() != 0)
        {
            processCertificate(_sslServerContext, baseCerts.getRSACert());
        }

        // Process the DSA Certificate (if present).
        if (baseCerts.getDSACert().getKeySize() != 0)
        {
            processCertificate(_sslServerContext, baseCerts.getDSACert());
        }

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

        // Set the RSA Callback routine in case we need to build a temporary RSA key.
        SSL_CTX_set_tmp_rsa_callback(_sslServerContext, tmpRSACallback);

        // Set the DH Callback routine in case we need a temporary DH key.
        SSL_CTX_set_tmp_dh_callback(_sslServerContext, tmpDHCallback);

        // Get the cipherlist and set it in the context.
        setCipherList(_sslServerContext, general.getCipherList());

        // Set the certificate verification mode.
        SSL_CTX_set_verify(_sslServerContext, general.getVerifyMode(), verifyCallback);

        // Set the certificate verify depth
        SSL_CTX_set_verify_depth(_sslServerContext, general.getVerifyDepth());

        // Set the default context for the SSL system (can be overridden if needed) [SERVER ONLY].
        SSL_CTX_set_session_id_context(_sslServerContext,
                                       reinterpret_cast<const unsigned char *>(_sessionContext.c_str()),
                                       _sessionContext.size());
    }

    printContextInfo(_sslServerContext);

    ICE_METHOD_RET("OpenSSL::System::initServer()");
}

SSL_METHOD*
IceSecurity::Ssl::OpenSSL::System::getSslMethod(SslProtocol sslVersion)
{
    ICE_METHOD_INV("OpenSSL::System::getSslMethod()");

    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 :
        {
            string errorString;

            errorString = "SSL Version ";
            errorString += sslVersion;
            errorString += " not supported - defaulting to SSL_V23.";

            ICE_WARNING(errorString);

            sslMethod   = SSLv23_method();
        }
    }

    ICE_METHOD_RET("OpenSSL::System::getSslMethod()");

    return sslMethod;
}

void
IceSecurity::Ssl::OpenSSL::System::processCertificate(SSL_CTX* sslContext, const CertificateDesc& certificateDesc)
{
    ICE_METHOD_INV("OpenSSL::System::processCertificate()");

    const CertificateFile& publicCert = certificateDesc.getPublic();
    const CertificateFile& privateKey = certificateDesc.getPrivate();

    addKeyCert(sslContext, publicCert, privateKey);

    ICE_METHOD_RET("OpenSSL::System::processCertificate()");
}

void
IceSecurity::Ssl::OpenSSL::System::addKeyCert(SSL_CTX* sslContext,
                                              const CertificateFile& publicCert,
                                              const CertificateFile& privateKey)
{
    ICE_METHOD_INV("OpenSSL::System::addKeyCert()");

    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)
        {
            ContextException contextEx(__FILE__, __LINE__);

            contextEx._message = "Unable to get certificate from '";
            contextEx._message += publicFile;
            contextEx._message += "'\n";
            contextEx._message += sslGetErrors();

            ICE_EXCEPTION(contextEx._message);

            throw contextEx;
        }

        if (privateKey.getFileName().empty())
        {
            ICE_WARNING("No private key specified - using the certificate.");

            privKeyFile = publicFile;
            privKeyFileType = publicEncoding;
        }

        // Set which Private Key file to use.
        if (SSL_CTX_use_PrivateKey_file(sslContext, privKeyFile, privKeyFileType) <= 0)
        {
            ContextException contextEx(__FILE__, __LINE__);

            contextEx._message = "Unable to get private key from '";
            contextEx._message += privKeyFile;
            contextEx._message += "'\n";
            contextEx._message += sslGetErrors();

            ICE_EXCEPTION(contextEx._message);

	    throw contextEx;
        }

        // 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))
        {
            ContextException contextEx(__FILE__, __LINE__);

            contextEx._message = "Private key does not match the certificate public key.";
            string sslError = sslGetErrors();

            if (!sslError.empty())
            {
                contextEx._message += "\n";
                contextEx._message += sslError;
            }

            ICE_EXCEPTION(contextEx._message);

            throw contextEx;
        }
    }

    ICE_METHOD_RET("OpenSSL::System::addKeyCert()");
}


SSL_CTX*
IceSecurity::Ssl::OpenSSL::System::createContext(SslProtocol sslProtocol)
{
    ICE_METHOD_INV("OpenSSL::System::createContext()");

    SSL_CTX* context = SSL_CTX_new(getSslMethod(sslProtocol));

    if (context == 0)
    {
        ContextException contextEx(__FILE__, __LINE__);

        contextEx._message = "Unable to create SSL Context.\n" + sslGetErrors();

        ICE_EXCEPTION(contextEx._message);

        throw contextEx;
    }

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

    ICE_METHOD_RET("OpenSSL::System::createContext()");

    return context;
}


string
IceSecurity::Ssl::OpenSSL::System::sslGetErrors()
{
    ICE_METHOD_INV("OpenSSL::System::sslGetErrors()");

    string errorMessage;
    char buf[200];
    char bigBuffer[1024];
    const char* file = 0;
    const char* data = 0;
    int line = 0;
    int flags = 0;
    unsigned errorCode = 0;
    int errorNum = 1;

    unsigned long es = CRYPTO_thread_id();

    while ((errorCode = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0)
    {
        sprintf(bigBuffer,"%6d - Thread ID: %lu\n", errorNum, es);
        errorMessage += bigBuffer;

        sprintf(bigBuffer,"%6d - Error:     %u\n", errorNum, errorCode);
        errorMessage += bigBuffer;

        // Request an error from the OpenSSL library
        ERR_error_string_n(errorCode, buf, sizeof(buf));
        sprintf(bigBuffer,"%6d - Message:   %s\n", errorNum, buf);
        errorMessage += bigBuffer;

        sprintf(bigBuffer,"%6d - Location:  %s, %d\n", errorNum, file, line);
        errorMessage += bigBuffer;

        if (flags & ERR_TXT_STRING)
        {
            sprintf(bigBuffer,"%6d - Data:      %s\n", errorNum, data);
            errorMessage += bigBuffer;
        }

        errorNum++;
    }

    ERR_clear_error();

    ICE_METHOD_RET("OpenSSL::System::sslGetErrors()");

    return errorMessage;
}

void
IceSecurity::Ssl::OpenSSL::System::commonConnectionSetup(Connection* connection)
{
    connection->setTrace(_traceLevels);
    connection->setLogger(_logger);

    // Set the Post-Hanshake Read timeout
    // This timeout is implemented once on the first read after hanshake.
    int handshakeReadTimeout;
    string value = _properties->getProperty("Ice.Security.Ssl.Handshake.ReadTimeout");

    if (!value.empty())
    {
	const_cast<int&>(handshakeReadTimeout) = atoi(value.c_str());
    }
    else
    {
        handshakeReadTimeout = 5000;
    }

    connection->setHandshakeReadTimeout(handshakeReadTimeout);
}

SSL*
IceSecurity::Ssl::OpenSSL::System::createConnection(SSL_CTX* sslContext, int socket)
{
    ICE_METHOD_INV("OpenSSL::System::createConnection()");

    SSL* sslConnection = 0;

    sslConnection = SSL_new(sslContext);

    SSL_clear(sslConnection);

    SSL_set_fd(sslConnection, socket);

    if (ICE_SECURITY_LEVEL_PROTOCOL_DEBUG)
    {
        sslConnection->debug = 1;
        BIO_set_callback(SSL_get_rbio(sslConnection), bio_dump_cb);
        BIO_set_callback_arg(SSL_get_rbio(sslConnection), 0);
        BIO_set_callback(SSL_get_wbio(sslConnection), bio_dump_cb);
        BIO_set_callback_arg(SSL_get_rbio(sslConnection), 0);
    }

    // Map the SSL Connection to this SslSystem
    // This is required for the OpenSSL callbacks
    // to work properly.
    Factory::addSystemHandle(sslConnection, this);

    ICE_METHOD_RET("OpenSSL::System::createConnection()");

    return sslConnection;
}

void
IceSecurity::Ssl::OpenSSL::System::loadCAFiles(SSL_CTX* sslContext, CertificateAuthority& certAuth)
{
    ICE_METHOD_INV("OpenSSL::System::loadCAFiles()");

    string caFile = certAuth.getCAFileName();
    string caPath = certAuth.getCAPath();

    loadCAFiles(sslContext, caFile.c_str(), caPath.c_str());

    ICE_METHOD_RET("OpenSSL::System::loadCAFiles()");
}

void
IceSecurity::Ssl::OpenSSL::System::loadCAFiles(SSL_CTX* sslContext, const char* caFile, const char* caPath)
{
    ICE_METHOD_INV("OpenSSL::System::loadCAFiles()");

    if (sslContext != 0)
    {
        // The following checks are required to send the expected values to the OpenSSL library.
        // It does not like receiving "", but prefers NULLs.
        if ((caFile != 0) && (strlen(caFile) == 0))
        {
            caFile = 0;
        }

        if ((caPath != 0) && (strlen(caPath) == 0))
        {
            caPath = 0;
        }

        // Check the Certificate Authority file(s).
        if ((!SSL_CTX_load_verify_locations(sslContext, caFile, caPath)) ||
            (!SSL_CTX_set_default_verify_paths(sslContext)))
        {
            // Non Fatal.
            ICE_WARNING("Unable to load/verify Certificate Authorities.");
        }
    }

    ICE_METHOD_RET("OpenSSL::System::loadCAFiles()");
}

void
IceSecurity::Ssl::OpenSSL::System::loadAndCheckCAFiles(SSL_CTX* sslContext, CertificateAuthority& certAuth)
{
    ICE_METHOD_INV("OpenSSL::System::loadAndCheckCAFiles()");

    if (sslContext != 0)
    {
        string caFile = certAuth.getCAFileName();
        string caPath = certAuth.getCAPath();

        // Check the Certificate Authority file(s).
        loadCAFiles(sslContext, caFile.c_str(), caPath.c_str());

        if (!caPath.empty())
        {
            STACK_OF(X509_NAME)* certNames = SSL_load_client_CA_file(caFile.c_str());

            if (certNames == 0)
            {
                string errorString = "Unable to load Certificate Authorities certificate names from " + caFile + ".\n";
                errorString += sslGetErrors();
                ICE_WARNING(errorString);
            }
            else
            {
                SSL_CTX_set_client_CA_list(sslContext, certNames);
            }
        }
    }

    ICE_METHOD_RET("OpenSSL::System::loadAndCheckCAFiles()");
}

DH*
IceSecurity::Ssl::OpenSSL::System::loadDHParam(const char* dhfile)
{
    ICE_METHOD_INV(string("OpenSSL::System::loadDHParam(") + dhfile + string(")"));

    DH* ret = 0;
    BIO* bio;

    if ((bio = BIO_new_file(dhfile,"r")) != 0)
    {
        ret = PEM_read_bio_DHparams(bio, 0, 0, 0);
    }

    if (bio != 0)
    {
        BIO_free(bio);
    }

    ICE_METHOD_RET(string("OpenSSL::System::loadDHParam(") + dhfile + string(")"));

    return ret;
}

DH*
IceSecurity::Ssl::OpenSSL::System::getTempDH(unsigned char* p, int plen, unsigned char* g, int glen)
{
    ICE_METHOD_INV("OpenSSL::System::getTempDH()");

    DH* dh = 0;

    if ((dh = DH_new()) != 0)
    {
        dh->p = BN_bin2bn(p, plen, 0);

        dh->g = BN_bin2bn(g, glen, 0);

        if ((dh->p == 0) || (dh->g == 0))
        {
            DH_free(dh);
            dh = 0;
        }
    }

    ICE_METHOD_RET("OpenSSL::System::getTempDH()");

    return dh;
}

DH*
IceSecurity::Ssl::OpenSSL::System::getTempDH512()
{
    ICE_METHOD_INV("OpenSSL::System::getTempDH512()");

    DH* dh = getTempDH(_tempDiffieHellman512p, sizeof(_tempDiffieHellman512p),
                       _tempDiffieHellman512g, sizeof(_tempDiffieHellman512g));

    ICE_METHOD_RET("OpenSSL::System::getTempDH512()");

    return dh;
}

void
IceSecurity::Ssl::OpenSSL::System::setDHParams(SSL_CTX* sslContext, BaseCertificates& baseCerts)
{
    ICE_METHOD_INV("OpenSSL::System::setDHParams()");

    string dhFile;
    int encoding = 0;

    if (baseCerts.getDHParams().getKeySize() != 0)
    {
        dhFile = baseCerts.getDHParams().getFileName();
        encoding = baseCerts.getDHParams().getEncoding();
    }
    else if (baseCerts.getRSACert().getKeySize() != 0)
    {
        dhFile = baseCerts.getRSACert().getPublic().getFileName();
        encoding = baseCerts.getRSACert().getPublic().getEncoding();
    }

    DH* dh = 0;

    // 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)
    {
        ICE_WARNING("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);
    }

    ICE_METHOD_RET("OpenSSL::System::setDHParams()");
}

void
IceSecurity::Ssl::OpenSSL::System::setCipherList(SSL_CTX* sslContext, const string& cipherList)
{
    ICE_METHOD_INV("OpenSSL::System::setCipherList()");

    if (!cipherList.empty() && (!SSL_CTX_set_cipher_list(sslContext, cipherList.c_str())))
    {
        string errorString = "Error setting cipher list " + cipherList + " - using default list.\n";

        errorString += sslGetErrors();

        ICE_WARNING(errorString);
    }

    ICE_METHOD_RET("OpenSSL::System::setCipherList()");
}

int
IceSecurity::Ssl::OpenSSL::System::seedRand()
{
    ICE_METHOD_INV("OpenSSL::System::seedRand()");

    int retCode = 1;
    char buffer[1024];
	
#ifdef WINDOWS
    RAND_screen();
#endif

    const char* file = RAND_file_name(buffer, sizeof(buffer));

    if (file == 0 || !RAND_load_file(file, -1))
    {
        retCode = 0;
    }
    else
    {
        _randSeeded = 1;
    }

    ICE_METHOD_RET("OpenSSL::System::seedRand()");

    return retCode;
}

long
IceSecurity::Ssl::OpenSSL::System::loadRandFiles(const string& names)
{
    ICE_METHOD_INV("OpenSSL::System::loadRandFiles(" + names + ")");

    long tot = 0;

    if (!names.empty())
    {
        int egd;

        // Make a modifiable copy of the string.
        char* namesString = new char[names.length() + 1];
        strcpy(namesString, names.c_str());

        char seps[5];

        sprintf(seps, "%c", LIST_SEPARATOR_CHAR);

        char* token = strtok(namesString, seps);

        while (token != 0)
        {
            egd = RAND_egd(token);

            if (egd > 0)
            {
                tot += egd;
            }
            else
            {
                tot += RAND_load_file(token, -1);
            }

            token = strtok(0, seps);
        }

        if (tot > 512)
        {
            _randSeeded = 1;
        }

        delete []namesString;
    }

    ICE_METHOD_RET("OpenSSL::System::loadRandFiles(" + names + ")");

    return tot;
}

void
IceSecurity::Ssl::OpenSSL::System::initRandSystem(const string& randBytesFiles)
{
    ICE_METHOD_INV("OpenSSL::System::initRandSystem(" + randBytesFiles + ")");

    if (!_randSeeded)
    {
        long randBytesLoaded = 0;

        if (!seedRand() && randBytesFiles.empty() && !RAND_status())
        {
            ICE_WARNING("There is a lack of random data, consider specifying a random data file.");
        }

        if (!randBytesFiles.empty())
        {
            randBytesLoaded = loadRandFiles(randBytesFiles);
        }
    }

    ICE_METHOD_RET("OpenSSL::System::initRandSystem(" + randBytesFiles + ")");
}

void
IceSecurity::Ssl::OpenSSL::System::loadTempCerts(TempCertificates& tempCerts)
{
    ICE_METHOD_INV("OpenSSL::System::loadTempCerts()");

    RSAVector::iterator iRSA = tempCerts.getRSACerts().begin();
    RSAVector::iterator eRSA = tempCerts.getRSACerts().end();

    while (iRSA != eRSA)
    {
        _tempRSAFileMap[(*iRSA).getKeySize()] = *iRSA;
        iRSA++;
    }

    DSAVector::iterator iDSA = tempCerts.getDSACerts().begin();
    DSAVector::iterator eDSA = tempCerts.getDSACerts().end();

    while (iDSA != eDSA)
    {
        _tempDSAFileMap[(*iDSA).getKeySize()] = *iDSA;
        iDSA++;
    }

    DHVector::iterator iDHP = tempCerts.getDHParams().begin();
    DHVector::iterator eDHP = tempCerts.getDHParams().end();

    while (iDHP != eDHP)
    {
        _tempDHParamsFileMap[(*iDHP).getKeySize()] = *iDHP;
        iDHP++;
    }

    ICE_METHOD_RET("OpenSSL::System::loadTempCerts()");
}