summaryrefslogtreecommitdiff
path: root/extra/yassl/src/yassl_imp.cpp
blob: bf10c4b8932296e8b47fe6868020519c2aec0e56 (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
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
/* yassl_imp.cpp                                
 *
 * Copyright (C) 2003 Sawtooth Consulting Ltd.
 *
 * This file is part of yaSSL.
 *
 * yaSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * There are special exceptions to the terms and conditions of the GPL as it
 * is applied to yaSSL. View the full text of the exception in the file
 * FLOSS-EXCEPTIONS in the directory of this software distribution.
 *
 * yaSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

/*  yaSSL source implements all SSL.v3 secification structures.
 */

#include "runtime.hpp"
#include "yassl_int.hpp"
#include "handshake.hpp"

#include "asn.hpp"  // provide crypto wrapper??



namespace yaSSL {


namespace { // locals

bool isTLS(ProtocolVersion pv)
{
    if (pv.major_ >= 3 && pv.minor_ >= 1)
        return true;

    return false;
}


}  // namespace (locals)


void hashHandShake(SSL&, const input_buffer&, uint);


ProtocolVersion::ProtocolVersion(uint8 maj, uint8 min) 
    : major_(maj), minor_(min) 
{}


// construct key exchange with known ssl parms
void ClientKeyExchange::createKey(SSL& ssl)
{
    const ClientKeyFactory& ckf = ssl.getFactory().getClientKey();
    client_key_ = ckf.CreateObject(ssl.getSecurity().get_parms().kea_);

    if (!client_key_)
        ssl.SetError(factory_error);
}


// construct key exchange with known ssl parms
void ServerKeyExchange::createKey(SSL& ssl)
{
    const ServerKeyFactory& skf = ssl.getFactory().getServerKey();
    server_key_ = skf.CreateObject(ssl.getSecurity().get_parms().kea_);

    if (!server_key_)
        ssl.SetError(factory_error);
}


// build/set PreMaster secret and encrypt, client side
void EncryptedPreMasterSecret::build(SSL& ssl)
{
    opaque tmp[SECRET_LEN];
    memset(tmp, 0, sizeof(tmp));
    ssl.getCrypto().get_random().Fill(tmp, SECRET_LEN);
    ProtocolVersion pv = ssl.getSecurity().get_connection().chVersion_;
    tmp[0] = pv.major_;
    tmp[1] = pv.minor_;
    ssl.set_preMaster(tmp, SECRET_LEN);

    const CertManager& cert = ssl.getCrypto().get_certManager();
    RSA rsa(cert.get_peerKey(), cert.get_peerKeyLength());
    bool tls = ssl.isTLS();     // if TLS, put length for encrypted data
    alloc(rsa.get_cipherLength() + (tls ? 2 : 0));
    byte* holder = secret_;
    if (tls) {
        byte len[2];
        c16toa(rsa.get_cipherLength(), len);
        memcpy(secret_, len, sizeof(len));
        holder += 2;
    }
    rsa.encrypt(holder, tmp, SECRET_LEN, ssl.getCrypto().get_random());
}


// build/set premaster and Client Public key, client side
void ClientDiffieHellmanPublic::build(SSL& ssl)
{
    DiffieHellman& dhServer = ssl.useCrypto().use_dh();
    DiffieHellman  dhClient(dhServer);

    uint keyLength = dhClient.get_agreedKeyLength(); // pub and agree same

    alloc(keyLength, true);
    dhClient.makeAgreement(dhServer.get_publicKey(), keyLength);
    c16toa(keyLength, Yc_);
    memcpy(Yc_ + KEY_OFFSET, dhClient.get_publicKey(), keyLength);

    // because of encoding first byte might be zero, don't use it for preMaster
    if (*dhClient.get_agreedKey() == 0) 
        ssl.set_preMaster(dhClient.get_agreedKey() + 1, keyLength - 1);
    else
    ssl.set_preMaster(dhClient.get_agreedKey(), keyLength);
}


// build server exhange, server side
void DH_Server::build(SSL& ssl)
{
    DiffieHellman& dhServer = ssl.useCrypto().use_dh();

    int pSz, gSz, pubSz;
    dhServer.set_sizes(pSz, gSz, pubSz);
    dhServer.get_parms(parms_.alloc_p(pSz), parms_.alloc_g(gSz),
                       parms_.alloc_pub(pubSz));

    short sigSz = 0;
    mySTL::auto_ptr<Auth> auth;
    const CertManager& cert = ssl.getCrypto().get_certManager();
    
    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo)
        auth.reset(NEW_YS RSA(cert.get_privateKey(),
                   cert.get_privateKeyLength(), false));
    else {
        auth.reset(NEW_YS DSS(cert.get_privateKey(),
                   cert.get_privateKeyLength(), false));
        sigSz += DSS_ENCODED_EXTRA;
    }
    
    sigSz += auth->get_signatureLength();
    if (!sigSz) {
        ssl.SetError(privateKey_error);
        return;
    }

    length_ = 8; // pLen + gLen + YsLen + SigLen
    length_ += pSz + gSz + pubSz + sigSz;

    output_buffer tmp(length_);
    byte len[2];
    // P
    c16toa(pSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_p(), pSz);
    // G
    c16toa(gSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_g(), gSz);
    // Ys
    c16toa(pubSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_pub(), pubSz);

    // Sig
    byte hash[FINISHED_SZ];
    MD5  md5;
    SHA  sha;
    signature_ = NEW_YS byte[sigSz];

    const Connection& conn = ssl.getSecurity().get_connection();
    // md5
    md5.update(conn.client_random_, RAN_LEN);
    md5.update(conn.server_random_, RAN_LEN);
    md5.update(tmp.get_buffer(), tmp.get_size());
    md5.get_digest(hash);

    // sha
    sha.update(conn.client_random_, RAN_LEN);
    sha.update(conn.server_random_, RAN_LEN);
    sha.update(tmp.get_buffer(), tmp.get_size());
    sha.get_digest(&hash[MD5_LEN]);

    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo)
        auth->sign(signature_, hash, sizeof(hash),
                   ssl.getCrypto().get_random());
    else {
        auth->sign(signature_, &hash[MD5_LEN], SHA_LEN,
                   ssl.getCrypto().get_random());
        byte encoded[DSS_SIG_SZ + DSS_ENCODED_EXTRA];
        TaoCrypt::EncodeDSA_Signature(signature_, encoded);
        memcpy(signature_, encoded, sizeof(encoded));
    }

    c16toa(sigSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(signature_, sigSz);

    // key message
    keyMessage_ = NEW_YS opaque[length_];
    memcpy(keyMessage_, tmp.get_buffer(), tmp.get_size());
}


// read PreMaster secret and decrypt, server side
void EncryptedPreMasterSecret::read(SSL& ssl, input_buffer& input)
{
    const CertManager& cert = ssl.getCrypto().get_certManager();
    RSA rsa(cert.get_privateKey(), cert.get_privateKeyLength(), false);
    uint16 cipherLen = rsa.get_cipherLength();
    if (ssl.isTLS()) {
        byte len[2];
        input.read(len, sizeof(len));
        ato16(len, cipherLen);
    }
    alloc(cipherLen);
    input.read(secret_, length_);

    opaque preMasterSecret[SECRET_LEN];
    rsa.decrypt(preMasterSecret, secret_, length_, 
                ssl.getCrypto().get_random());

    ProtocolVersion pv = ssl.getSecurity().get_connection().chVersion_;
    if (pv.major_ != preMasterSecret[0] || pv.minor_ != preMasterSecret[1])
        ssl.SetError(pms_version_error); // continue deriving for timing attack

    ssl.set_preMaster(preMasterSecret, SECRET_LEN);
    ssl.makeMasterSecret();
}


EncryptedPreMasterSecret::EncryptedPreMasterSecret()
    : secret_(0), length_(0)
{}


EncryptedPreMasterSecret::~EncryptedPreMasterSecret()
{
    ysArrayDelete(secret_);
}


int EncryptedPreMasterSecret::get_length() const
{
    return length_;
}


opaque* EncryptedPreMasterSecret::get_clientKey() const
{
    return secret_;
}


void EncryptedPreMasterSecret::alloc(int sz)
{
    length_ = sz;
    secret_ = NEW_YS opaque[sz];
}


// read client's public key, server side
void ClientDiffieHellmanPublic::read(SSL& ssl, input_buffer& input)
{
    DiffieHellman& dh = ssl.useCrypto().use_dh();

    uint16 keyLength;
    byte tmp[2];
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, keyLength);

    alloc(keyLength);
    input.read(Yc_, keyLength);
    dh.makeAgreement(Yc_, keyLength); 

    // because of encoding, first byte might be 0, don't use for preMaster 
    if (*dh.get_agreedKey() == 0) 
        ssl.set_preMaster(dh.get_agreedKey() + 1, dh.get_agreedKeyLength() - 1);
    else
        ssl.set_preMaster(dh.get_agreedKey(), dh.get_agreedKeyLength());
    ssl.makeMasterSecret();
}


