File: Cipher.pmod

package info (click to toggle)
pike8.0 8.0.1956-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 60,580 kB
  • sloc: ansic: 259,734; xml: 36,320; makefile: 3,748; sh: 1,713; cpp: 1,349; awk: 1,036; lisp: 655; javascript: 468; asm: 242; objc: 240; pascal: 157; sed: 34
file content (1907 lines) | stat: -rw-r--r-- 52,777 bytes parent folder | download | duplicates (6)
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
#pike __REAL_VERSION__
#require constant(Crypto.Hash)

//! Encryption and MAC algorithms used in SSL.

import .Constants;

#ifdef SSL3_DEBUG
#define SSL3_DEBUG_MSG(X ...)  werror(X)
#else /*! SSL3_DEBUG */
#define SSL3_DEBUG_MSG(X ...)
#endif /* SSL3_DEBUG */


// A mapping from DH p to DH q to effort verification level to
// indicate if a DH group with a specific p and q is valid or not. -1
// means failed validation.
protected mapping(Gmp.mpz:mapping(Gmp.mpz:int)) valid_dh;
protected int valid_dh_count;

protected mapping(Gmp.mpz:mapping(Gmp.mpz:int)) make_valid_dh()
{
  mapping dh = ([]);
  foreach(values(Crypto.DH), mixed m)
  {
    if(!objectp(m)) continue;
    object o = [object]m;
    if(m->p && m->q)
      dh[m->p] = ([ m->q : Int.NATIVE_MAX ]);
  }
  return dh;
}

protected bool validate_dh(Crypto.DH.Parameters dh, object session)
{
  if( !valid_dh || valid_dh_count > 1000 )
  {
    valid_dh = make_valid_dh();
    valid_dh_count = 0;
  }

  // Spend more effort validating q when in anonymous KE. These two
  // effort values should possibly be part of the context.
  int effort = 0;
  if( session->cipher_spec->signature_alg == SIGNATURE_anonymous )
    effort = 8; // Misses non-prime with 0.0015% probability.

  mapping pmap = valid_dh[dh->p];
  if( pmap )
  {
    if( has_index(pmap, dh->q) )
      return pmap[dh->q] >= effort;
  }
  else
    valid_dh[dh->p] = ([]);

  if( !dh->validate(effort) )
    effort = -1;

  valid_dh[dh->p][dh->q] = effort;
  valid_dh_count++;
  return effort > -1;
}

//! Cipher algorithm interface.
class CipherAlgorithm {
  this_program set_encrypt_key(string);
  this_program set_decrypt_key(string);
  //! Set the key used for encryption/decryption, and
  //! enter encryption mode.

  int(0..) block_size();
  //! Return the block size for this crypto.

  optional string crypt(string);
  optional string unpad(string,int);
  optional string pad(int);

  optional this_program set_iv(string);
}

//! Message Authentication Code interface.
class MACAlgorithm {

  //! Generates a header and creates a HMAC hash for the given
  //! @[packet].
  //! @param packet
  //!   @[Packet] to generate a MAC hash for.
  //! @param seq_num
  //!   Sequence number for the packet in the stream.
  //! @param adjust_len
  //!   Added to @tt{sizeof(packet)@} to get the packet length.
  //! @returns
  //!   Returns the MAC hash for the @[packet].
  string hash_packet(object packet, int seq_num, int|void adjust_len);

  //! Creates a HMAC hash of the @[data] with the underlying hash
  //! algorithm.
  string hash(string data);

  //! Creates a normal hash of the @[data] using the underlying hash
  //! algorithm.
  string hash_raw(string data);

  //! The block size of the underlying hash algorithm.
  int block_size();

  //! The length of the header prefixed by @[hash()].
  constant hash_header_size = 13;
}

//! Cipher specification.
class CipherSpec {

  //! Key exchange factory.
  program(KeyExchange) ke_factory;

  //! The algorithm to use for the bulk of the transfered data.
  program(CipherAlgorithm) bulk_cipher_algorithm;

  int cipher_type;

  //! The Message Authentication Code to use for the packets.
  program(MACAlgorithm) mac_algorithm;

  //! Indication whether the combination uses strong or weak
  //! (aka exportable) crypto.
  int is_exportable;

  //! The number of bytes in the MAC hashes.
  int hash_size;

  //! The number of bytes of key material used on initialization.
  int key_material;

  //! The number of bytes of random data needed for initialization vectors.
  int iv_size;

  //! The number of bytes of explicit data needed for initialization vectors.
  //! This is used by AEAD ciphers, where there's a secret part of the iv
  //! "salt" of length @[iv_size], and an explicit part that is sent in
  //! the clear.
  //!
  //! This is usually @expr{bulk_cipher_algorithm->iv_size() - iv_size@},
  //! but may be set to zero to just have the sequence number expanded
  //! to the same size as an implicit iv. This is used by the suites
  //! with @[Crypto.ChaCha20.POLY1305].
  int explicit_iv_size;

  //! The effective number of bits in @[key_material].
  //!
  //! This is typically @expr{key_material * 8@}, but for eg @[DES]
  //! this is @expr{key_material * 7@}.
  int key_bits;

  //! The Pseudo Random Function to use.
  //!
  //! @seealso
  //!   @[prf_ssl_3_0()], @[prf_tls_1_0()], @[prf_tls_1_2()]
  function(string(8bit), string(8bit), string(8bit), int:string(8bit)) prf;

  //! The hash algorithm for signing the handshake.
  //!
  //! Usually the same hash as is the base for the @[prf].
  //!
  //! @note
  //!   Only used in TLS 1.2 and later.
  Crypto.Hash hash;

  //! The hash algorithm used for key exchange signatures.
  HashAlgorithm signature_hash = HASH_sha;

  //! The signature algorithm used for key exchange signatures.
  SignatureAlgorithm signature_alg;

  //! The function used to sign packets.
  ADT.struct sign(object session, string(8bit) cookie, ADT.struct struct)
  {
    if( signature_alg == SIGNATURE_anonymous )
      return struct;

    // RFC 5246 4.7
    if( session->version >= PROTOCOL_TLS_1_2 )
    {
      string sign =
        session->private_key->pkcs_sign(cookie + struct->contents(),
                                        HASH_lookup[signature_hash]);
      struct->put_uint(signature_hash, 1);
      struct->put_uint(signature_alg, 1);
      struct->put_var_string(sign, 2);
      return struct;
    }

    // RFC 4346 7.4.3 (struct Signature)
    string data = cookie + struct->contents();
    switch( signature_alg )
    {
    case SIGNATURE_rsa:
      {
        string digest = Crypto.MD5->hash(data) + Crypto.SHA1->hash(data);
        struct->add_hint(session->private_key->raw_sign(digest), 2);
        return struct;
      }

    case SIGNATURE_dsa:
    case SIGNATURE_ecdsa:
      {
        string s =
          session->private_key->pkcs_sign(cookie + struct->contents(),
                                          Crypto.SHA1);
        struct->put_var_string(s, 2);
        return struct;
      }
    }

    error("Internal error");
  }