ClientDiffieHellmanPublic::ClientDiffieHellmanPublic()
    : length_(0), Yc_(0)
{}


ClientDiffieHellmanPublic::~ClientDiffieHellmanPublic()
{
    ysArrayDelete(Yc_);
}


int ClientDiffieHellmanPublic::get_length() const
{
    return length_;
}


opaque* ClientDiffieHellmanPublic::get_clientKey() const
{
    return Yc_;
}


void ClientDiffieHellmanPublic::alloc(int sz, bool offset) 
{
    length_ = sz + (offset ? KEY_OFFSET : 0); 
    Yc_ = NEW_YS opaque[length_];
}


// read server's p, g, public key and sig, client side
void DH_Server::read(SSL& ssl, input_buffer& input)
{
    uint16 length, messageTotal = 6; // pSz + gSz + pubSz
    byte tmp[2];

    // p
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_p(length), length);

    // g
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_g(length), length);

    // pub
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_pub(length), length);

    // save message for hash verify
    input_buffer message(messageTotal);
    input.set_current(input.get_current() - messageTotal);
    input.read(message.get_buffer(), messageTotal);
    message.add_size(messageTotal);

    // signature
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);

    signature_ = NEW_YS byte[length];
    input.read(signature_, length);

    // verify signature
    byte hash[FINISHED_SZ];
    MD5  md5;
    SHA  sha;

    const Connection& conn = ssl.getSecurity().get_connection();
    // md5
    md5.update(conn.client_random_, RAN_LEN);
    md5.update(conn.server_random_, RAN_LEN);
    md5.update(message.get_buffer(), message.get_size());
    md5.get_digest(hash);

    // sha
    sha.update(conn.client_random_, RAN_LEN);
    sha.update(conn.server_random_, RAN_LEN);
    sha.update(message.get_buffer(), message.get_size());
    sha.get_digest(&hash[MD5_LEN]);

    const CertManager& cert = ssl.getCrypto().get_certManager();
    
    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo) {
        RSA rsa(cert.get_peerKey(), cert.get_peerKeyLength());
        if (!rsa.verify(hash, sizeof(hash), signature_, length))
            ssl.SetError(verify_error);
    }
    else {
        byte decodedSig[DSS_SIG_SZ];
        length = TaoCrypt::DecodeDSA_Signature(decodedSig, signature_, length);
        
        DSS dss(cert.get_peerKey(), cert.get_peerKeyLength());
        if (!dss.verify(&hash[MD5_LEN], SHA_LEN, decodedSig, length))
            ssl.SetError(verify_error);
    }

    // save input
    ssl.useCrypto().SetDH(NEW_YS DiffieHellman(parms_.get_p(),
               parms_.get_pSize(), parms_.get_g(), parms_.get_gSize(),
               parms_.get_pub(), parms_.get_pubSize(),
               ssl.getCrypto().get_random()));
}


DH_Server::DH_Server()
    : signature_(0), length_(0), keyMessage_(0)
{}


DH_Server::~DH_Server()
{
    ysArrayDelete(keyMessage_);
    ysArrayDelete(signature_);
}


int DH_Server::get_length() const
{
    return length_;
}


opaque* DH_Server::get_serverKey() const
{
    return keyMessage_;
}


// set available suites
Parameters::Parameters(ConnectionEnd ce, const Ciphers& ciphers, 
                       ProtocolVersion pv, bool haveDH) : entity_(ce)
{
    pending_ = true;	// suite not set yet
    strncpy(cipher_name_, "NONE", 5);

    if (ciphers.setSuites_) {   // use user set list
        suites_size_ = ciphers.suiteSz_;
        memcpy(suites_, ciphers.suites_, ciphers.suiteSz_);
        SetCipherNames();
    }
    else 
        SetSuites(pv, ce == server_end && !haveDH);  // defaults

}


void Parameters::SetSuites(ProtocolVersion pv, bool removeDH)
{
    int i = 0;
    // available suites, best first
    // when adding more, make sure cipher_names is updated and
    //      MAX_CIPHERS is big enough

    if (isTLS(pv)) {
        if (!removeDH) {
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_DSS_WITH_AES_256_CBC_SHA;
        }
        suites_[i++] = 0x00;
        suites_[i++] = TLS_RSA_WITH_AES_256_CBC_SHA;

        if (!removeDH) {
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_DSS_WITH_AES_128_CBC_SHA;
        }
        suites_[i++] = 0x00;
        suites_[i++] = TLS_RSA_WITH_AES_128_CBC_SHA;

        suites_[i++] = 0x00;
        suites_[i++] = TLS_RSA_WITH_AES_256_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_RSA_WITH_AES_128_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_RSA_WITH_3DES_EDE_CBC_RMD160;

        if (!removeDH) {
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_RSA_WITH_AES_256_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_RSA_WITH_AES_128_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160;

        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_DSS_WITH_AES_256_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_DSS_WITH_AES_128_CBC_RMD160;
        suites_[i++] = 0x00;
        suites_[i++] = TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160;
    }
    }

    suites_[i++] = 0x00;
    suites_[i++] = SSL_RSA_WITH_RC4_128_SHA;  
    suites_[i++] = 0x00;
    suites_[i++] = SSL_RSA_WITH_RC4_128_MD5;

    suites_[i++] = 0x00;
    suites_[i++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA;
    suites_[i++] = 0x00;
    suites_[i++] = SSL_RSA_WITH_DES_CBC_SHA;

    if (!removeDH) {
    suites_[i++] = 0x00;
    suites_[i++] = SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA;  
    suites_[i++] = 0x00;
    suites_[i++] = SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA; 

    suites_[i++] = 0x00;
    suites_[i++] = SSL_DHE_RSA_WITH_DES_CBC_SHA;  
    suites_[i++] = 0x00;
    suites_[i++] = SSL_DHE_DSS_WITH_DES_CBC_SHA;
    }

    suites_size_ = i;

    SetCipherNames();
}


void Parameters::SetCipherNames()
{
    const int suites = suites_size_ / 2;
    int pos = 0;

    for (int j = 0; j < suites; j++) {
        int index = suites_[j*2 + 1];  // every other suite is suite id
        int len = strlen(cipher_names[index]) + 1;
        strncpy(cipher_list_[pos++], cipher_names[index], len);
    }
    cipher_list_[pos][0] = 0;
}


// input operator for RecordLayerHeader, adjust stream
input_buffer& operator>>(input_buffer& input, RecordLayerHeader& hdr)
{
    hdr.type_ = ContentType(input[AUTO]);
    hdr.version_.major_ = input[AUTO];
    hdr.version_.minor_ = input[AUTO];

    // length
    byte tmp[2];
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, hdr.length_);

    return input;
}


// output operator for RecordLayerHeader
output_buffer& operator<<(output_buffer& output, const RecordLayerHeader& hdr)
{
    output[AUTO] = hdr.type_;
    output[AUTO] = hdr.version_.major_;
    output[AUTO] = hdr.version_.minor_;
    
    // length
    byte tmp[2];
    c16toa(hdr.length_, tmp);
    output[AUTO] = tmp[0];
    output[AUTO] = tmp[1];

    return output;
}


// virtual input operator for Messages
input_buffer& operator>>(input_buffer& input, Message& msg)
{
    return msg.set(input);
}

// virtual output operator for Messages
output_buffer& operator<<(output_buffer& output, const Message& msg)
{
    return msg.get(output);
}


// input operator for HandShakeHeader
input_buffer& operator>>(input_buffer& input, HandShakeHeader& hs)
{
    hs.type_ = HandShakeType(input[AUTO]);

    hs.length_[0] = input[AUTO];
    hs.length_[1] = input[AUTO];
    hs.length_[2] = input[AUTO];
    
    return input;
}


// output operator for HandShakeHeader
output_buffer& operator<<(output_buffer& output, const HandShakeHeader& hdr)
{
    output[AUTO] = hdr.type_;
    output.write(hdr.length_, sizeof(hdr.length_));
    return output;
}


// HandShake Header Processing function
void HandShakeHeader::Process(input_buffer& input, SSL& ssl)
{
    ssl.verifyState(*this);
    if (ssl.GetError()) return;
    const HandShakeFactory& hsf = ssl.getFactory().getHandShake();
    mySTL::auto_ptr<HandShakeBase> hs(hsf.CreateObject(type_));
    if (!hs.get()) {
        ssl.SetError(factory_error);
        return;
    }

    uint len = c24to32(length_);
    hashHandShake(ssl, input, len);

    hs->set_length(len);
    input >> *hs;
    hs->Process(input, ssl);
}


ContentType HandShakeHeader::get_type() const
{
    return handshake;
}


uint16 HandShakeHeader::get_length() const
{
    return c24to32(length_);
}


HandShakeType HandShakeHeader::get_handshakeType() const
{
    return type_;
}


void HandShakeHeader::set_type(HandShakeType hst)
{
    type_ = hst;
}


void HandShakeHeader::set_length(uint32 u32)
{
    c32to24(u32, length_);
}


input_buffer& HandShakeHeader::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& HandShakeHeader::get(output_buffer& out) const
{
    return out << *this;
}



int HandShakeBase::get_length() const
{
    return length_;
}


void HandShakeBase::set_length(int l)
{
    length_ = l;
}


// for building buffer's type field
HandShakeType HandShakeBase::get_type() const
{
    return no_shake;
}


input_buffer& HandShakeBase::set(input_buffer& in)
{
    return in;
}

 
output_buffer& HandShakeBase::get(output_buffer& out) const
{
    return out;
}


void HandShakeBase::Process(input_buffer&, SSL&) 
{}


input_buffer& HelloRequest::set(input_buffer& in)
{
    return in;
}


output_buffer& HelloRequest::get(output_buffer& out) const
{
    return out;
}


void HelloRequest::Process(input_buffer&, SSL&)
{}


HandShakeType HelloRequest::get_type() const
{
    return hello_request;
}


// input operator for CipherSpec
input_buffer& operator>>(input_buffer& input, ChangeCipherSpec& cs)
{
    cs.type_ = CipherChoice(input[AUTO]);
    return input; 
}

// output operator for CipherSpec
output_buffer& operator<<(output_buffer& output, const ChangeCipherSpec& cs)
{
    output[AUTO] = cs.type_;
    return output;
}


ChangeCipherSpec::ChangeCipherSpec() 
    : type_(change_cipher_spec_choice)
{}


input_buffer& ChangeCipherSpec::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& ChangeCipherSpec::get(output_buffer& out) const
{
    return out << *this;
}


ContentType ChangeCipherSpec::get_type() const
{
    return change_cipher_spec;
}


uint16 ChangeCipherSpec::get_length() const
{
    return SIZEOF_ENUM;
}


// CipherSpec processing handler
void ChangeCipherSpec::Process(input_buffer&, SSL& ssl)
{
    ssl.useSecurity().use_parms().pending_ = false;
    if (ssl.getSecurity().get_resuming()) {
        if (ssl.getSecurity().get_parms().entity_ == client_end)
            buildFinished(ssl, ssl.useHashes().use_verify(), server); // server
    }
    else if (ssl.getSecurity().get_parms().entity_ == server_end)
        buildFinished(ssl, ssl.useHashes().use_verify(), client);     // client
}


Alert::Alert(AlertLevel al, AlertDescription ad)
    : level_(al), description_(ad)
{}


ContentType Alert::get_type() const
{
    return alert;
}


uint16 Alert::get_length() const
{
    return SIZEOF_ENUM * 2;
}


input_buffer& Alert::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& Alert::get(output_buffer& out) const
{
    return out << *this;
}


// input operator for Alert
input_buffer& operator>>(input_buffer& input, Alert& a)
{
    a.level_ = AlertLevel(input[AUTO]);
    a.description_ = AlertDescription(input[AUTO]);
 
    return input;
}


// output operator for Alert
output_buffer& operator<<(output_buffer& output, const Alert& a)
{
    output[AUTO] = a.level_;
    output[AUTO] = a.description_;
    return output;
}