  //! The function used to verify the signature for packets.
  int(0..1) verify(object session, string cookie, ADT.struct struct,
                   ADT.struct input)
  {
    if( signature_alg == SIGNATURE_anonymous )
      return 1;

    Crypto.Sign.State pkc = session->peer_public_key;
    if( !pkc ) return 0;

    // RFC 5246 4.7
    if( session->version >= PROTOCOL_TLS_1_2 )
    {
      int hash_id = input->get_uint(1);
      int sign_id = input->get_uint(1);
      string sign = input->get_var_string(2);

      Crypto.Hash hash = HASH_lookup[hash_id];
      if (!hash) return 0;

      // FIXME: Validate that the sign_id is correct.

      return pkc->pkcs_verify(cookie + struct->contents(), hash, sign);
    }

    // RFC 4346 7.4.3 (struct Signature)
    string data = cookie + struct->contents();
    switch( signature_alg )
    {
    case SIGNATURE_rsa:
      {
        string digest = Crypto.MD5->hash(data) + Crypto.SHA1->hash(data);
        // FIXME: We could check that the signature is encoded
        // (padded) to the correct number of bytes
        // (pkc->private_key->key_size()/8).
        Gmp.mpz signature = input->get_bignum();
        return pkc->raw_verify(digest, signature);
      }

    case SIGNATURE_dsa:
    case SIGNATURE_ecdsa:
      {
        return pkc->pkcs_verify(data, Crypto.SHA1,
                                input->get_var_string(2));
      }
    }

    error("Internal error");
  }

  void set_hash(int max_hash_size,
                array(array(int)) signature_algorithms,
                int wanted_hash_id)
  {
    // Stay with SHA1 for requests without signature algorithms
    // extensions (RFC 5246 7.4.1.4.1) and anonymous requests.
    if( signature_alg == SIGNATURE_anonymous || !signature_algorithms )
      return;

    int hash_id = -1;
    SSL3_DEBUG_MSG("Signature algorithms (max hash size %d):\n%s",
                   max_hash_size, fmt_signature_pairs(signature_algorithms));
    foreach(signature_algorithms, array(int) pair) {
      if ((pair[1] == signature_alg) && HASH_lookup[pair[0]]) {
        if (pair[0] == wanted_hash_id) {
          // Use the required hash from Suite B if available.
          hash_id = wanted_hash_id;
          break;
        }
        if (max_hash_size < HASH_lookup[pair[0]]->digest_size()) {
          // Eg RSA has a maximum block size and the digest is too large.
          continue;
        }
        if (pair[0] > hash_id) {
          hash_id = pair[0];
        }
      }
    }

    if (signature_hash == -1)
      error("No acceptable hash algorithm.\n");
    signature_hash = hash_id;

    SSL3_DEBUG_MSG("Selected <%s, %s>\n",
                   fmt_constant(signature_hash, "HASH"),
                   fmt_constant(signature_alg, "SIGNATURE"));
  }
}

//! KeyExchange method base class.
class KeyExchange(object context, object session, object connection,
		  ProtocolVersion client_version)
{
  //! Indicates whether a certificate isn't required.
  int anonymous;

  //! Indicates whether the key exchange has failed due to bad MACs.
  int message_was_bad;

  //! @returns
  //!   Returns an @[ADT.struct] with the
  //!   @[HANDSHAKE_server_key_exchange] payload.
  ADT.struct server_key_params();

  //! The default implementation calls @[server_key_params()] to generate
  //! the base payload.
  //!
  //! @returns
  //!   Returns the signed payload for a @[HANDSHAKE_server_key_exchange].
  string server_key_exchange_packet(string client_random, string server_random)
  {
    ADT.struct struct = server_key_params();
    if (!struct) return 0;

    session->cipher_spec->sign(session, client_random + server_random, struct);
    return struct->pop_data();
  }

  //! Derive the master secret from the premaster_secret
  //! and the random seeds.
  //!
  //! @returns
  //!   Returns the master secret.
  string derive_master_secret(string premaster_secret,
			      string client_random,
			      string server_random,
			      ProtocolVersion version)
  {
    string res = "";

    SSL3_DEBUG_MSG("KeyExchange: in derive_master_secret is version=0x%x\n",
		   version);

    res = session->cipher_spec->prf(premaster_secret, "master secret",
				    client_random + server_random, 48);

    connection->ke = UNDEFINED;

    SSL3_DEBUG_MSG("master: %O\n", res);
    return res;
  }

  //! @returns
  //!   Returns the payload for a @[HANDSHAKE_client_key_exchange] packet.
  //!   May return @expr{0@} (zero) to generate an @[ALERT_unexpected_message].
  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version);

  //! @param data
  //!   Payload from a @[HANDSHAKE_client_key_exchange].
  //!
  //! @returns
  //!   Master secret or alert number.
  //!
  //! @note
  //!   May set @[message_was_bad] and return a fake master secret.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
						 string(8bit) client_random,
						 string(8bit) server_random,
						 ProtocolVersion version);

  //! @param input
  //!   @[ADT.struct] with the content of a @[HANDSHAKE_server_key_exchange].
  //!
  //! @returns
  //!   The key exchange information should be extracted from @[input],
  //!   so that it is positioned at the signature.
  //!
  //!   Returns a new @[ADT.struct] with the unsigned payload of @[input].
  ADT.struct parse_server_key_exchange(ADT.struct input);

  //! @param input
  //!   @[ADT.struct] with the content of a @[HANDSHAKE_server_key_exchange].
  //!
  //! The default implementation calls @[parse_server_key_exchange()],
  //! and then verifies the signature.
  //!
  //! @returns
  //!   @int
  //!     @value 0
  //!       Returns zero on success.
  //!     @value -1
  //!       Returns negative on verification failure.
  //!   @endint
  int server_key_exchange(ADT.struct input,
			  string client_random,
			  string server_random)
  {
    SSL3_DEBUG_MSG("SSL.Session: SERVER_KEY_EXCHANGE\n");

    ADT.struct temp_struct = parse_server_key_exchange(input);
    int verification_ok;

    if(temp_struct)
    {
      mixed err = catch {
          verification_ok = session->cipher_spec->verify(
            session, client_random + server_random, temp_struct, input);
        };
#ifdef SSL3_DEBUG
      if( err ) {
        master()->handle_error(err);
      }
#endif
    }

    if (!verification_ok)
    {
      connection->ke = UNDEFINED;
      return -1;
    }
    return 0;
  }
}

//! Key exchange for @[KE_null].
//!
//! This is the NULL @[KeyExchange], which is only used for the
//! @[SSL_null_with_null_null] cipher suite, which is usually disabled.
class KeyExchangeNULL
{
  inherit KeyExchange;

  ADT.struct server_key_params()
  {
    return ADT.struct();
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    anonymous = 1;
    session->master_secret = "";
    return "";
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit) server_derive_master_secret(string(8bit) data,
                                           string(8bit) client_random,
                                           string(8bit) server_random,
                                           ProtocolVersion version)
  {
    anonymous = 1;
    return "";
  }

  int server_key_exchange(ADT.struct input,
			  string client_random,
			  string server_random)
  {
    return 0;
  }
}

//! Key exchange for @[KE_rsa].
//!
//! @[KeyExchange] that uses the Rivest Shamir Adelman algorithm.
class KeyExchangeRSA
{
  inherit KeyExchange;