// Alert processing handler
void Alert::Process(input_buffer& input, SSL& ssl)
{
    if (ssl.getSecurity().get_parms().pending_ == false)  { // encrypted alert
        int            aSz = get_length();  // alert size already read on input
        opaque         verify[SHA_LEN];
        const  opaque* data = input.get_buffer() + input.get_current() - aSz;

        if (ssl.isTLS())
            TLS_hmac(ssl, verify, data, aSz, alert, true);
        else
            hmac(ssl, verify, data, aSz, alert, true);

        // read mac and fill
        int    digestSz = ssl.getCrypto().get_digest().get_digestSize();
        opaque mac[SHA_LEN];
        input.read(mac, digestSz);

        if (ssl.getSecurity().get_parms().cipher_type_ == block) {
            int    ivExtra = 0;
        opaque fill;

            if (ssl.isTLSv1_1())
                ivExtra = ssl.getCrypto().get_cipher().get_blockSize();
            int padSz = ssl.getSecurity().get_parms().encrypt_size_ - ivExtra -
                        aSz - digestSz;
        for (int i = 0; i < padSz; i++) 
            fill = input[AUTO];
        }

        // verify
        if (memcmp(mac, verify, digestSz)) {
            ssl.SetError(verify_error);
            return;
        }
    }
    if (level_ == fatal) {
        ssl.useStates().useRecord()    = recordNotReady;
        ssl.useStates().useHandShake() = handShakeNotReady;
        ssl.SetError(YasslError(description_));
    }
}


Data::Data()
    : length_(0), buffer_(0), write_buffer_(0)
{}


Data::Data(uint16 len, opaque* b)
    : length_(len), buffer_(b), write_buffer_(0)
{}


void Data::SetData(uint16 len, const opaque* buffer)
{
    assert(write_buffer_ == 0);

    length_ = len;
    write_buffer_ = buffer;
}

input_buffer& Data::set(input_buffer& in)
{
    return in;
}


output_buffer& Data::get(output_buffer& out) const
{
    return out << *this;
}


ContentType Data::get_type() const
{
    return application_data;
}


uint16 Data::get_length() const
{
    return length_;
}


void Data::set_length(uint16 l)
{
    length_ = l;
}


opaque* Data::set_buffer()
{
    return buffer_;
}


// output operator for Data
output_buffer& operator<<(output_buffer& output, const Data& data)
{
    output.write(data.write_buffer_, data.length_);
    return output;
}


// Process handler for Data
void Data::Process(input_buffer& input, SSL& ssl)
{
    int msgSz = ssl.getSecurity().get_parms().encrypt_size_;
    int pad   = 0, padByte = 0;
    int ivExtra = 0;

    if (ssl.getSecurity().get_parms().cipher_type_ == block) {
        if (ssl.isTLSv1_1())  // IV
            ivExtra = ssl.getCrypto().get_cipher().get_blockSize();
        pad = *(input.get_buffer() + input.get_current() + msgSz -ivExtra - 1);
        padByte = 1;
    }
    int digestSz = ssl.getCrypto().get_digest().get_digestSize();
    int dataSz = msgSz - ivExtra - digestSz - pad - padByte;   
    opaque verify[SHA_LEN];

    const byte* rawData = input.get_buffer() + input.get_current();

    // read data
    if (dataSz) {                               // could be compressed
        if (ssl.CompressionOn()) {
            input_buffer tmp;
            if (DeCompress(input, dataSz, tmp) == -1) {
                ssl.SetError(decompress_error);
                return;
            }
            ssl.addData(NEW_YS input_buffer(tmp.get_size(),
                                            tmp.get_buffer(), tmp.get_size()));
        }
        else {
        input_buffer* data;
        ssl.addData(data = NEW_YS input_buffer(dataSz));
        input.read(data->get_buffer(), dataSz);
        data->add_size(dataSz);
        }

        if (ssl.isTLS())
            TLS_hmac(ssl, verify, rawData, dataSz, application_data, true);
        else
            hmac(ssl, verify, rawData, dataSz, application_data, true);
    }

    // read mac and fill
    opaque mac[SHA_LEN];
    opaque fill;
    input.read(mac, digestSz);
    for (int i = 0; i < pad; i++) 
        fill = input[AUTO];
    if (padByte)
        fill = input[AUTO];    

    // verify
    if (dataSz) {
        if (memcmp(mac, verify, digestSz)) {
            ssl.SetError(verify_error);
            return;
        }
    }
    else 
        ssl.get_SEQIncrement(true);  // even though no data, increment verify
}


// virtual input operator for HandShakes
input_buffer& operator>>(input_buffer& input, HandShakeBase& hs)
{
    return hs.set(input);
}


// virtual output operator for HandShakes
output_buffer& operator<<(output_buffer& output, const HandShakeBase& hs)
{
    return hs.get(output);
}


Certificate::Certificate(const x509* cert) : cert_(cert) 
{
    set_length(cert_->get_length() + 2 * CERT_HEADER); // list and cert size
}


const opaque* Certificate::get_buffer() const
{
    return cert_->get_buffer(); 
}


// output operator for Certificate
output_buffer& operator<<(output_buffer& output, const Certificate& cert)
{
    uint sz = cert.get_length() - 2 * CERT_HEADER;
    opaque tmp[CERT_HEADER];

    c32to24(sz + CERT_HEADER, tmp);
    output.write(tmp, CERT_HEADER);
    c32to24(sz, tmp);
    output.write(tmp, CERT_HEADER);
    output.write(cert.get_buffer(), sz);

    return output;
}


// certificate processing handler
void Certificate::Process(input_buffer& input, SSL& ssl)
{
    CertManager& cm = ssl.useCrypto().use_certManager();
  
    uint32 list_sz;
    byte   tmp[3];

    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    tmp[2] = input[AUTO];
    c24to32(tmp, list_sz);
    
    while (list_sz) {
        // cert size
        uint32 cert_sz;
        tmp[0] = input[AUTO];
        tmp[1] = input[AUTO];
        tmp[2] = input[AUTO];
        c24to32(tmp, cert_sz);
        
        x509* myCert;
        cm.AddPeerCert(myCert = NEW_YS x509(cert_sz));
        input.read(myCert->use_buffer(), myCert->get_length());

        list_sz -= cert_sz + CERT_HEADER;
    }
    if (int err = cm.Validate())
        ssl.SetError(YasslError(err));
    else if (ssl.getSecurity().get_parms().entity_ == client_end)
        ssl.useStates().useClient() = serverCertComplete;
}


Certificate::Certificate()
    : cert_(0)
{}


input_buffer& Certificate::set(input_buffer& in)
{
    return in;
}


output_buffer& Certificate::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType Certificate::get_type() const
{
    return certificate;
}


ServerDHParams::ServerDHParams()
    : pSz_(0), gSz_(0), pubSz_(0), p_(0), g_(0), Ys_(0)
{}


ServerDHParams::~ServerDHParams()
{
    ysArrayDelete(Ys_);
    ysArrayDelete(g_);
    ysArrayDelete(p_);
}


int ServerDHParams::get_pSize() const
{
    return pSz_;
}


int ServerDHParams::get_gSize() const
{
    return gSz_;
}


int ServerDHParams::get_pubSize() const
{
    return pubSz_;
}


const opaque* ServerDHParams::get_p() const
{
    return p_;
}


const opaque* ServerDHParams::get_g() const
{
    return g_;
}


const opaque* ServerDHParams::get_pub() const
{
    return Ys_;
}


opaque* ServerDHParams::alloc_p(int sz)
{
    p_ = NEW_YS opaque[pSz_ = sz];
    return p_;
}


opaque* ServerDHParams::alloc_g(int sz)
{
    g_ = NEW_YS opaque[gSz_ = sz];
    return g_;
}


opaque* ServerDHParams::alloc_pub(int sz)
{
    Ys_ = NEW_YS opaque[pubSz_ = sz];
    return Ys_;
}


int ServerKeyBase::get_length() const
{
    return 0;
}


opaque* ServerKeyBase::get_serverKey() const
{
    return 0;
}


// input operator for ServerHello
input_buffer& operator>>(input_buffer& input, ServerHello& hello)
{ 
    // Protocol
    hello.server_version_.major_ = input[AUTO];
    hello.server_version_.minor_ = input[AUTO];
   
    // Random
    input.read(hello.random_, RAN_LEN);
    
    // Session
    hello.id_len_ = input[AUTO];
    if (hello.id_len_)
        input.read(hello.session_id_, hello.id_len_);
 
    // Suites
    hello.cipher_suite_[0] = input[AUTO];
    hello.cipher_suite_[1] = input[AUTO];
   
    // Compression
    hello.compression_method_ = CompressionMethod(input[AUTO]);

    return input;
}


// output operator for ServerHello
output_buffer& operator<<(output_buffer& output, const ServerHello& hello)
{
    // Protocol
    output[AUTO] = hello.server_version_.major_;
    output[AUTO] = hello.server_version_.minor_;

    // Random
    output.write(hello.random_, RAN_LEN);

    // Session
    output[AUTO] = hello.id_len_;
    output.write(hello.session_id_, ID_LEN);

    // Suites
    output[AUTO] = hello.cipher_suite_[0];
    output[AUTO] = hello.cipher_suite_[1];

    // Compression
    output[AUTO] = hello.compression_method_;

    return output;
}


// Server Hello processing handler
void ServerHello::Process(input_buffer&, SSL& ssl)
{
    if (ssl.GetMultiProtocol()) {   // SSLv23 support
        if (ssl.isTLS() && server_version_.minor_ < 1)
            // downgrade to SSLv3
            ssl.useSecurity().use_connection().TurnOffTLS();
        else if (ssl.isTLSv1_1() && server_version_.minor_ == 1)
            // downdrage to TLSv1
            ssl.useSecurity().use_connection().TurnOffTLS1_1();
    }
    else if (ssl.isTLSv1_1() && server_version_.minor_ < 2) {
        ssl.SetError(badVersion_error);
        return;
    }
    else if (ssl.isTLS() && server_version_.minor_ < 1) {
        ssl.SetError(badVersion_error);
        return;
    }
    else if (!ssl.isTLS() && (server_version_.major_ == 3 &&
                              server_version_.minor_ >= 1)) {
        ssl.SetError(badVersion_error);
        return;
    }
    ssl.set_pending(cipher_suite_[1]);
    ssl.set_random(random_, server_end);
    if (id_len_)
    ssl.set_sessionID(session_id_);
    else
        ssl.useSecurity().use_connection().sessionID_Set_ = false;

    if (ssl.getSecurity().get_resuming())
        if (memcmp(session_id_, ssl.getSecurity().get_resume().GetID(),
                   ID_LEN) == 0) {
            ssl.set_masterSecret(ssl.getSecurity().get_resume().GetSecret());
            if (ssl.isTLS())
                ssl.deriveTLSKeys();
            else
                ssl.deriveKeys();
            ssl.useStates().useClient() = serverHelloDoneComplete;
            return;
        }
        else {
            ssl.useSecurity().set_resuming(false);
            ssl.useLog().Trace("server denied resumption");
        }

    if (ssl.CompressionOn() && !compression_method_)
        ssl.UnSetCompression(); // server isn't supporting yaSSL zlib request

    ssl.useStates().useClient() = serverHelloComplete;
}


ServerHello::ServerHello()
{
    memset(random_, 0, RAN_LEN);
    memset(session_id_, 0, ID_LEN);
}


ServerHello::ServerHello(ProtocolVersion pv, bool useCompression)
    : server_version_(pv),
      compression_method_(useCompression ? zlib : no_compression)
{
    memset(random_, 0, RAN_LEN);
    memset(session_id_, 0, ID_LEN);
}


input_buffer& ServerHello::set(input_buffer& in)
{
    return in  >> *this;
}


output_buffer& ServerHello::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType ServerHello::get_type() const
{
    return server_hello;
}


const opaque* ServerHello::get_random() const
{
    return random_;
}


// Server Hello Done processing handler
void ServerHelloDone::Process(input_buffer&, SSL& ssl)
{
    ssl.useStates().useClient() = serverHelloDoneComplete;
}


ServerHelloDone::ServerHelloDone()
{
    set_length(0);
}


input_buffer& ServerHelloDone::set(input_buffer& in)
{
    return in;
}


output_buffer& ServerHelloDone::get(output_buffer& out) const
{
    return out;
}


HandShakeType ServerHelloDone::get_type() const
{
    return server_hello_done;
}


int ClientKeyBase::get_length() const
{
    return 0;
}


opaque* ClientKeyBase::get_clientKey() const
{
    return 0;
}


// input operator for Client Hello
input_buffer& operator>>(input_buffer& input, ClientHello& hello)
{
    uint begin = input.get_current();  // could have extensions at end

    // Protocol
    hello.client_version_.major_ = input[AUTO];
    hello.client_version_.minor_ = input[AUTO];

    // Random
    input.read(hello.random_, RAN_LEN);

    // Session
    hello.id_len_ = input[AUTO];
    if (hello.id_len_) input.read(hello.session_id_, ID_LEN);
    
    // Suites
    byte tmp[2];
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, hello.suite_len_);
    input.read(hello.cipher_suites_, hello.suite_len_);

    // Compression
    hello.comp_len_ = input[AUTO];
    hello.compression_methods_ = no_compression;
    while (hello.comp_len_--) {
        CompressionMethod cm = CompressionMethod(input[AUTO]);
        if (cm == zlib)
            hello.compression_methods_ = zlib;
    }

    uint read = input.get_current() - begin;
    uint expected = hello.get_length();

    // ignore client hello extensions for now
    if (read < expected)
        input.set_current(input.get_current() + expected - read);

    return input;
}


// output operaotr for Client Hello
output_buffer& operator<<(output_buffer& output, const ClientHello& hello)
{ 
    // Protocol
    output[AUTO] = hello.client_version_.major_;
    output[AUTO] = hello.client_version_.minor_;

    // Random
    output.write(hello.random_, RAN_LEN);

    // Session
    output[AUTO] = hello.id_len_;
    if (hello.id_len_) output.write(hello.session_id_, ID_LEN);

    // Suites
    byte tmp[2];
    c16toa(hello.suite_len_, tmp);
    output[AUTO] = tmp[0];
    output[AUTO] = tmp[1];
    output.write(hello.cipher_suites_, hello.suite_len_);
  
    // Compression
    output[AUTO] = hello.comp_len_;
    output[AUTO] = hello.compression_methods_;

    return output;
}