  Crypto.RSA temp_key; /* Key used for session key exchange (if not the same
			* as the server's certified key) */

  ADT.struct server_key_params()
  {
    ADT.struct struct;
  
    SSL3_DEBUG_MSG("KE_RSA\n");
    if (session->cipher_spec->is_exportable)
    {
      /* Send a ServerKeyExchange message. */

      if (temp_key = context->short_rsa) {
	if (--context->short_rsa_counter <= 0) {
	  context->short_rsa = UNDEFINED;
	}
      } else {
	// RFC 2246 D.1:
	// For typical electronic commerce applications, it is suggested
	// that keys be changed daily or every 500 transactions, and more
	// often if possible.

	// Now >10 years later, an aging laptop is capable of generating
	// >75 512-bit RSA keys per second, and clients requiring
	// export suites are getting far between, so rotating the key
	// after 5 uses seems ok. When the key generation rate reaches
	// ~250/second, I believe rotating the key every transaction
	// will be feasible.
	//	/grubba 2014-03-23
	SSL3_DEBUG_MSG("Generating a new ephemeral 512-bit RSA key.\n");
	context->short_rsa_counter = 5 - 1;
	context->short_rsa = temp_key = Crypto.RSA()->generate_key(512);
      }

      SSL3_DEBUG_MSG("Sending a server key exchange-message, "
		     "with a %d-bits key.\n", temp_key->key_size());
      struct = ADT.struct();
      struct->put_bignum(temp_key->get_n());
      struct->put_bignum(temp_key->get_e());
    }
    else
      return 0;

    return struct;
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("client_key_exchange_packet(%O, %O, %d.%d)\n",
		   client_random, server_random, version>>8, version & 0xff);
    ADT.struct struct = ADT.struct();
    string data;
    string premaster_secret;

    SSL3_DEBUG_MSG("KE_RSA\n");
    // NOTE: To protect against version roll-back attacks,
    //       the version sent here MUST be the same as the
    //       one in the initial handshake!
    struct->put_uint(client_version, 2);
    struct->put_fix_string( context->random(46) );
    premaster_secret = struct->pop_data();

    SSL3_DEBUG_MSG("temp_key: %O\n"
		   "session->peer_public_key: %O\n",
		   temp_key, session->peer_public_key);
    data = (temp_key || session->peer_public_key)->encrypt(premaster_secret);

    if(version >= PROTOCOL_TLS_1_0)
      data = sprintf("%2H", [string(8bit)]data);

    session->master_secret = derive_master_secret(premaster_secret,
						  client_random,
						  server_random,
						  version);
    return data;
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
                                                     string(8bit) client_random,
                                                     string(8bit) server_random,
                                                     ProtocolVersion version)
  {
    string premaster_secret;

    SSL3_DEBUG_MSG("server_derive_master_secret: ke_method %d\n",
		   session->ke_method);

    SSL3_DEBUG_MSG("KE_RSA\n");
    /* Decrypt the premaster_secret */
    SSL3_DEBUG_MSG("encrypted premaster_secret: %O\n", data);
    SSL3_DEBUG_MSG("temp_key: %O\n"
		   "session->private_key: %O\n",
		   temp_key, session->private_key);
    string rest = "";
    if(version >= PROTOCOL_TLS_1_0)
      sscanf(data, "%2H%s", data, rest);
    // Decrypt, even when we know data is incorrect, for time invariance.
    premaster_secret = (temp_key || session->private_key)->decrypt(data) ||
      "xx";

    SSL3_DEBUG_MSG("premaster_secret: %O\n", premaster_secret);

    // We want both branches to execute in equal time (ignoring
    // SSL3_DEBUG in the hope it is never on in production).
    // Workaround documented in RFC 2246.
    if ( `+( sizeof(rest),
             (sizeof(premaster_secret) != 48),
             (premaster_secret[0] != 3),
             (premaster_secret[1] != (client_version & 0xff)) ))
    {
      /* To avoid the chosen ciphertext attack discovered by Daniel
       * Bleichenbacher, it is essential not to send any error
       * messages back to the client until after the client's
       * Finished-message (or some other invalid message) has been
       * received.
       */
      /* Also checks for version roll-back attacks.
       */
#ifdef SSL3_DEBUG
      werror("SSL.ServerConnection: Invalid premaster_secret! "
	     "A chosen ciphertext attack?\n");
      if (premaster_secret && sizeof(premaster_secret) > 2) {
	werror("SSL.ServerConnection: Strange version (%d.%d) detected in "
	       "key exchange message (expected %d.%d).\n",
	       premaster_secret[0], premaster_secret[1],
	       client_version>>8, client_version & 0xff);
      }
#endif

      premaster_secret = context->random(48);
      message_was_bad = 1;
      connection->ke = UNDEFINED;

    } else {
      string timing_attack_mitigation = context->random(48);
      message_was_bad = 0;
      connection->ke = this;
    }

    return derive_master_secret(premaster_secret, client_random, server_random,
				version);
  }

  ADT.struct parse_server_key_exchange(ADT.struct input)
  {
    ADT.struct temp_struct = ADT.struct();

    SSL3_DEBUG_MSG("KE_RSA\n");
    Gmp.mpz n = input->get_bignum();
    Gmp.mpz e = input->get_bignum();
    temp_struct->put_bignum(n);
    temp_struct->put_bignum(e);
    if (session->cipher_spec->is_exportable) {
      temp_key = Crypto.RSA()->set_public_key(n, e);
    }

    return temp_struct;
  }
}

//! Key exchange for @[KE_dh_dss] and @[KE_dh_dss].
//!
//! @[KeyExchange] that uses Diffie-Hellman with a key from
//! a DSS certificate.
class KeyExchangeDH
{
  inherit KeyExchange;

  DHKeyExchange dh_state; /* For diffie-hellman key exchange */

  ADT.struct server_key_params()
  {
    ADT.struct struct;

    SSL3_DEBUG_MSG("KE_DH\n");
    // anonymous, not used on the server, but here for completeness.
    anonymous = 1;
    struct = ADT.struct();

    dh_state = DHKeyExchange(Crypto.DH.Parameters(session->private_key));
    dh_state->secret = session->private_key->get_x();

    // RFC 4346 7.4.3:
    // It is not legal to send the server key exchange message for the
    // following key exchange methods:
    //
    //   RSA
    //   DH_DSS
    //   DH_RSA
    return 0;
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("client_key_exchange_packet(%O, %O, %d.%d)\n",
		   client_random, server_random, version>>8, version & 0xff);
    ADT.struct struct = ADT.struct();
    string data;
    string premaster_secret;

    SSL3_DEBUG_MSG("KE_DH\n");
    anonymous = 1;
    if (!dh_state) {
      Crypto.DH.Parameters p = Crypto.DH.Parameters(session->peer_public_key);
      if( !validate_dh(p, session) )
      {
        SSL3_DEBUG_MSG("DH parameters not correct or not secure.\n");
        return 0;
      }
      dh_state = DHKeyExchange(p);
      if (!dh_state->set_other(session->peer_public_key->get_y())) {
	SSL3_DEBUG_MSG("DH Ys not valid for set parameters.\n");
	dh_state = 0;
	return 0;
      }
    }
    dh_state->new_secret(context->random);
    struct->put_bignum(dh_state->our);
    data = struct->pop_data();
    premaster_secret = dh_state->get_shared()->digits(256);

    session->master_secret =
      derive_master_secret(premaster_secret, client_random, server_random,
			   version);
    return data;
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
						 string(8bit) client_random,
						 string(8bit) server_random,
						 ProtocolVersion version)
  {
    string premaster_secret;

    SSL3_DEBUG_MSG("server_derive_master_secret: ke_method %d\n",
		   session->ke_method);

    SSL3_DEBUG_MSG("KE_DH\n");
    anonymous = 1;

    /* Explicit encoding */
    ADT.struct struct = ADT.struct(data);

    if (catch
      {
	if (!dh_state->set_other(struct->get_bignum())) {
	  connection->ke = UNDEFINED;
	  return ALERT_handshake_failure;
	}
      } || sizeof(struct))
    {
      connection->ke = UNDEFINED;
      return ALERT_handshake_failure;
    }

    premaster_secret = dh_state->get_shared()->digits(256);
    dh_state = 0;

    return derive_master_secret(premaster_secret, client_random, server_random,
				version);
  }

  ADT.struct parse_server_key_exchange(ADT.struct input)
  {
    SSL3_DEBUG_MSG("KE_DH\n");
    // RFC 4346 7.4.3:
    // It is not legal to send the server key exchange message for the
    // following key exchange methods:
    //
    //   RSA
    //   DH_DSS
    //   DH_RSA
    error("Invalid message.\n");
  }
}

//! KeyExchange for @[KE_dhe_rsa], @[KE_dhe_dss] and @[KE_dh_anon].
//!
//! KeyExchange that uses Diffie-Hellman to generate an Ephemeral key.
class KeyExchangeDHE
{
  inherit KeyExchangeDH;

  ADT.struct server_key_params()
  {
    ADT.struct struct;

    SSL3_DEBUG_MSG("KE_DHE\n");
    // anonymous, not used on the server, but here for completeness.
    anonymous = 1;
    struct = ADT.struct();

    // NIST SP800-57 5.6.1
    // { symmetric key length, p limit, q limit }
    constant nist_strength = ({
      ({ 80,   1024, 160 }),
      ({ 112,  2048, 224 }),
      ({ 128,  3072, 256 }),
      ({ 192,  7680, 384 }),
      ({ 256, 15360, 511 }),
    });
    int key_strength = CIPHER_effective_keylengths
      [ CIPHER_SUITES[ session->cipher_suite ][1] ];
    int target_p, target_q;
    foreach(nist_strength, [int key, target_p, target_q])
      if( key_strength <= key ) break;

    Crypto.DH.Parameters p;
    foreach( context->dh_groups, Crypto.DH.Parameters o )
    {
      if( !p || o->p->size()>p->p->size() ||
          (o->p->size()==p->p->size() && o->q->size()>p->q->size()) )
        p = o;
      if( p->p->size() >= target_p && p->q->size() >= target_q )
        break;
    }

    if(!p) error("No suitable DH group in Context.\n");
    dh_state = DHKeyExchange(p);
    dh_state->new_secret(context->random);

    struct->put_bignum(dh_state->parameters->p);
    struct->put_bignum(dh_state->parameters->g);
    struct->put_bignum(dh_state->our);

    return struct;
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
						 string(8bit) client_random,
						 string(8bit) server_random,
						 ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("server_derive_master_secret: ke_method %d\n",
		   session->ke_method);

    SSL3_DEBUG_MSG("KE_DHE\n");

    if (!sizeof(data))
    {
      /* Implicit encoding; Should never happen unless we have
       * requested and received a client certificate of type
       * rsa_fixed_dh or dss_fixed_dh. Not supported. */
      SSL3_DEBUG_MSG("SSL.ServerConnection: Client uses implicit encoding if its DH-value.\n"
		     "               Hanging up.\n");
      connection->ke = UNDEFINED;
      return ALERT_certificate_unknown;
    }

    return ::server_derive_master_secret(data, client_random, server_random,
					 version);
  }

  ADT.struct parse_server_key_exchange(ADT.struct input)
  {
    ADT.struct temp_struct = ADT.struct();

    SSL3_DEBUG_MSG("KE_DHE\n");
    Gmp.mpz p = input->get_bignum();
    Gmp.mpz g = input->get_bignum();
    Crypto.DH.Parameters params = Crypto.DH.Parameters(p, g);
    if( !validate_dh(params, session) )
    {
      SSL3_DEBUG_MSG("DH parameters not correct or not secure.\n");
      return 0;
    }
    temp_struct->put_bignum(p);
    temp_struct->put_bignum(g);
    dh_state = DHKeyExchange(params);
    if (!dh_state->set_other(input->get_bignum())) {
      SSL3_DEBUG_MSG("DH Ys not valid for set parameters.\n");
      dh_state = 0;
      return 0;
    }
    temp_struct->put_bignum(dh_state->other);

    return temp_struct;
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("KE_DHE\n");
    if (!dh_state) {
      SSL3_DEBUG_MSG("Missing server key exchange packet.\n");
      return 0;
    }
    return ::client_key_exchange_packet(client_random, server_random, version);
  }
}

#if constant(Crypto.ECC.Curve)
//! KeyExchange for @[KE_ecdh_rsa] and @[KE_ecdh_ecdsa].
//!
//! NB: The only difference between the two is whether the certificate
//!     is signed with RSA or ECDSA.
//!
//! This KeyExchange uses the Elliptic Curve parameters from
//! the ECDSA certificate on the server side, and ephemeral
//! parameters on the client side.
class KeyExchangeECDH
{
  inherit KeyExchange;

  protected Gmp.mpz get_server_secret()
  {
    return session->private_key->get_private_key();
  }

  protected Gmp.mpz get_server_pubx()
  {
    return session->peer_public_key->get_x();
  }

  protected Gmp.mpz get_server_puby()
  {
    return session->peer_public_key->get_y();
  }

  ADT.struct server_key_params()
  {
    SSL3_DEBUG_MSG("KE_ECDH\n");
    // RFC 4492 2.1:
    // A ServerKeyExchange MUST NOT be sent (the server's certificate
    // contains all the necessary keying information required by the client
    // to arrive at the premaster secret).
    return 0;
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("client_key_exchange_packet(%O, %O, %d.%d)\n",
		   client_random, server_random, version>>8, version & 0xff);
    ADT.struct struct = ADT.struct();
    string data;
    string premaster_secret;

    SSL3_DEBUG_MSG("KE_ECDH\n");

    Gmp.mpz secret = session->curve->new_scalar(context->random);
    Crypto.ECC.Curve.Point p = session->curve * secret;

    struct->put_var_string(p->encode(), 1);

    data = struct->pop_data();

    Gmp.mpz pubx = get_server_pubx();
    Gmp.mpz puby = get_server_puby();

    // RFC 4492 5.10:
    // Note that this octet string (Z in IEEE 1363 terminology) as
    // output by FE2OSP, the Field Element to Octet String
    // Conversion Primitive, has constant length for any given
    // field; leading zeros found in this octet string MUST NOT be
    // truncated.
    premaster_secret =
      sprintf("%*c",
	      (session->curve->size() + 7)>>3,
	      session->curve->point_mul(pubx, puby, secret)->get_x());
    secret = 0;

    session->master_secret =
      derive_master_secret(premaster_secret, client_random, server_random,
			   version);
    return data;
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
						 string(8bit) client_random,
						 string(8bit) server_random,
						 ProtocolVersion version)
  {
    SSL3_DEBUG_MSG("server_derive_master_secret: ke_method %d\n",
		   session->ke_method);

    SSL3_DEBUG_MSG("KE_ECDH\n");

    if (!sizeof(data))
    {
      /* Implicit encoding; Should never happen unless we have
       * requested and received a client certificate of type
       * rsa_fixed_dh or dss_fixed_dh. Not supported. */
      SSL3_DEBUG_MSG("SSL.ServerConnection: Client uses implicit encoding if its DH-value.\n"
		     "               Hanging up.\n");
      connection->ke = UNDEFINED;
      return ALERT_certificate_unknown;
    }

    string premaster_secret;

    /* Explicit encoding */
    ADT.struct struct = ADT.struct(data);

    object point = session->curve->Point(struct->get_var_string(1));
    Gmp.mpz secret = get_server_secret();
    // RFC 4492 5.10:
    // Note that this octet string (Z in IEEE 1363 terminology) as
    // output by FE2OSP, the Field Element to Octet String
    // Conversion Primitive, has constant length for any given
    // field; leading zeros found in this octet string MUST NOT be
    // truncated.

    premaster_secret =
      sprintf("%*c", (session->curve->size() + 7)>>3, (point*secret)->get_x());

    return derive_master_secret(premaster_secret, client_random, server_random,
				version);
  }

  ADT.struct parse_server_key_exchange(ADT.struct input)
  {
    SSL3_DEBUG_MSG("KE_ECDH\n");
    // RFC 4492 2.1:
    // A ServerKeyExchange MUST NOT be sent (the server's certificate
    // contains all the necessary keying information required by the client
    // to arrive at the premaster secret).
    error("Invalid message.\n");
  }
}

//! KeyExchange for @[KE_ecdhe_rsa] and @[KE_ecdhe_ecdsa].
//!
//! KeyExchange that uses Elliptic Curve Diffie-Hellman to
//! generate an Ephemeral key.
class KeyExchangeECDHE
{
  inherit KeyExchangeECDH;

  protected Gmp.mpz secret;
  protected Gmp.mpz pubx;
  protected Gmp.mpz puby;

  protected Gmp.mpz get_server_secret()
  {
    return secret;
  }

  protected Gmp.mpz get_server_pubx()
  {
    return pubx;
  }

  protected Gmp.mpz get_server_puby()
  {
    return puby;
  }

  ADT.struct server_key_params()
  {
    ADT.struct struct;

    SSL3_DEBUG_MSG("KE_ECDHE\n");
    // anonymous, not used on the server, but here for completeness.
    anonymous = 1;
    struct = ADT.struct();

    // Select a suitable curve.
    int c;
    switch(session->cipher_spec->key_bits) {
    case 257..:
      c = CURVE_secp521r1;
      break;
    case 129..256:
      // Suite B requires SECP384r1/SHA256 for AES-256
      c = CURVE_secp384r1;
      break;
    case ..128:
      // Suite B requires SECP256r1/SHA256 for AES-128
      c = CURVE_secp256r1;
      break;
    }

    if (!has_value(session->ecc_curves, c)) {
      // Preferred curve not available -- Select the strongest available.
      c = session->ecc_curves[0];
    }
    session->curve = ECC_CURVES[c];

    SSL3_DEBUG_MSG("Curve: %s: %O\n", fmt_constant(c, "CURVE"), session->curve);

    secret = session->curve->new_scalar(context->random);
    Crypto.ECC.Curve.Point p = session->curve * secret;

    SSL3_DEBUG_MSG("secret: %O\n", secret);
    SSL3_DEBUG_MSG("x: %O\n", p->get_x());
    SSL3_DEBUG_MSG("y: %O\n", p->get_y());

    struct->put_uint(CURVETYPE_named_curve, 1);
    struct->put_uint(c, 2);
    struct->put_var_string(p->encode(), 1);
    return struct;
  }

  string client_key_exchange_packet(string client_random,
				    string server_random,
				    ProtocolVersion version)
  {
    anonymous = 1;
    if (!pubx || !puby) {
      SSL3_DEBUG_MSG("Missing server key exchange packet.\n");
      return 0;
    }
    return ::client_key_exchange_packet(client_random, server_random, version);
  }

  //! @returns
  //!   Master secret or alert number.
  string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data,
						 string(8bit) client_random,
						 string(8bit) server_random,
						 ProtocolVersion version)
  {
    anonymous = 1;
    return ::server_derive_master_secret(data, client_random,
					 server_random, version);
  }

  ADT.struct parse_server_key_exchange(ADT.struct input)
  {
    SSL3_DEBUG_MSG("KE_ECDHE\n");

    ADT.struct temp_struct = ADT.struct();

    // First the curve.
    switch(input->get_uint(1)) {
    case CURVETYPE_named_curve:
      temp_struct->put_uint(CURVETYPE_named_curve, 1);
      int c = input->get_uint(2);
      temp_struct->put_uint(c, 2);
      if (has_value(context->ecc_curves, c)) {
	// Only look up curves that we are configured to support.
	session->curve = ECC_CURVES[c];
      }
      if (!session->curve) {
	connection->ke = UNDEFINED;
	error("Unsupported curve: %s.\n", fmt_constant(c, "GROUP"));
      }
      SSL3_DEBUG_MSG("Curve: %O (%O: %s)\n",
		     session->curve, c, fmt_constant(c, "GROUP"));
      break;
    default:
      connection->ke = UNDEFINED;
      error("Invalid curve encoding.\n");
      break;
    }

    // Then the point.
    string raw;
    object point = session->curve->Point(raw = input->get_var_string(1));
    pubx = point->get_x();
    puby = point->get_y();
    temp_struct->put_var_string(raw, 1);

    return temp_struct;
  }
}

#endif /* Crypto.ECC.Curve */

//! MAC using SHA.
//!
//! @note
//!   Note: This uses the algorithm from the SSL 3.0 draft.
class MACsha
{
  inherit MACAlgorithm;

  protected constant pad_1 = "6" * 40;
  protected constant pad_2 = "\\" * 40;

  protected Crypto.Hash algorithm = Crypto.SHA1;
  protected string secret;

  constant hash_header_size = 11;

  string(8bit) hash_raw(string(8bit) data)
  {
    return algorithm->hash(data);
  }

  string(8bit) hash_packet(object packet, int seq_num, int|void adjust_len)
  {
    string s = sprintf("%8c%c%2c", seq_num,
		       packet->content_type,
		       sizeof(packet->fragment) + adjust_len);
    Crypto.Hash.State h = algorithm();
    h->update(secret);
    h->update(pad_1);
    h->update(s);
    h->update(packet->fragment);
    return hash_raw(secret + pad_2 + h->digest());
  }

  string(8bit) hash(string(8bit) data)
  {
    return hash_raw(secret + pad_2 +
		hash_raw(data + secret + pad_1));
  }

  int(1..) block_size()
  {
    return algorithm->block_size();
  }

  protected void create (string|void s)
  {
    secret = s || "";
  }
}

//! MAC using MD5.
//!
//! @note
//!   Note: This uses the algorithm from the SSL 3.0 draft.
class MACmd5 {
  inherit MACsha;

  protected constant pad_1 = "6" * 48;
  protected constant pad_2 = "\\" * 48;

  protected Crypto.Hash algorithm = Crypto.MD5;
}

//! HMAC using SHA.
//!
//! This is the MAC algorithm used by TLS 1.0 and later.
class MAChmac_sha {
  inherit MACAlgorithm;

  protected Crypto.Hash algorithm = Crypto.SHA1;
  protected Crypto.MAC.State hmac;

  constant hash_header_size = 13;

  string hash_raw(string data)
  {
    return algorithm->hash(data);
  }

  string hash(string data)
  {
    return hmac(data);
  }

  string hash_packet(object packet, int seq_num, int|void adjust_len)
  {
    hmac->update( sprintf("%8c%c%2c%2c", seq_num,
                          packet->content_type,
                          packet->protocol_version,
                          sizeof(packet->fragment) + adjust_len));
    hmac->update( packet->fragment );
    return hmac->digest();
  }

  int(1..) block_size()
  {
    return algorithm->block_size();
  }

  //!
  protected void create(string|void s) {
    hmac = algorithm->HMAC( s||"" );
  }
}

//! HMAC using MD5.
//!
//! This is the MAC algorithm used by TLS 1.0 and later.
class MAChmac_md5 {
  inherit MAChmac_sha;
  protected Crypto.Hash algorithm = Crypto.MD5;
}

//! HMAC using SHA256.
//!
//! This is the MAC algorithm used by some cipher suites in TLS 1.2 and later.
class MAChmac_sha256 {
  inherit MAChmac_sha;
  protected Crypto.Hash algorithm = Crypto.SHA256;
}

#if constant(Crypto.SHA384)
//! HMAC using SHA384.
//!
//! This is a MAC algorithm used by some cipher suites in TLS 1.2 and later.
class MAChmac_sha384 {
  inherit MAChmac_sha;
  protected Crypto.Hash algorithm = Crypto.SHA384;
}
#endif

#if constant(Crypto.SHA512)
//! HMAC using SHA512.
//!
//! This is a MAC algorithm used by some cipher suites in TLS 1.2 and later.
class MAChmac_sha512 {
  inherit MAChmac_sha;
  protected Crypto.Hash algorithm = Crypto.SHA512;
}
#endif

//! Hashfn is either a @[Crypto.MD5], @[Crypto.SHA] or @[Crypto.SHA256].
protected string(8bit) P_hash(Crypto.Hash hashfn,
                              string(8bit) secret,
                              string(8bit) seed, int len)
{
  Crypto.MAC.State hmac=hashfn->HMAC(secret);
  string temp=seed;
  string res="";

  while( sizeof(res)<len )
  {
    temp=hmac(temp);
    res+=hmac(temp+seed);
  }
  return res[..(len-1)];
} 

//! This Pseudo Random Function is used to derive secret keys in SSL 3.0.
//!
//! @note
//!   The argument @[label] is ignored.
string(8bit) prf_ssl_3_0(string(8bit) secret,
                         string(8bit) label,
                         string(8bit) seed,
                         int len)
{
  string res = "";
  for (int i = 1; sizeof(res) < len; i++) {
    string cookie = (string)allocate(i, i + 64);
    res += Crypto.MD5.hash(secret +
			   Crypto.SHA1.hash(cookie + secret + seed));
  }
  return res[..len-1];
}

//! This Pseudo Random Function is used to derive secret keys
//! in TLS 1.0 and 1.1.
string(8bit) prf_tls_1_0(string(8bit) secret,
                         string(8bit) label,
                         string(8bit) seed,
                         int len)
{
  string s1=secret[..(int)(ceil(sizeof(secret)/2.0)-1)];
  string s2=secret[(int)(floor(sizeof(secret)/2.0))..];

  string a=P_hash(Crypto.MD5, s1, label+seed, len);
  string b=P_hash(Crypto.SHA1, s2, label+seed, len);

  return a ^ b;
}

//! This Pseudo Random Function is used to derive secret keys in TLS 1.2.
string(8bit) prf_tls_1_2(string(8bit) secret,
                         string(8bit) label,
                         string(8bit) seed,
                         int len)
{
  return P_hash(Crypto.SHA256, secret, label + seed, len);
}

#if constant(Crypto.SHA384)
//! This Pseudo Random Function is used to derive secret keys
//! for some ciphers suites defined after TLS 1.2.
string(8bit) prf_sha384(string(8bit) secret,
                        string(8bit) label,
                        string(8bit) seed,
                        int len)
{
  return P_hash(Crypto.SHA384, secret, label + seed, len);
}
#endif

#if constant(Crypto.SHA512)
//! This Pseudo Random Function could be used to derive secret keys
//! for some ciphers suites defined after TLS 1.2.
string(8bit) prf_sha512(string(8bit) secret,
                        string(8bit) label,
                        string(8bit) seed,
                        int len)
{
  return P_hash(Crypto.SHA512, secret, label + seed, len);
}
#endif

//!
class DES
{
  inherit Crypto.DES.CBC.Buffer.State;

  this_program set_encrypt_key(string k)
  {
    ::set_encrypt_key(Crypto.DES.fix_parity(k));
    return this;
  }

  this_program set_decrypt_key(string k)
  {
    ::set_decrypt_key(Crypto.DES.fix_parity(k));
    return this;
  }
}

//!
class DES3
{
  inherit Crypto.DES3.CBC.Buffer.State;

  this_program set_encrypt_key(string k)
  {
    ::set_encrypt_key(Crypto.DES3.fix_parity(k));
    return this;
  }

  this_program set_decrypt_key(string k)
  {
    ::set_decrypt_key(Crypto.DES3.fix_parity(k));
    return this;
  }
}

#if constant(Crypto.Arctwo)
//!
class RC2
{
  inherit Crypto.Arctwo.CBC.Buffer.State;

  this_program set_encrypt_key(string k)
  {
    ::set_encrypt_key(k, 128);
    return this;
  }

  this_program set_decrypt_key(string k)
  {
    ::set_decrypt_key(k, 128);
    return this;
  }
}
#endif /* Crypto.Arctwo */

//! Implements Diffie-Hellman key-exchange.
//!
//! The following key exchange methods are implemented here:
//! @[KE_dhe_dss], @[KE_dhe_rsa] and @[KE_dh_anon].
class DHKeyExchange
{
  //! Finite field Diffie-Hellman parameters.
  Crypto.DH.Parameters parameters;

  Gmp.mpz our; /* Our value */
  Gmp.mpz other; /* Other party's value */
  Gmp.mpz secret; /* our =  g ^ secret mod p */

  //!
  protected void create(Crypto.DH.Parameters p) {
    parameters = p;
  }

  this_program new_secret(function random)
  {
    [our, secret] = parameters->generate_keypair(random);
    return this;
  }

  //! Set the value received from the peer.
  //!
  //! @returns
  //!   Returns @[UNDEFINED] if @[o] is invalid for the set @[parameters].
  //!
  //!   Otherwise returns the current object.
  this_program set_other(Gmp.mpz o) {
    if ((o <= 1) || (o >= (parameters->p - 1))) {
      // Negotiated FF DHE Parameters Draft 4 3:
      //   If the selected group matches an offered FFDHE group exactly, the
      //   the client MUST verify that dh_Ys is in the range 1 < dh_Ys < dh_p
      //   - 1.  If dh_Ys is not in this range, the client MUST terminate the
      //   connection with a fatal handshake_failure(40) alert.
      //
      // Negotiated FF DHE Parameters Draft 4 4:
      //   When a compatible server selects an FFDHE group from among a
      //   client's Supported Groups, and the client sends a ClientKeyExchange,
      //   the server MUST verify that 1 < dh_Yc < dh_p - 1. If it is out of
      //   range, the server MUST terminate the connection with fatal
      //   handshake_failure(40) alert.
      return UNDEFINED;
    }
    other = o;
    return this;
  }

  Gmp.mpz get_shared() {
    return other->powm(secret, parameters->p);
  }
}

//! Lookup the crypto parameters for a cipher suite.
//!
//! @param suite
//!   Cipher suite to lookup.
//!
//! @param version
//!   Version of the SSL/TLS protocol to support.
//!
//! @param signature_algorithms
//!   The set of <hash, signature> combinations that
//!   are supported by the other end.
//!
//! @param max_hash_size
//!   The maximum hash size supported for the signature algorithm.
//!
//! @returns
//!   Returns @expr{0@} (zero) for unsupported combinations, otherwise
//!   returns an initialized @[CipherSpec] for the @[suite].
CipherSpec lookup(int suite, ProtocolVersion|int version,
                  array(array(int)) signature_algorithms,
                  int max_hash_size)
{
  CipherSpec res = CipherSpec();

  array algorithms = CIPHER_SUITES[suite];
  if (!algorithms)
    return 0;

  int ke_method = algorithms[0];

  switch(algorithms[1])
  {
#if constant(Crypto.Arctwo)
  case CIPHER_rc2_40:
    res->bulk_cipher_algorithm = RC2;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 1;
    res->key_material = 16;
    res->iv_size = 8;
    res->key_bits = 40;
    break;
#endif
  case CIPHER_rc4_40:
    res->bulk_cipher_algorithm = Crypto.Arcfour.State;
    res->cipher_type = CIPHER_stream;
    res->is_exportable = 1;
    res->key_material = 16;
    res->iv_size = 0;
    res->key_bits = 40;
    break;
  case CIPHER_des40:
    res->bulk_cipher_algorithm = DES;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 1;
    res->key_material = 8;
    res->iv_size = 8;
    res->key_bits = 40;
    break;    
  case CIPHER_null:
    res->bulk_cipher_algorithm = 0;
    res->cipher_type = CIPHER_stream;
    res->is_exportable = 1;
    res->key_material = 0;
    res->iv_size = 0;
    res->key_bits = 0;
    break;
  case CIPHER_rc4:
    res->bulk_cipher_algorithm = Crypto.Arcfour.State;
    res->cipher_type = CIPHER_stream;
    res->is_exportable = 0;
    res->key_material = 16;
    res->iv_size = 0;
    res->key_bits = 128;
    break;
  case CIPHER_des:
    res->bulk_cipher_algorithm = DES;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 8;
    res->iv_size = 8;
    res->key_bits = 56;
    break;
  case CIPHER_3des:
    res->bulk_cipher_algorithm = DES3;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 24;
    res->iv_size = 8;
    res->key_bits = 168;
    break;
#if constant(Crypto.IDEA)
  case CIPHER_idea:
    res->bulk_cipher_algorithm = Crypto.IDEA.CBC.Buffer.State;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 16;
    res->iv_size = 8;
    res->key_bits = 128;
    break;
#endif
  case CIPHER_aes:
    res->bulk_cipher_algorithm = Crypto.AES.CBC.Buffer.State;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 16;
    res->iv_size = 16;
    res->key_bits = 128;
    break;
  case CIPHER_aes256:
    res->bulk_cipher_algorithm = Crypto.AES.CBC.Buffer.State;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 32;
    res->iv_size = 16;
    res->key_bits = 256;
    break;
#if constant(Crypto.Camellia)
  case CIPHER_camellia128:
    res->bulk_cipher_algorithm = Crypto.Camellia.CBC.Buffer.State;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 16;
    res->iv_size = 16;
    res->key_bits = 128;
    break;
  case CIPHER_camellia256:
    res->bulk_cipher_algorithm = Crypto.Camellia.CBC.Buffer.State;
    res->cipher_type = CIPHER_block;
    res->is_exportable = 0;
    res->key_material = 32;
    res->iv_size = 16;
    res->key_bits = 256;
    break;
#endif
#if constant(Crypto.ChaCha20.POLY1305)
  case CIPHER_chacha20:
    if ((sizeof(algorithms) <= 3) || (algorithms[3] != MODE_poly1305)) {
      // Unsupported.
      return 0;
    }
    res->bulk_cipher_algorithm = Crypto.ChaCha20.POLY1305.State;
    res->cipher_type = CIPHER_aead;
    res->is_exportable = 0;
    res->key_material = 32;
    res->key_bits = 256;
    res->iv_size = 0;		// Length of the salt.
    res->explicit_iv_size = 0;	// Length of the explicit nonce/iv.
    res->hash_size = 0;		// No need for MAC keys.
    res->mac_algorithm = 0;	// MACs are not used with AEAD.

    break;
#endif
  default:
    return 0;
  }

  switch(algorithms[2])
  {
#if constant(Crypto.SHA512)
  case HASH_sha512:
    res->mac_algorithm = MAChmac_sha512;
    res->hash_size = 64;
    break;
#endif
#if constant(Crypto.SHA384)
  case HASH_sha384:
    res->mac_algorithm = MAChmac_sha384;
    res->hash_size = 48;
    break;
#endif
  case HASH_sha256:
    res->mac_algorithm = MAChmac_sha256;
    res->hash_size = 32;
    break;
  case HASH_sha:
    if(version >= PROTOCOL_TLS_1_0)
      res->mac_algorithm = MAChmac_sha;
    else
      res->mac_algorithm = MACsha;
    res->hash_size = 20;
    break;
  case HASH_md5:
    if(version >= PROTOCOL_TLS_1_0)
      res->mac_algorithm = MAChmac_md5;
    else
      res->mac_algorithm = MACmd5;
    res->hash_size = 16;
    break;
  case 0:
    res->mac_algorithm = 0;
    res->hash_size = 0;
    break;
  default:
    return 0;
  }

  if ((version == PROTOCOL_SSL_3_0) && (ke_method != KE_rsa_fips)) {
    res->prf = prf_ssl_3_0;
  } else if (version <= PROTOCOL_TLS_1_1) {
    res->prf = prf_tls_1_0;
  } else {
    // The PRF is really part of the cipher suite in TLS 1.2.
    //
    // In all existing post TLS 1.2 cases the hash for the prf is the same
    // as the hash for the suite.
    switch(algorithms[2]) {
    case HASH_none:
      break;
    case HASH_md5:
    case HASH_sha:
    case HASH_sha224:
      // These old suites are all upgraded to using SHA256.
    case HASH_sha256:
      res->prf = prf_tls_1_2;
      res->hash = Crypto.SHA256;
      break;
#if constant(Crypto.SHA384)
    case HASH_sha384:
      res->prf = prf_sha384;
      res->hash = Crypto.SHA384;
      break;
#endif
#if constant(Crypto.SHA384)
    case HASH_sha512:
      res->prf = prf_sha512;
      res->hash = Crypto.SHA512;
      break;
#endif
    default:
      return 0;
    }
  }

  if (sizeof(algorithms) > 3) {
    switch(algorithms[3]) {
    case MODE_cbc:
      break;
    case MODE_ccm:
      if (res->bulk_cipher_algorithm == Crypto.AES.CBC.Buffer.State) {
	res->bulk_cipher_algorithm = Crypto.AES.CCM.State;
      } else {
	// Unsupported.
	return 0;
      }
      res->cipher_type = CIPHER_aead;
      res->iv_size = 4;			// Length of the salt.
      res->explicit_iv_size = 8;	// Length of the explicit nonce/iv.
      res->hash_size = 0;		// No need for MAC keys.
      res->mac_algorithm = 0;		// MACs are not used with AEAD.

      break;
    case MODE_ccm_8:
      if (res->bulk_cipher_algorithm == Crypto.AES.CBC.Buffer.State) {
	res->bulk_cipher_algorithm = Crypto.AES.CCM8.State;
      } else {
	// Unsupported.
	return 0;
      }
      res->cipher_type = CIPHER_aead;
      res->iv_size = 4;			// Length of the salt.
      res->explicit_iv_size = 8;	// Length of the explicit nonce/iv.
      res->hash_size = 0;		// No need for MAC keys.
      res->mac_algorithm = 0;		// MACs are not used with AEAD.

      break;
#if constant(Crypto.AES.GCM)
    case MODE_gcm:
      if (res->bulk_cipher_algorithm == Crypto.AES.CBC.Buffer.State) {
	res->bulk_cipher_algorithm = Crypto.AES.GCM.State;
#if constant(Crypto.Camellia.GCM)
      } else if (res->bulk_cipher_algorithm ==
		 Crypto.Camellia.CBC.Buffer.State) {
	res->bulk_cipher_algorithm = Crypto.Camellia.GCM.State;
#endif
      } else {
	// Unsupported.
	return 0;
      }
      res->cipher_type = CIPHER_aead;
      res->iv_size = 4;			// Length of the salt.
      res->explicit_iv_size = 8;	// Length of the explicit nonce/iv.
      res->hash_size = 0;		// No need for MAC keys.
      res->mac_algorithm = 0;		// MACs are not used with AEAD.

      break;
#endif
#if constant(Crypto.ChaCha20.POLY1305)
    case MODE_poly1305:
      res->mac_algorithm = 0;		// MACs are not used with AEAD.
      res->hash_size = 0;
      break;
#endif
    default:
      return 0;
    }
  }

  switch(ke_method)
  {
  case KE_null:
    res->ke_factory = KeyExchangeNULL;
    break;
  case KE_rsa:
  case KE_rsa_fips:
    res->ke_factory = KeyExchangeRSA;
    break;
  case KE_dh_dss:
  case KE_dh_rsa:
    res->ke_factory = KeyExchangeDH;
    break;
  case KE_dh_anon:
  case KE_dhe_rsa:
  case KE_dhe_dss:
    res->ke_factory = KeyExchangeDHE;
    break;
#if constant(Crypto.ECC.Curve)
  case KE_ecdhe_rsa:
  case KE_ecdhe_ecdsa:
  case KE_ecdh_anon:
    res->ke_factory = KeyExchangeECDHE;
    break;
  case KE_ecdh_rsa:
  case KE_ecdh_ecdsa:
    res->ke_factory = KeyExchangeECDH;
    break;
#endif
  default:
    error( "Internal error.\n" );
  }

  switch(ke_method)
  {
  case KE_rsa:
  case KE_rsa_fips:
  case KE_dhe_rsa:
  case KE_ecdhe_rsa:
    res->signature_alg = SIGNATURE_rsa;
    break;
  case KE_dh_rsa:
  case KE_dh_dss:
  case KE_dhe_dss:
    res->signature_alg = SIGNATURE_dsa;
    break;
  case KE_null:
  case KE_dh_anon:
  case KE_ecdh_anon:
    res->signature_alg = SIGNATURE_anonymous;
    break;
#if constant(Crypto.ECC.Curve)
  case KE_ecdh_rsa:
  case KE_ecdh_ecdsa:
  case KE_ecdhe_ecdsa:
    // FIXME: SIGNATURE_ecdsa used for KE_ecdh_rsa. Naming issue?
    res->signature_alg = SIGNATURE_ecdsa;
    break;
#endif
  default:
    error( "Internal error.\n" );
  }

  if (version >= PROTOCOL_TLS_1_2)
  {
    int wanted_hash_id;
    if( res->signature_alg == SIGNATURE_ecdsa )
    {
      if (res->key_bits < 256) {
	// Suite B requires SHA256 with AES-128.
	wanted_hash_id = HASH_sha256;
      } else if (res->key_bits < 384) {
	// Suite B requires SHA384 with AES-256.
	wanted_hash_id = HASH_sha384;
      }
    }

    res->set_hash(max_hash_size, signature_algorithms, wanted_hash_id);
  }

  if (res->is_exportable && res->bulk_cipher_algorithm &&
      (version >= PROTOCOL_TLS_1_1)) {
    // RFC 4346 A.5:
    // TLS 1.1 implementations MUST NOT negotiate
    // these cipher suites in TLS 1.1 mode.
    SSL3_DEBUG_MSG("Suite not supported in TLS 1.1 and later.\n");
    return 0;
  }

  if (version >= PROTOCOL_TLS_1_2) {
    if (res->bulk_cipher_algorithm == DES) {
      // RFC 5246 1.2:
      // Removed IDEA and DES cipher suites.  They are now deprecated and
      // will be documented in a separate document.
      SSL3_DEBUG_MSG("Suite not supported in TLS 1.2 and later.\n");
      return 0;
    }
#if constant(Crypto.IDEA.CBC)
    if (res->bulk_cipher_algorithm == Crypto.IDEA.CBC.Buffer.State) {
      // RFC 5246 1.2:
      // Removed IDEA and DES cipher suites.  They are now deprecated and
      // will be documented in a separate document.
      SSL3_DEBUG_MSG("Suite not supported in TLS 1.2 and later.\n");
      return 0;
    }
#endif
  } else if (res->cipher_type == CIPHER_aead) {
    // RFC 5822 4:
    // These cipher suites make use of the authenticated encryption
    // with additional data defined in TLS 1.2 [RFC5246]. They MUST
    // NOT be negotiated in older versions of TLS.
    SSL3_DEBUG_MSG("Suite not supported prior to TLS 1.2.\n");
    return 0;
  }

  return res;
}