// Client Hello processing handler
void ClientHello::Process(input_buffer&, SSL& ssl)
{
    // store version for pre master secret
    ssl.useSecurity().use_connection().chVersion_ = client_version_;

    if (client_version_.major_ != 3) {
        ssl.SetError(badVersion_error);
        return;
    }
    if (ssl.GetMultiProtocol()) {   // SSLv23 support
        if (ssl.isTLS() && client_version_.minor_ < 1) {
            // downgrade to SSLv3
        ssl.useSecurity().use_connection().TurnOffTLS();
        ProtocolVersion pv = ssl.getSecurity().get_connection().version_;
        ssl.useSecurity().use_parms().SetSuites(pv);  // reset w/ SSL suites
    }
        else if (ssl.isTLSv1_1() && client_version_.minor_ == 1)
            // downgrade to TLSv1, but use same suites
            ssl.useSecurity().use_connection().TurnOffTLS1_1();
    }
    else if (ssl.isTLSv1_1() && client_version_.minor_ < 2) {
        ssl.SetError(badVersion_error);
        return;
    }
    else if (ssl.isTLS() && client_version_.minor_ < 1) {
        ssl.SetError(badVersion_error);
        return;
    }
    else if (!ssl.isTLS() && client_version_.minor_ >= 1) {
        ssl.SetError(badVersion_error);
        return;
    }

    ssl.set_random(random_, client_end);

    while (id_len_) {  // trying to resume
        SSL_SESSION* session = 0;
        if (!ssl.getSecurity().GetContext()->GetSessionCacheOff())
            session = GetSessions().lookup(session_id_);
        if (!session)  {
            ssl.useLog().Trace("session lookup failed");
            break;
        }
        ssl.set_session(session);
        ssl.useSecurity().set_resuming(true);
        ssl.matchSuite(session->GetSuite(), SUITE_LEN);
        ssl.set_pending(ssl.getSecurity().get_parms().suite_[1]);
        ssl.set_masterSecret(session->GetSecret());

        opaque serverRandom[RAN_LEN];
        ssl.getCrypto().get_random().Fill(serverRandom, sizeof(serverRandom));
        ssl.set_random(serverRandom, server_end);
        if (ssl.isTLS())
            ssl.deriveTLSKeys();
        else
            ssl.deriveKeys();
        ssl.useStates().useServer() = clientKeyExchangeComplete;
        return;
    }
    ssl.matchSuite(cipher_suites_, suite_len_);
    ssl.set_pending(ssl.getSecurity().get_parms().suite_[1]);

    if (compression_methods_ == zlib)
        ssl.SetCompression();

    ssl.useStates().useServer() = clientHelloComplete;
}


input_buffer& ClientHello::set(input_buffer& in)
{
    return in  >> *this;
}


output_buffer& ClientHello::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType ClientHello::get_type() const
{
    return client_hello;
}


const opaque* ClientHello::get_random() const
{
    return random_;
}


ClientHello::ClientHello()
{
    memset(random_, 0, RAN_LEN);
}


ClientHello::ClientHello(ProtocolVersion pv, bool useCompression)
    : client_version_(pv),
      compression_methods_(useCompression ? zlib : no_compression)
{
    memset(random_, 0, RAN_LEN);
}


// output operator for ServerKeyExchange
output_buffer& operator<<(output_buffer& output, const ServerKeyExchange& sk)
{
    output.write(sk.getKey(), sk.getKeyLength());
    return output;
}


// Server Key Exchange processing handler
void ServerKeyExchange::Process(input_buffer& input, SSL& ssl)
{
    createKey(ssl);
    if (ssl.GetError()) return;
    server_key_->read(ssl, input);

    ssl.useStates().useClient() = serverKeyExchangeComplete;
}


ServerKeyExchange::ServerKeyExchange(SSL& ssl)
{
    createKey(ssl);
}


ServerKeyExchange::ServerKeyExchange()
    : server_key_(0)
{}


ServerKeyExchange::~ServerKeyExchange()
{
    ysDelete(server_key_);
}


void ServerKeyExchange::build(SSL& ssl) 
{ 
    server_key_->build(ssl); 
    set_length(server_key_->get_length());
}


const opaque* ServerKeyExchange::getKey() const
{
    return server_key_->get_serverKey();
}


int ServerKeyExchange::getKeyLength() const
{
    return server_key_->get_length();
}


input_buffer& ServerKeyExchange::set(input_buffer& in)
{
    return in;      // process does
}


output_buffer& ServerKeyExchange::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType ServerKeyExchange::get_type() const
{
    return server_key_exchange;
}


// CertificateRequest 
CertificateRequest::CertificateRequest()
    : typeTotal_(0)
{
    memset(certificate_types_, 0, sizeof(certificate_types_));
}


CertificateRequest::~CertificateRequest()
{

    STL::for_each(certificate_authorities_.begin(),
                  certificate_authorities_.end(),
                  del_ptr_zero()) ;
}


void CertificateRequest::Build()
{
    certificate_types_[0] = rsa_sign;
    certificate_types_[1] = dss_sign;

    typeTotal_ = 2;

    uint16 authCount = 0;
    uint16 authSz = 0;
  
    for (int j = 0; j < authCount; j++) {
        int sz = REQUEST_HEADER + MIN_DIS_SIZE;
        DistinguishedName dn;
        certificate_authorities_.push_back(dn = NEW_YS byte[sz]);

        opaque tmp[REQUEST_HEADER];
        c16toa(MIN_DIS_SIZE, tmp);
        memcpy(dn, tmp, sizeof(tmp));
  
        // fill w/ junk for now
        memcpy(dn, tmp, MIN_DIS_SIZE);
        authSz += sz;
    }

    set_length(SIZEOF_ENUM + typeTotal_ + REQUEST_HEADER + authSz);
}


input_buffer& CertificateRequest::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& CertificateRequest::get(output_buffer& out) const
{
    return out << *this;
}


// input operator for CertificateRequest
input_buffer& operator>>(input_buffer& input, CertificateRequest& request)
{
    // types
    request.typeTotal_ = input[AUTO];
    for (int i = 0; i < request.typeTotal_; i++)
        request.certificate_types_[i] = ClientCertificateType(input[AUTO]);

    byte tmp[REQUEST_HEADER];
    input.read(tmp, sizeof(tmp));
    uint16 sz;
    ato16(tmp, sz);

    // authorities
    while (sz) {
        uint16 dnSz;
        input.read(tmp, sizeof(tmp));
        ato16(tmp, dnSz);
        
        DistinguishedName dn;
        request.certificate_authorities_.push_back(dn = NEW_YS 
                                                  byte[REQUEST_HEADER + dnSz]);
        memcpy(dn, tmp, REQUEST_HEADER);
        input.read(&dn[REQUEST_HEADER], dnSz);

        sz -= dnSz + REQUEST_HEADER;
    }

    return input;
}


// output operator for CertificateRequest
output_buffer& operator<<(output_buffer& output,
                          const CertificateRequest& request)
{
    // types
    output[AUTO] = request.typeTotal_;
    for (int i = 0; i < request.typeTotal_; i++)
        output[AUTO] = request.certificate_types_[i];

    // authorities
    opaque tmp[REQUEST_HEADER];
    c16toa(request.get_length() - SIZEOF_ENUM -
           request.typeTotal_ - REQUEST_HEADER, tmp);
    output.write(tmp, sizeof(tmp));

    STL::list<DistinguishedName>::const_iterator first =
                                    request.certificate_authorities_.begin();
    STL::list<DistinguishedName>::const_iterator last =
                                    request.certificate_authorities_.end();
    while (first != last) {
        uint16 sz;
        ato16(*first, sz);
        output.write(*first, sz + REQUEST_HEADER);

        ++first;
    }

    return output;
}


// CertificateRequest processing handler
void CertificateRequest::Process(input_buffer&, SSL& ssl)
{
    CertManager& cm = ssl.useCrypto().use_certManager();

    // make sure user provided cert and key before sending and using
    if (cm.get_cert() && cm.get_privateKey())
        cm.setSendVerify();
}


HandShakeType CertificateRequest::get_type() const
{
    return certificate_request;
}


// CertificateVerify 
CertificateVerify::CertificateVerify() : signature_(0)
{}


CertificateVerify::~CertificateVerify()
{
    ysArrayDelete(signature_);
}


void CertificateVerify::Build(SSL& ssl)
{
    build_certHashes(ssl, hashes_);

    uint16 sz = 0;
    byte   len[VERIFY_HEADER];
    mySTL::auto_array<byte> sig;

    // sign
    const CertManager& cert = ssl.getCrypto().get_certManager();
    if (cert.get_keyType() == rsa_sa_algo) {
        RSA rsa(cert.get_privateKey(), cert.get_privateKeyLength(), false);

        sz = rsa.get_cipherLength() + VERIFY_HEADER;
        sig.reset(NEW_YS byte[sz]);

        c16toa(sz - VERIFY_HEADER, len);
        memcpy(sig.get(), len, VERIFY_HEADER);
        rsa.sign(sig.get() + VERIFY_HEADER, hashes_.md5_, sizeof(Hashes),
                 ssl.getCrypto().get_random());
    }
    else {  // DSA
        DSS dss(cert.get_privateKey(), cert.get_privateKeyLength(), false);

        sz = DSS_SIG_SZ + DSS_ENCODED_EXTRA + VERIFY_HEADER;
        sig.reset(NEW_YS byte[sz]);

        c16toa(sz - VERIFY_HEADER, len);
        memcpy(sig.get(), len, VERIFY_HEADER);
        dss.sign(sig.get() + VERIFY_HEADER, hashes_.sha_, SHA_LEN,
                 ssl.getCrypto().get_random());

        byte encoded[DSS_SIG_SZ + DSS_ENCODED_EXTRA];
        TaoCrypt::EncodeDSA_Signature(sig.get() + VERIFY_HEADER, encoded);
        memcpy(sig.get() + VERIFY_HEADER, encoded, sizeof(encoded));
    }
    set_length(sz);
    signature_ = sig.release();
}


input_buffer& CertificateVerify::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& CertificateVerify::get(output_buffer& out) const
{
    return out << *this;
}


// input operator for CertificateVerify
input_buffer& operator>>(input_buffer& input, CertificateVerify& request)
{
    byte tmp[VERIFY_HEADER];
    input.read(tmp, sizeof(tmp));

    uint16 sz = 0;
    ato16(tmp, sz);
    request.set_length(sz);

    request.signature_ = NEW_YS byte[sz];
    input.read(request.signature_, sz);

    return input;
}


// output operator for CertificateVerify
output_buffer& operator<<(output_buffer& output,
                          const CertificateVerify& verify)
{
    output.write(verify.signature_, verify.get_length());

    return output;
}


// CertificateVerify processing handler
void CertificateVerify::Process(input_buffer&, SSL& ssl)
{
    const Hashes&      hashVerify = ssl.getHashes().get_certVerify();
    const CertManager& cert       = ssl.getCrypto().get_certManager();

    if (cert.get_peerKeyType() == rsa_sa_algo) {
        RSA rsa(cert.get_peerKey(), cert.get_peerKeyLength());

        if (!rsa.verify(hashVerify.md5_, sizeof(hashVerify), signature_,
                        get_length()))
            ssl.SetError(verify_error);
    }
    else { // DSA
        byte decodedSig[DSS_SIG_SZ];
        TaoCrypt::DecodeDSA_Signature(decodedSig, signature_, get_length());
        
        DSS dss(cert.get_peerKey(), cert.get_peerKeyLength());
        if (!dss.verify(hashVerify.sha_, SHA_LEN, decodedSig, get_length()))
            ssl.SetError(verify_error);
    }
}


HandShakeType CertificateVerify::get_type() const
{
    return certificate_verify;
}


// output operator for ClientKeyExchange
output_buffer& operator<<(output_buffer& output, const ClientKeyExchange& ck)
{
    output.write(ck.getKey(), ck.getKeyLength());
    return output;
}


// Client Key Exchange processing handler
void ClientKeyExchange::Process(input_buffer& input, SSL& ssl)
{
    createKey(ssl);
    if (ssl.GetError()) return;
    client_key_->read(ssl, input);

    if (ssl.getCrypto().get_certManager().verifyPeer())
        build_certHashes(ssl, ssl.useHashes().use_certVerify());

    ssl.useStates().useServer() = clientKeyExchangeComplete;
}


ClientKeyExchange::ClientKeyExchange(SSL& ssl)
{
    createKey(ssl);
}


ClientKeyExchange::ClientKeyExchange()
    : client_key_(0)
{}


ClientKeyExchange::~ClientKeyExchange()
{
    ysDelete(client_key_);
}


void ClientKeyExchange::build(SSL& ssl) 
{ 
    client_key_->build(ssl); 
    set_length(client_key_->get_length());
}

const opaque* ClientKeyExchange::getKey() const
{
    return client_key_->get_clientKey();
}


int ClientKeyExchange::getKeyLength() const
{
    return client_key_->get_length();
}


input_buffer& ClientKeyExchange::set(input_buffer& in)
{
    return in;
}


output_buffer& ClientKeyExchange::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType ClientKeyExchange::get_type() const
{
    return client_key_exchange;
}


// input operator for Finished
input_buffer& operator>>(input_buffer& input, Finished&)
{
    /*  do in process */

    return input; 
}

// output operator for Finished
output_buffer& operator<<(output_buffer& output, const Finished& fin)
{
    if (fin.get_length() == FINISHED_SZ) {
        output.write(fin.hashes_.md5_, MD5_LEN);
        output.write(fin.hashes_.sha_, SHA_LEN);
    }
    else    // TLS_FINISHED_SZ
        output.write(fin.hashes_.md5_, TLS_FINISHED_SZ);

    return output;
}


// Finished processing handler
void Finished::Process(input_buffer& input, SSL& ssl)
{
    // verify hashes
    const  Finished& verify = ssl.getHashes().get_verify();
    uint finishedSz = ssl.isTLS() ? TLS_FINISHED_SZ : FINISHED_SZ;

    input.read(hashes_.md5_, finishedSz);

    if (memcmp(&hashes_, &verify.hashes_, finishedSz)) {
        ssl.SetError(verify_error);
        return;
    }

    // read verify mac
    opaque verifyMAC[SHA_LEN];
    uint macSz = finishedSz + HANDSHAKE_HEADER;

    if (ssl.isTLS())
        TLS_hmac(ssl, verifyMAC, input.get_buffer() + input.get_current()
                 - macSz, macSz, handshake, true);
    else
        hmac(ssl, verifyMAC, input.get_buffer() + input.get_current() - macSz,
             macSz, handshake, true);

    // read mac and fill
    opaque mac[SHA_LEN];   // max size
    int    digestSz = ssl.getCrypto().get_digest().get_digestSize();
    input.read(mac, digestSz);

    uint ivExtra = 0;
    if (ssl.getSecurity().get_parms().cipher_type_ == block)
        if (ssl.isTLSv1_1())
            ivExtra = ssl.getCrypto().get_cipher().get_blockSize();

    opaque fill;
    int    padSz = ssl.getSecurity().get_parms().encrypt_size_ - ivExtra -
                     HANDSHAKE_HEADER - finishedSz - digestSz;
    for (int i = 0; i < padSz; i++) 
        fill = input[AUTO];

    // verify mac
    if (memcmp(mac, verifyMAC, digestSz)) {
        ssl.SetError(verify_error);
        return;
    }

    // update states
    ssl.useStates().useHandShake() = handShakeReady;
    if (ssl.getSecurity().get_parms().entity_ == client_end)
        ssl.useStates().useClient() = serverFinishedComplete;
    else
        ssl.useStates().useServer() = clientFinishedComplete;
}


Finished::Finished()
{
    set_length(FINISHED_SZ);
}


uint8* Finished::set_md5()
{
    return hashes_.md5_;
}


uint8* Finished::set_sha()
{
    return hashes_.sha_;
}


input_buffer& Finished::set(input_buffer& in)
{
    return in  >> *this;
}


output_buffer& Finished::get(output_buffer& out) const
{
    return out << *this;
}


HandShakeType Finished::get_type() const
{
    return finished;
}


void clean(volatile opaque* p, uint sz, RandomPool& ran)
{
    uint i(0);

    for (i = 0; i < sz; ++i)
        p[i] = 0;

    ran.Fill(const_cast<opaque*>(p), sz);

    for (i = 0; i < sz; ++i)
        p[i] = 0;
}



Connection::Connection(ProtocolVersion v, RandomPool& ran)
    : pre_master_secret_(0), sequence_number_(0), peer_sequence_number_(0),
      pre_secret_len_(0), send_server_key_(false), master_clean_(false),
      TLS_(v.major_ >= 3 && v.minor_ >= 1),
      TLSv1_1_(v.major_ >= 3 && v.minor_ >= 2), compression_(false),
      version_(v), random_(ran)
{
    memset(sessionID_, 0, sizeof(sessionID_));
}


Connection::~Connection() 
{ 
    CleanMaster(); CleanPreMaster(); ysArrayDelete(pre_master_secret_);
}


void Connection::AllocPreSecret(uint sz) 
{ 
    pre_master_secret_ = NEW_YS opaque[pre_secret_len_ = sz];
}


void Connection::TurnOffTLS()
{
    TLS_ = false;
    version_.minor_ = 0;
}


void Connection::TurnOffTLS1_1()
{
    TLSv1_1_ = false;
    version_.minor_ = 1;
}


// wipeout master secret
void Connection::CleanMaster()
{
    if (!master_clean_) {
        volatile opaque* p = master_secret_;
        clean(p, SECRET_LEN, random_);
        master_clean_ = true;
    }
}


// wipeout pre master secret
void Connection::CleanPreMaster()
{
    if (pre_master_secret_) {
        volatile opaque* p = pre_master_secret_;
        clean(p, pre_secret_len_, random_);

        ysArrayDelete(pre_master_secret_);
        pre_master_secret_ = 0;
    }
}


// Create functions for message factory
Message* CreateCipherSpec() { return NEW_YS ChangeCipherSpec; }
Message* CreateAlert()      { return NEW_YS Alert; }
Message* CreateHandShake()  { return NEW_YS HandShakeHeader; }
Message* CreateData()       { return NEW_YS Data; }

// Create functions for handshake factory
HandShakeBase* CreateHelloRequest()       { return NEW_YS HelloRequest; }
HandShakeBase* CreateClientHello()        { return NEW_YS ClientHello; }
HandShakeBase* CreateServerHello()        { return NEW_YS ServerHello; }
HandShakeBase* CreateCertificate()        { return NEW_YS Certificate; }
HandShakeBase* CreateServerKeyExchange()  { return NEW_YS ServerKeyExchange;}
HandShakeBase* CreateCertificateRequest() { return NEW_YS 
                                                    CertificateRequest; }
HandShakeBase* CreateServerHelloDone()    { return NEW_YS ServerHelloDone; }
HandShakeBase* CreateCertificateVerify()  { return NEW_YS CertificateVerify;}
HandShakeBase* CreateClientKeyExchange()  { return NEW_YS ClientKeyExchange;}
HandShakeBase* CreateFinished()           { return NEW_YS Finished; }

// Create functions for server key exchange factory
ServerKeyBase* CreateRSAServerKEA()       { return NEW_YS RSA_Server; }
ServerKeyBase* CreateDHServerKEA()        { return NEW_YS DH_Server; }
ServerKeyBase* CreateFortezzaServerKEA()  { return NEW_YS Fortezza_Server; }

// Create functions for client key exchange factory
ClientKeyBase* CreateRSAClient()      { return NEW_YS 
                                                EncryptedPreMasterSecret; }
ClientKeyBase* CreateDHClient()       { return NEW_YS 
                                                ClientDiffieHellmanPublic; }
ClientKeyBase* CreateFortezzaClient() { return NEW_YS FortezzaKeys; }


// Constructor calls this to Register compile time callbacks
void InitMessageFactory(MessageFactory& mf)
{
    mf.Reserve(4);
    mf.Register(alert, CreateAlert);
    mf.Register(change_cipher_spec, CreateCipherSpec);
    mf.Register(handshake, CreateHandShake);
    mf.Register(application_data, CreateData);
}


// Constructor calls this to Register compile time callbacks
void InitHandShakeFactory(HandShakeFactory& hsf)
{
    hsf.Reserve(10);
    hsf.Register(hello_request, CreateHelloRequest);
    hsf.Register(client_hello, CreateClientHello);
    hsf.Register(server_hello, CreateServerHello);
    hsf.Register(certificate, CreateCertificate);
    hsf.Register(server_key_exchange, CreateServerKeyExchange);
    hsf.Register(certificate_request, CreateCertificateRequest);
    hsf.Register(server_hello_done, CreateServerHelloDone);
    hsf.Register(certificate_verify, CreateCertificateVerify);
    hsf.Register(client_key_exchange, CreateClientKeyExchange);
    hsf.Register(finished, CreateFinished);
}


// Constructor calls this to Register compile time callbacks
void InitServerKeyFactory(ServerKeyFactory& skf)
{
    skf.Reserve(3);
    skf.Register(rsa_kea, CreateRSAServerKEA);
    skf.Register(diffie_hellman_kea, CreateDHServerKEA);
    skf.Register(fortezza_kea, CreateFortezzaServerKEA);
}


// Constructor calls this to Register compile time callbacks
void InitClientKeyFactory(ClientKeyFactory& ckf)
{
    ckf.Reserve(3);
    ckf.Register(rsa_kea, CreateRSAClient);
    ckf.Register(diffie_hellman_kea, CreateDHClient);
    ckf.Register(fortezza_kea, CreateFortezzaClient);
}


} // namespace