aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/ntp/ntpd/ntp_crypto.c
blob: 956875de7b449afda2f5a367a7f1f7bbbdd2998a (plain) (blame)
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
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
/*
 * ntp_crypto.c - NTP version 4 public key routines
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef AUTOKEY
#include <stdio.h>
#include <stdlib.h>	/* strtoul */
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>

#include "ntpd.h"
#include "ntp_stdlib.h"
#include "ntp_unixtime.h"
#include "ntp_string.h"
#include "ntp_random.h"
#include "ntp_assert.h"
#include "ntp_calendar.h"
#include "ntp_leapsec.h"

#include "openssl/bn.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/pem.h"
#include "openssl/rand.h"
#include "openssl/x509v3.h"
#include "libssl_compat.h"

#ifdef KERNEL_PLL
#include "ntp_syscall.h"
#endif /* KERNEL_PLL */

/*
 * calcomp - compare two calendar structures, ignoring yearday and weekday; like strcmp
 * No, it's not a plotter.  If you don't understand that, you're too young.
 */
static int calcomp(struct calendar *pjd1, struct calendar *pjd2)
{
	int32_t diff;	/* large enough to hold the signed difference between two uint16_t values */

	diff = pjd1->year - pjd2->year;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	/* same year; compare months */
	diff = pjd1->month - pjd2->month;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	/* same year and month; compare monthday */
	diff = pjd1->monthday - pjd2->monthday;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	/* same year and month and monthday; compare time */
	diff = pjd1->hour - pjd2->hour;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	diff = pjd1->minute - pjd2->minute;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	diff = pjd1->second - pjd2->second;
	if (diff < 0) return -1; else if (diff > 0) return 1;
	/* identical */
	return 0;
}

/*
 * Extension field message format
 *
 * These are always signed and saved before sending in network byte
 * order. They must be converted to and from host byte order for
 * processing.
 *
 * +-------+-------+
 * |   op  |  len  | <- extension pointer
 * +-------+-------+
 * |    associd    |
 * +---------------+
 * |   timestamp   | <- value pointer
 * +---------------+
 * |   filestamp   |
 * +---------------+
 * |   value len   |
 * +---------------+
 * |               |
 * =     value     =
 * |               |
 * +---------------+
 * | signature len |
 * +---------------+
 * |               |
 * =   signature   =
 * |               |
 * +---------------+
 *
 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
 * Requests carry the association ID of the receiver; responses carry
 * the association ID of the sender. Some messages include only the
 * operation/length and association ID words and so have length 8
 * octets. Ohers include the value structure and associated value and
 * signature fields. These messages include the timestamp, filestamp,
 * value and signature words and so have length at least 24 octets. The
 * signature and/or value fields can be empty, in which case the
 * respective length words are zero. An empty value with nonempty
 * signature is syntactically valid, but semantically questionable.
 *
 * The filestamp represents the time when a cryptographic data file such
 * as a public/private key pair is created. It follows every reference
 * depending on that file and serves as a means to obsolete earlier data
 * of the same type. The timestamp represents the time when the
 * cryptographic data of the message were last signed. Creation of a
 * cryptographic data file or signing a message can occur only when the
 * creator or signor is synchronized to an authoritative source and
 * proventicated to a trusted authority.
 *
 * Note there are several conditions required for server trust. First,
 * the public key on the server certificate must be verified, which can
 * involve a hike along the certificate trail to a trusted host. Next,
 * the server trust must be confirmed by one of several identity
 * schemes. Valid cryptographic values are signed with attached
 * timestamp and filestamp. Individual packet trust is confirmed
 * relative to these values by a message digest with keys generated by a
 * reverse-order pseudorandom hash.
 *
 * State decomposition. These flags are lit in the order given. They are
 * dim only when the association is demobilized.
 *
 * CRYPTO_FLAG_ENAB	Lit upon acceptance of a CRYPTO_ASSOC message
 * CRYPTO_FLAG_CERT	Lit when a self-digned trusted certificate is
 *			accepted.
 * CRYPTO_FLAG_VRFY	Lit when identity is confirmed.
 * CRYPTO_FLAG_PROV	Lit when the first signature is verified.
 * CRYPTO_FLAG_COOK	Lit when a valid cookie is accepted.
 * CRYPTO_FLAG_AUTO	Lit when valid autokey values are accepted.
 * CRYPTO_FLAG_SIGN	Lit when the server signed certificate is
 *			accepted.
 * CRYPTO_FLAG_LEAP	Lit when the leapsecond values are accepted.
 */
/*
 * Cryptodefines
 */
#define TAI_1972	10	/* initial TAI offset (s) */
#define MAX_LEAP	100	/* max UTC leapseconds (s) */
#define VALUE_LEN	(6 * 4) /* min response field length */
#define MAX_VALLEN	(65535 - VALUE_LEN)
#define YEAR		(60 * 60 * 24 * 365) /* seconds in year */

/*
 * Global cryptodata in host byte order
 */
u_int32	crypto_flags = 0x0;	/* status word */
int	crypto_nid = KEY_TYPE_MD5; /* digest nid */
char	*sys_hostname = NULL;
char	*sys_groupname = NULL;
static char *host_filename = NULL;	/* host file name */
static char *ident_filename = NULL;	/* group file name */

/*
 * Global cryptodata in network byte order
 */
struct cert_info *cinfo = NULL;	/* certificate info/value cache */
struct cert_info *cert_host = NULL; /* host certificate */
struct pkey_info *pkinfo = NULL; /* key info/value cache */
struct value hostval;		/* host value */
struct value pubkey;		/* public key */
struct value tai_leap;		/* leapseconds values */
struct pkey_info *iffkey_info = NULL; /* IFF keys */
struct pkey_info *gqkey_info = NULL; /* GQ keys */
struct pkey_info *mvkey_info = NULL; /* MV keys */

/*
 * Private cryptodata in host byte order
 */
static char *passwd = NULL;	/* private key password */
static EVP_PKEY *host_pkey = NULL; /* host key */
static EVP_PKEY *sign_pkey = NULL; /* sign key */
static const EVP_MD *sign_digest = NULL; /* sign digest */
static u_int sign_siglen;	/* sign key length */
static char *rand_file = NULL;	/* random seed file */

/*
 * Cryptotypes
 */
static	int	crypto_verify	(struct exten *, struct value *,
				    struct peer *);
static	int	crypto_encrypt	(const u_char *, u_int, keyid_t *,
				    struct value *);
static	int	crypto_alice	(struct peer *, struct value *);
static	int	crypto_alice2	(struct peer *, struct value *);
static	int	crypto_alice3	(struct peer *, struct value *);
static	int	crypto_bob	(struct exten *, struct value *);
static	int	crypto_bob2	(struct exten *, struct value *);
static	int	crypto_bob3	(struct exten *, struct value *);
static	int	crypto_iff	(struct exten *, struct peer *);
static	int	crypto_gq	(struct exten *, struct peer *);
static	int	crypto_mv	(struct exten *, struct peer *);
static	int	crypto_send	(struct exten *, struct value *, int);
static	tstamp_t crypto_time	(void);
static	void	asn_to_calendar		(ASN1_TIME *, struct calendar*);
static	struct cert_info *cert_parse (const u_char *, long, tstamp_t);
static	int	cert_sign	(struct exten *, struct value *);
static	struct cert_info *cert_install (struct exten *, struct peer *);
static	int	cert_hike	(struct peer *, struct cert_info *);
static	void	cert_free	(struct cert_info *);
static	struct pkey_info *crypto_key (char *, char *, sockaddr_u *);
static	void	bighash		(BIGNUM *, BIGNUM *);
static	struct cert_info *crypto_cert (char *);
static	u_int	exten_payload_size(const struct exten *);

#ifdef SYS_WINNT
int
readlink(char * link, char * file, int len) {
	return (-1);
}
#endif

/*
 * session_key - generate session key
 *
 * This routine generates a session key from the source address,
 * destination address, key ID and private value. The value of the
 * session key is the MD5 hash of these values, while the next key ID is
 * the first four octets of the hash.
 *
 * Returns the next key ID or 0 if there is no destination address.
 */
keyid_t
session_key(
	sockaddr_u *srcadr, 	/* source address */
	sockaddr_u *dstadr, 	/* destination address */
	keyid_t	keyno,		/* key ID */
	keyid_t	private,	/* private value */
	u_long	lifetime 	/* key lifetime */
	)
{
	EVP_MD_CTX *ctx;	/* message digest context */
	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
	keyid_t	keyid;		/* key identifer */
	u_int32	header[10];	/* data in network byte order */
	u_int	hdlen, len;

	if (!dstadr)
		return 0;
	
	/*
	 * Generate the session key and key ID. If the lifetime is
	 * greater than zero, install the key and call it trusted.
	 */
	hdlen = 0;
	switch(AF(srcadr)) {
	case AF_INET:
		header[0] = NSRCADR(srcadr);
		header[1] = NSRCADR(dstadr);
		header[2] = htonl(keyno);
		header[3] = htonl(private);
		hdlen = 4 * sizeof(u_int32);
		break;

	case AF_INET6:
		memcpy(&header[0], PSOCK_ADDR6(srcadr),
		    sizeof(struct in6_addr));
		memcpy(&header[4], PSOCK_ADDR6(dstadr),
		    sizeof(struct in6_addr));
		header[8] = htonl(keyno);
		header[9] = htonl(private);
		hdlen = 10 * sizeof(u_int32);
		break;
	}
	ctx = EVP_MD_CTX_new();
	EVP_DigestInit(ctx, EVP_get_digestbynid(crypto_nid));
	EVP_DigestUpdate(ctx, (u_char *)header, hdlen);
	EVP_DigestFinal(ctx, dgst, &len);
	EVP_MD_CTX_free(ctx);
	memcpy(&keyid, dgst, 4);
	keyid = ntohl(keyid);
	if (lifetime != 0) {
		MD5auth_setkey(keyno, crypto_nid, dgst, len, NULL);
		authtrust(keyno, lifetime);
	}
	DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
		    stoa(srcadr), stoa(dstadr), keyno,
		    private, keyid, lifetime));

	return (keyid);
}


/*
 * make_keylist - generate key list
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 *
 * This routine constructs a pseudo-random sequence by repeatedly
 * hashing the session key starting from a given source address,
 * destination address, private value and the next key ID of the
 * preceeding session key. The last entry on the list is saved along
 * with its sequence number and public signature.
 */
int
make_keylist(
	struct peer *peer,	/* peer structure pointer */
	struct interface *dstadr /* interface */
	)
{
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;	/* NTP timestamp */
	struct autokey *ap;	/* autokey pointer */
	struct value *vp;	/* value pointer */
	keyid_t	keyid = 0;	/* next key ID */
	keyid_t	cookie;		/* private value */
	long	lifetime;
	u_int	len, mpoll;
	int	i;

	if (!dstadr)
		return XEVNT_ERR;
	
	/*
	 * Allocate the key list if necessary.
	 */
	tstamp = crypto_time();
	if (peer->keylist == NULL)
		peer->keylist = eallocarray(NTP_MAXSESSION,
					    sizeof(keyid_t));

	/*
	 * Generate an initial key ID which is unique and greater than
	 * NTP_MAXKEY.
	 */
	while (1) {
		keyid = ntp_random() & 0xffffffff;
		if (keyid <= NTP_MAXKEY)
			continue;

		if (authhavekey(keyid))
			continue;
		break;
	}

	/*
	 * Generate up to NTP_MAXSESSION session keys. Stop if the
	 * next one would not be unique or not a session key ID or if
	 * it would expire before the next poll. The private value
	 * included in the hash is zero if broadcast mode, the peer
	 * cookie if client mode or the host cookie if symmetric modes.
	 */
	mpoll = 1 << min(peer->ppoll, peer->hpoll);
	lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll);
	if (peer->hmode == MODE_BROADCAST)
		cookie = 0;
	else
		cookie = peer->pcookie;
	for (i = 0; i < NTP_MAXSESSION; i++) {
		peer->keylist[i] = keyid;
		peer->keynumber = i;
		keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
		    cookie, lifetime + mpoll);
		lifetime -= mpoll;
		if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
		    lifetime < 0 || tstamp == 0)
			break;
	}

	/*
	 * Save the last session key ID, sequence number and timestamp,
	 * then sign these values for later retrieval by the clients. Be
	 * careful not to use invalid key media. Use the public values
	 * timestamp as filestamp. 
	 */
	vp = &peer->sndval;
	if (vp->ptr == NULL)
		vp->ptr = emalloc(sizeof(struct autokey));
	ap = (struct autokey *)vp->ptr;
	ap->seq = htonl(peer->keynumber);
	ap->key = htonl(keyid);
	vp->tstamp = htonl(tstamp);
	vp->fstamp = hostval.tstamp;
	vp->vallen = htonl(sizeof(struct autokey));
	vp->siglen = 0;
	if (tstamp != 0) {
		if (vp->sig == NULL)
			vp->sig = emalloc(sign_siglen);
		ctx = EVP_MD_CTX_new();
		EVP_SignInit(ctx, sign_digest);
		EVP_SignUpdate(ctx, (u_char *)vp, 12);
		EVP_SignUpdate(ctx, vp->ptr, sizeof(struct autokey));
		if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
			INSIST(len <= sign_siglen);
			vp->siglen = htonl(len);
			peer->flags |= FLAG_ASSOC;
		}
		EVP_MD_CTX_free(ctx);
	}
	DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
		    peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
		    ntohl(vp->fstamp), peer->hpoll));
	return (XEVNT_OK);
}


/*
 * crypto_recv - parse extension fields
 *
 * This routine is called when the packet has been matched to an
 * association and passed sanity, format and MAC checks. We believe the
 * extension field values only if the field has proper format and
 * length, the timestamp and filestamp are valid and the signature has
 * valid length and is verified. There are a few cases where some values
 * are believed even if the signature fails, but only if the proventic
 * bit is not set.
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_LEN	bad field format or length
 */
int
crypto_recv(
	struct peer *peer,	/* peer structure pointer */
	struct recvbuf *rbufp	/* packet buffer pointer */
	)
{
	const EVP_MD *dp;	/* message digest algorithm */
	u_int32	*pkt;		/* receive packet pointer */
	struct autokey *ap, *bp; /* autokey pointer */
	struct exten *ep, *fp;	/* extension pointers */
	struct cert_info *xinfo; /* certificate info pointer */
	int	macbytes;	/* length of MAC field, signed by intention */
	int	authlen;	/* offset of MAC field */
	associd_t associd;	/* association ID */
	tstamp_t fstamp = 0;	/* filestamp */
	u_int	len;		/* extension field length */
	u_int	code;		/* extension field opcode */
	u_int	vallen = 0;	/* value length */
	X509	*cert;		/* X509 certificate */
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	keyid_t	cookie;		/* crumbles */
	int	hismode;	/* packet mode */
	int	rval = XEVNT_OK;
	const u_char *puch;
	u_int32 temp32;

	/*
	 * Initialize. Note that the packet has already been checked for
	 * valid format and extension field lengths. First extract the
	 * field length, command code and association ID in host byte
	 * order. These are used with all commands and modes. Then check
	 * the version number, which must be 2, and length, which must
	 * be at least 8 for requests and VALUE_LEN (24) for responses.
	 * Packets that fail either test sink without a trace. The
	 * association ID is saved only if nonzero.
	 */
	authlen = LEN_PKT_NOMAC;
	hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
	while ((macbytes = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
		/* We can be reasonably sure that we can read at least
		 * the opcode and the size field here. More stringent
		 * checks follow up shortly.
		 */
		pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
		ep = (struct exten *)pkt;
		code = ntohl(ep->opcode) & 0xffff0000;
		len = ntohl(ep->opcode) & 0x0000ffff;
		// HMS: Why pkt[1] instead of ep->associd ?
		associd = (associd_t)ntohl(pkt[1]);
		rval = XEVNT_OK;
		DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
			    peer->crypto, authlen, len, code >> 16,
			    associd));

		/*
		 * Check version number and field length. If bad,
		 * quietly ignore the packet.
		 */
		if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
			sys_badlength++;
			code |= CRYPTO_ERROR;
		}

		/* Check if the declared size fits into the remaining
		 * buffer. We *know* 'macbytes' > 0 here!
		 */
		if (len > (u_int)macbytes) {
			DPRINTF(1, ("crypto_recv: possible attack detected, associd %d\n",
				    associd));
			return XEVNT_LEN;
		}

		/* Check if the paylod of the extension fits into the
		 * declared frame.
		 */
		if (len >= VALUE_LEN) {
			fstamp = ntohl(ep->fstamp);
			vallen = ntohl(ep->vallen);
			/*
			 * Bug 2761: I hope this isn't too early...
			 */
			if (   vallen == 0
			    || len - VALUE_LEN < vallen)
				return XEVNT_LEN;
		}
		switch (code) {

		/*
		 * Install status word, host name, signature scheme and
		 * association ID. In OpenSSL the signature algorithm is
		 * bound to the digest algorithm, so the NID completely
		 * defines the signature scheme. Note the request and
		 * response are identical, but neither is validated by
		 * signature. The request is processed here only in
		 * symmetric modes. The server name field might be
		 * useful to implement access controls in future.
		 */
		case CRYPTO_ASSOC:

			/*
			 * If our state machine is running when this
			 * message arrives, the other fellow might have
			 * restarted. However, this could be an
			 * intruder, so just clamp the poll interval and
			 * find out for ourselves. Otherwise, pass the
			 * extension field to the transmit side.
			 */
			if (peer->crypto & CRYPTO_FLAG_CERT) {
				rval = XEVNT_ERR;
				break;
			}
			if (peer->cmmd) {
				if (peer->assoc != associd) {
					rval = XEVNT_ERR;
					break;
				}
				free(peer->cmmd); /* will be set again! */
			}
			fp = emalloc(len);
			memcpy(fp, ep, len);
			fp->associd = htonl(peer->associd);
			peer->cmmd = fp;
			/* fall through */

		case CRYPTO_ASSOC | CRYPTO_RESP:

			/*
			 * Discard the message if it has already been
			 * stored or the message has been amputated.
			 */
			if (peer->crypto) {
				if (peer->assoc != associd)
					rval = XEVNT_ERR;
				break;
			}
			INSIST(len >= VALUE_LEN);
			if (vallen == 0 || vallen > MAXHOSTNAME ||
			    len - VALUE_LEN < vallen) {
				rval = XEVNT_LEN;
				break;
			}
			DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
				    crypto_flags, peer->associd, fstamp,
				    peer->assoc));
			temp32 = crypto_flags & CRYPTO_FLAG_MASK;

			/*
			 * If the client scheme is PC, the server scheme
			 * must be PC. The public key and identity are
			 * presumed valid, so we skip the certificate
			 * and identity exchanges and move immediately
			 * to the cookie exchange which confirms the
			 * server signature.
			 */
			if (crypto_flags & CRYPTO_FLAG_PRIV) {
				if (!(fstamp & CRYPTO_FLAG_PRIV)) {
					rval = XEVNT_KEY;
					break;
				}
				fstamp |= CRYPTO_FLAG_CERT |
				    CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;

			/*
			 * It is an error if either peer supports
			 * identity, but the other does not.
			 */
			} else if (hismode == MODE_ACTIVE || hismode ==
			    MODE_PASSIVE) {
				if ((temp32 && !(fstamp &
				    CRYPTO_FLAG_MASK)) ||
				    (!temp32 && (fstamp &
				    CRYPTO_FLAG_MASK))) {
					rval = XEVNT_KEY;
					break;
				}
			}

			/*
			 * Discard the message if the signature digest
			 * NID is not supported.
			 */
			temp32 = (fstamp >> 16) & 0xffff;
			dp =
			    (const EVP_MD *)EVP_get_digestbynid(temp32);
			if (dp == NULL) {
				rval = XEVNT_MD;
				break;
			}

			/*
			 * Save status word, host name and message
			 * digest/signature type. If this is from a
			 * broadcast and the association ID has changed,
			 * request the autokey values.
			 */
			peer->assoc = associd;
			if (hismode == MODE_SERVER)
				fstamp |= CRYPTO_FLAG_AUTO;
			if (!(fstamp & CRYPTO_FLAG_TAI))
				fstamp |= CRYPTO_FLAG_LEAP;
			RAND_bytes((u_char *)&peer->hcookie, 4);
			peer->crypto = fstamp;
			peer->digest = dp;
			if (peer->subject != NULL)
				free(peer->subject);
			peer->subject = emalloc(vallen + 1);
			memcpy(peer->subject, ep->pkt, vallen);
			peer->subject[vallen] = '\0';
			if (peer->issuer != NULL)
				free(peer->issuer);
			peer->issuer = estrdup(peer->subject);
			snprintf(statstr, sizeof(statstr),
			    "assoc %d %d host %s %s", peer->associd,
			    peer->assoc, peer->subject,
			    OBJ_nid2ln(temp32));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Decode X509 certificate in ASN.1 format and extract
		 * the data containing, among other things, subject
		 * name and public key. In the default identification
		 * scheme, the certificate trail is followed to a self
		 * signed trusted certificate.
		 */
		case CRYPTO_CERT | CRYPTO_RESP:

			/*
			 * Discard the message if empty or invalid.
			 */
			if (len < VALUE_LEN)
				break;

			if ((rval = crypto_verify(ep, NULL, peer)) !=
			    XEVNT_OK)
				break;

			/*
			 * Scan the certificate list to delete old
			 * versions and link the newest version first on
			 * the list. Then, verify the signature. If the
			 * certificate is bad or missing, just ignore
			 * it.
			 */
			if ((xinfo = cert_install(ep, peer)) == NULL) {
				rval = XEVNT_CRT;
				break;
			}
			if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
				break;

			/*
			 * We plug in the public key and lifetime from
			 * the first certificate received. However, note
			 * that this certificate might not be signed by
			 * the server, so we can't check the
			 * signature/digest NID.
			 */
			if (peer->pkey == NULL) {
				puch = xinfo->cert.ptr;
				cert = d2i_X509(NULL, &puch,
				    ntohl(xinfo->cert.vallen));
				peer->pkey = X509_get_pubkey(cert);
				X509_free(cert);
			}
			peer->flash &= ~TEST8;
			temp32 = xinfo->nid;
			snprintf(statstr, sizeof(statstr),
			    "cert %s %s 0x%x %s (%u) fs %u",
			    xinfo->subject, xinfo->issuer, xinfo->flags,
			    OBJ_nid2ln(temp32), temp32,
			    ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Schnorr (IFF) identity scheme. This scheme is
		 * designed for use with shared secret server group keys
		 * and where the certificate may be generated by a third
		 * party. The client sends a challenge to the server,
		 * which performs a calculation and returns the result.
		 * A positive result is possible only if both client and
		 * server contain the same secret group key.
		 */
		case CRYPTO_IFF | CRYPTO_RESP:

			/*
			 * Discard the message if invalid.
			 */
			if ((rval = crypto_verify(ep, NULL, peer)) !=
			    XEVNT_OK)
				break;

			/*
			 * If the challenge matches the response, the
			 * server public key, signature and identity are
			 * all verified at the same time. The server is
			 * declared trusted, so we skip further
			 * certificate exchanges and move immediately to
			 * the cookie exchange.
			 */
			if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
				break;

			peer->crypto |= CRYPTO_FLAG_VRFY;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr), "iff %s fs %u",
			    peer->issuer, ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Guillou-Quisquater (GQ) identity scheme. This scheme
		 * is designed for use with public certificates carrying
		 * the GQ public key in an extension field. The client
		 * sends a challenge to the server, which performs a
		 * calculation and returns the result. A positive result
		 * is possible only if both client and server contain
		 * the same group key and the server has the matching GQ
		 * private key.
		 */
		case CRYPTO_GQ | CRYPTO_RESP:

			/*
			 * Discard the message if invalid
			 */
			if ((rval = crypto_verify(ep, NULL, peer)) !=
			    XEVNT_OK)
				break;

			/*
			 * If the challenge matches the response, the
			 * server public key, signature and identity are
			 * all verified at the same time. The server is
			 * declared trusted, so we skip further
			 * certificate exchanges and move immediately to
			 * the cookie exchange.
			 */
			if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
				break;

			peer->crypto |= CRYPTO_FLAG_VRFY;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr), "gq %s fs %u",
			    peer->issuer, ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Mu-Varadharajan (MV) identity scheme. This scheme is
		 * designed for use with three levels of trust, trusted
		 * host, server and client. The trusted host key is
		 * opaque to servers and clients; the server keys are
		 * opaque to clients and each client key is different.
		 * Client keys can be revoked without requiring new key
		 * generations.
		 */
		case CRYPTO_MV | CRYPTO_RESP:

			/*
			 * Discard the message if invalid.
			 */
			if ((rval = crypto_verify(ep, NULL, peer)) !=
			    XEVNT_OK)
				break;

			/*
			 * If the challenge matches the response, the
			 * server public key, signature and identity are
			 * all verified at the same time. The server is
			 * declared trusted, so we skip further
			 * certificate exchanges and move immediately to
			 * the cookie exchange.
			 */
			if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
				break;

			peer->crypto |= CRYPTO_FLAG_VRFY;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr), "mv %s fs %u",
			    peer->issuer, ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;


		/*
		 * Cookie response in client and symmetric modes. If the
		 * cookie bit is set, the working cookie is the EXOR of
		 * the current and new values.
		 */
		case CRYPTO_COOK | CRYPTO_RESP:

			/*
			 * Discard the message if invalid or signature
			 * not verified with respect to the cookie
			 * values.
			 */
			if ((rval = crypto_verify(ep, &peer->cookval,
			    peer)) != XEVNT_OK)
				break;

			/*
			 * Decrypt the cookie, hunting all the time for
			 * errors.
			 */
			if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
				RSA *rsa = EVP_PKEY_get0_RSA(host_pkey);
				u_int32 *cookiebuf = malloc(RSA_size(rsa));
				if (!cookiebuf) {
					rval = XEVNT_CKY;
					break;
				}

				if (RSA_private_decrypt(vallen,
				    (u_char *)ep->pkt,
				    (u_char *)cookiebuf,
				    rsa,
				    RSA_PKCS1_OAEP_PADDING) != 4) {
					rval = XEVNT_CKY;
					free(cookiebuf);
					break;
				} else {
					cookie = ntohl(*cookiebuf);
					free(cookiebuf);
				}
			} else {
				rval = XEVNT_CKY;
				break;
			}

			/*
			 * Install cookie values and light the cookie
			 * bit. If this is not broadcast client mode, we
			 * are done here.
			 */
			key_expire(peer);
			if (hismode == MODE_ACTIVE || hismode ==
			    MODE_PASSIVE)
				peer->pcookie = peer->hcookie ^ cookie;
			else
				peer->pcookie = cookie;
			peer->crypto |= CRYPTO_FLAG_COOK;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr),
			    "cook %x ts %u fs %u", peer->pcookie,
			    ntohl(ep->tstamp), ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Install autokey values in broadcast client and
		 * symmetric modes. We have to do this every time the
		 * sever/peer cookie changes or a new keylist is
		 * rolled. Ordinarily, this is automatic as this message
		 * is piggybacked on the first NTP packet sent upon
		 * either of these events. Note that a broadcast client
		 * or symmetric peer can receive this response without a
		 * matching request.
		 */
		case CRYPTO_AUTO | CRYPTO_RESP:

			/*
			 * Discard the message if invalid or signature
			 * not verified with respect to the receive
			 * autokey values.
			 */
			if ((rval = crypto_verify(ep, &peer->recval,
			    peer)) != XEVNT_OK) 
				break;

			/*
			 * Discard the message if a broadcast client and
			 * the association ID does not match. This might
			 * happen if a broacast server restarts the
			 * protocol. A protocol restart will occur at
			 * the next ASSOC message.
			 */
			if ((peer->cast_flags & MDF_BCLNT) &&
			    peer->assoc != associd)
				break;

			/*
			 * Install autokey values and light the
			 * autokey bit. This is not hard.
			 */
			if (ep->tstamp == 0)
				break;

			if (peer->recval.ptr == NULL)
				peer->recval.ptr =
				    emalloc(sizeof(struct autokey));
			bp = (struct autokey *)peer->recval.ptr;
			peer->recval.tstamp = ep->tstamp;
			peer->recval.fstamp = ep->fstamp;
			ap = (struct autokey *)ep->pkt;
			bp->seq = ntohl(ap->seq);
			bp->key = ntohl(ap->key);
			peer->pkeyid = bp->key;
			peer->crypto |= CRYPTO_FLAG_AUTO;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr), 
			    "auto seq %d key %x ts %u fs %u", bp->seq,
			    bp->key, ntohl(ep->tstamp),
			    ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;
	
		/*
		 * X509 certificate sign response. Validate the
		 * certificate signed by the server and install. Later
		 * this can be provided to clients of this server in
		 * lieu of the self signed certificate in order to
		 * validate the public key.
		 */
		case CRYPTO_SIGN | CRYPTO_RESP:

			/*
			 * Discard the message if invalid.
			 */
			if ((rval = crypto_verify(ep, NULL, peer)) !=
			    XEVNT_OK)
				break;

			/*
			 * Scan the certificate list to delete old
			 * versions and link the newest version first on
			 * the list.
			 */
			if ((xinfo = cert_install(ep, peer)) == NULL) {
				rval = XEVNT_CRT;
				break;
			}
			peer->crypto |= CRYPTO_FLAG_SIGN;
			peer->flash &= ~TEST8;
			temp32 = xinfo->nid;
			snprintf(statstr, sizeof(statstr),
			    "sign %s %s 0x%x %s (%u) fs %u",
			    xinfo->subject, xinfo->issuer, xinfo->flags,
			    OBJ_nid2ln(temp32), temp32,
			    ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * Install leapseconds values. While the leapsecond
		 * values epoch, TAI offset and values expiration epoch
		 * are retained, only the current TAI offset is provided
		 * via the kernel to other applications.
		 */
		case CRYPTO_LEAP | CRYPTO_RESP:
			/*
			 * Discard the message if invalid. We can't
			 * compare the value timestamps here, as they
			 * can be updated by different servers.
			 */
			rval = crypto_verify(ep, NULL, peer);
			if ((rval   != XEVNT_OK          ) ||
			    (vallen != 3*sizeof(uint32_t))  )
				break;

			/* Check if we can update the basic TAI offset
			 * for our current leap frame. This is a hack
			 * and ignores the time stamps in the autokey
			 * message.
			 */
			if (sys_leap != LEAP_NOTINSYNC)
				leapsec_autokey_tai(ntohl(ep->pkt[0]),
						    rbufp->recv_time.l_ui, NULL);
			tai_leap.tstamp = ep->tstamp;
			tai_leap.fstamp = ep->fstamp;
			crypto_update();
			mprintf_event(EVNT_TAI, peer,
				      "%d seconds", ntohl(ep->pkt[0]));
			peer->crypto |= CRYPTO_FLAG_LEAP;
			peer->flash &= ~TEST8;
			snprintf(statstr, sizeof(statstr),
				 "leap TAI offset %d at %u expire %u fs %u",
				 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
				 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			break;

		/*
		 * We come here in symmetric modes for miscellaneous
		 * commands that have value fields but are processed on
		 * the transmit side. All we need do here is check for
		 * valid field length. Note that ASSOC is handled
		 * separately.
		 */
		case CRYPTO_CERT:
		case CRYPTO_IFF:
		case CRYPTO_GQ:
		case CRYPTO_MV:
		case CRYPTO_COOK:
		case CRYPTO_SIGN:
			if (len < VALUE_LEN) {
				rval = XEVNT_LEN;
				break;
			}
			/* fall through */

		/*
		 * We come here in symmetric modes for requests
		 * requiring a response (above plus AUTO and LEAP) and
		 * for responses. If a request, save the extension field
		 * for later; invalid requests will be caught on the
		 * transmit side. If an error or invalid response,
		 * declare a protocol error.
		 */
		default:
			if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
				rval = XEVNT_ERR;
			} else if (peer->cmmd == NULL) {
				fp = emalloc(len);
				memcpy(fp, ep, len);
				peer->cmmd = fp;
			}
		}

		/*
		 * The first error found terminates the extension field
		 * scan and we return the laundry to the caller.
		 */
		if (rval != XEVNT_OK) {
			snprintf(statstr, sizeof(statstr),
			    "%04x %d %02x %s", htonl(ep->opcode),
			    associd, rval, eventstr(rval));
			record_crypto_stats(&peer->srcadr, statstr);
			DPRINTF(1, ("crypto_recv: %s\n", statstr));
			return (rval);
		}
		authlen += (len + 3) / 4 * 4;
	}
	return (rval);
}


/*
 * crypto_xmit - construct extension fields
 *
 * This routine is called both when an association is configured and
 * when one is not. The only case where this matters is to retrieve the
 * autokey information, in which case the caller has to provide the
 * association ID to match the association.
 *
 * Side effect: update the packet offset.
 *
 * Errors
 * XEVNT_OK	success
 * XEVNT_CRT	bad or missing certificate
 * XEVNT_ERR	protocol error
 * XEVNT_LEN	bad field format or length
 * XEVNT_PER	host certificate expired
 */
int
crypto_xmit(
	struct peer *peer,	/* peer structure pointer */
	struct pkt *xpkt,	/* transmit packet pointer */
	struct recvbuf *rbufp,	/* receive buffer pointer */
	int	start,		/* offset to extension field */
	struct exten *ep,	/* extension pointer */
	keyid_t cookie		/* session cookie */
	)
{
	struct exten *fp;	/* extension pointers */
	struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
	sockaddr_u *srcadr_sin; /* source address */
	u_int32	*pkt;		/* packet pointer */
	u_int	opcode;		/* extension field opcode */
	char	certname[MAXHOSTNAME + 1]; /* subject name buffer */
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	tstamp_t tstamp;
	struct calendar tscal;
	u_int	vallen;
	struct value vtemp;
	associd_t associd;
	int	rval;
	int	len;
	keyid_t tcookie;

	/*
	 * Generate the requested extension field request code, length
	 * and association ID. If this is a response and the host is not
	 * synchronized, light the error bit and go home.
	 */
	pkt = (u_int32 *)xpkt + start / 4;
	fp = (struct exten *)pkt;
	opcode = ntohl(ep->opcode);
	if (peer != NULL) {
		srcadr_sin = &peer->srcadr;
		if (!(opcode & CRYPTO_RESP))
			peer->opcode = ep->opcode;
	} else {
		srcadr_sin = &rbufp->recv_srcadr;
	}
	associd = (associd_t) ntohl(ep->associd);
	len = 8;
	fp->opcode = htonl((opcode & 0xffff0000) | len);
	fp->associd = ep->associd;
	rval = XEVNT_OK;
	tstamp = crypto_time();
	switch (opcode & 0xffff0000) {

	/*
	 * Send association request and response with status word and
	 * host name. Note, this message is not signed and the filestamp
	 * contains only the status word.
	 */
	case CRYPTO_ASSOC:
	case CRYPTO_ASSOC | CRYPTO_RESP:
		len = crypto_send(fp, &hostval, start);
		fp->fstamp = htonl(crypto_flags);
		break;

	/*
	 * Send certificate request. Use the values from the extension
	 * field.
	 */
	case CRYPTO_CERT:
		memset(&vtemp, 0, sizeof(vtemp));
		vtemp.tstamp = ep->tstamp;
		vtemp.fstamp = ep->fstamp;
		vtemp.vallen = ep->vallen;
		vtemp.ptr = (u_char *)ep->pkt;
		len = crypto_send(fp, &vtemp, start);
		break;

	/*
	 * Send sign request. Use the host certificate, which is self-
	 * signed and may or may not be trusted.
	 */
	case CRYPTO_SIGN:
		(void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
		if ((calcomp(&tscal, &(cert_host->first)) < 0)
		|| (calcomp(&tscal, &(cert_host->last)) > 0))
			rval = XEVNT_PER;
		else
			len = crypto_send(fp, &cert_host->cert, start);
		break;

	/*
	 * Send certificate response. Use the name in the extension
	 * field to find the certificate in the cache. If the request
	 * contains no subject name, assume the name of this host. This
	 * is for backwards compatibility. Private certificates are
	 * never sent.
	 *
	 * There may be several certificates matching the request. First
	 * choice is a self-signed trusted certificate; second choice is
	 * any certificate signed by another host. There is no third
	 * choice. 
	 */
	case CRYPTO_CERT | CRYPTO_RESP:
		vallen = exten_payload_size(ep); /* Must be <64k */
		if (vallen == 0 || vallen >= sizeof(certname) ) {
			rval = XEVNT_LEN;
			break;
		}

		/*
		 * Find all public valid certificates with matching
		 * subject. If a self-signed, trusted certificate is
		 * found, use that certificate. If not, use the last non
		 * self-signed certificate.
		 */
		memcpy(certname, ep->pkt, vallen);
		certname[vallen] = '\0';
		xp = yp = NULL;
		for (cp = cinfo; cp != NULL; cp = cp->link) {
			if (cp->flags & (CERT_PRIV | CERT_ERROR))
				continue;

			if (strcmp(certname, cp->subject) != 0)
				continue;

			if (strcmp(certname, cp->issuer) != 0)
				yp = cp;
			else if (cp ->flags & CERT_TRUST)
				xp = cp;
			continue;
		}

		/*
		 * Be careful who you trust. If the certificate is not
		 * found, return an empty response. Note that we dont
		 * enforce lifetimes here.
		 *
		 * The timestamp and filestamp are taken from the
		 * certificate value structure. For all certificates the
		 * timestamp is the latest signature update time. For
		 * host and imported certificates the filestamp is the
		 * creation epoch. For signed certificates the filestamp
		 * is the creation epoch of the trusted certificate at
		 * the root of the certificate trail. In principle, this
		 * allows strong checking for signature masquerade.
		 */
		if (xp == NULL)
			xp = yp;
		if (xp == NULL)
			break;

		if (tstamp == 0)
			break;

		len = crypto_send(fp, &xp->cert, start);
		break;

	/*
	 * Send challenge in Schnorr (IFF) identity scheme.
	 */
	case CRYPTO_IFF:
		if (peer == NULL)
			break;		/* hack attack */

		if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send response in Schnorr (IFF) identity scheme.
	 */
	case CRYPTO_IFF | CRYPTO_RESP:
		if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
	 */
	case CRYPTO_GQ:
		if (peer == NULL)
			break;		/* hack attack */

		if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send response in Guillou-Quisquater (GQ) identity scheme.
	 */
	case CRYPTO_GQ | CRYPTO_RESP:
		if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send challenge in MV identity scheme.
	 */
	case CRYPTO_MV:
		if (peer == NULL)
			break;		/* hack attack */

		if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send response in MV identity scheme.
	 */
	case CRYPTO_MV | CRYPTO_RESP:
		if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send certificate sign response. The integrity of the request
	 * certificate has already been verified on the receive side.
	 * Sign the response using the local server key. Use the
	 * filestamp from the request and use the timestamp as the
	 * current time. Light the error bit if the certificate is
	 * invalid or contains an unverified signature.
	 */
	case CRYPTO_SIGN | CRYPTO_RESP:
		if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Send public key and signature. Use the values from the public
	 * key.
	 */
	case CRYPTO_COOK:
		len = crypto_send(fp, &pubkey, start);
		break;

	/*
	 * Encrypt and send cookie and signature. Light the error bit if
	 * anything goes wrong.
	 */
	case CRYPTO_COOK | CRYPTO_RESP:
		vallen = ntohl(ep->vallen);	/* Must be <64k */
		if (   vallen == 0
		    || (vallen >= MAX_VALLEN)
		    || (opcode & 0x0000ffff)  < VALUE_LEN + vallen) {
			rval = XEVNT_LEN;
			break;
		}
		if (peer == NULL)
			tcookie = cookie;
		else
			tcookie = peer->hcookie;
		if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
		    == XEVNT_OK) {
			len = crypto_send(fp, &vtemp, start);
			value_free(&vtemp);
		}
		break;

	/*
	 * Find peer and send autokey data and signature in broadcast
	 * server and symmetric modes. Use the values in the autokey
	 * structure. If no association is found, either the server has
	 * restarted with new associations or some perp has replayed an
	 * old message, in which case light the error bit.
	 */
	case CRYPTO_AUTO | CRYPTO_RESP:
		if (peer == NULL) {
			if ((peer = findpeerbyassoc(associd)) == NULL) {
				rval = XEVNT_ERR;
				break;
			}
		}
		peer->flags &= ~FLAG_ASSOC;
		len = crypto_send(fp, &peer->sndval, start);
		break;

	/*
	 * Send leapseconds values and signature. Use the values from
	 * the tai structure. If no table has been loaded, just send an
	 * empty request.
	 */
	case CRYPTO_LEAP | CRYPTO_RESP:
		len = crypto_send(fp, &tai_leap, start);
		break;

	/*
	 * Default - Send a valid command for unknown requests; send
	 * an error response for unknown resonses.
	 */
	default:
		if (opcode & CRYPTO_RESP)
			rval = XEVNT_ERR;
	}

	/*
	 * In case of error, flame the log. If a request, toss the
	 * puppy; if a response, return so the sender can flame, too.
	 */
	if (rval != XEVNT_OK) {
		u_int32	uint32;

		uint32 = CRYPTO_ERROR;
		opcode |= uint32;
		fp->opcode |= htonl(uint32);
		snprintf(statstr, sizeof(statstr),
		    "%04x %d %02x %s", opcode, associd, rval,
		    eventstr(rval));
		record_crypto_stats(srcadr_sin, statstr);
		DPRINTF(1, ("crypto_xmit: %s\n", statstr));
		if (!(opcode & CRYPTO_RESP))
			return (0);
	}
	DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
		    crypto_flags, start, len, opcode >> 16, associd));
	return (len);
}


/*
 * crypto_verify - verify the extension field value and signature
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_FSP	bad filestamp
 * XEVNT_LEN	bad field format or length
 * XEVNT_PUB	bad or missing public key
 * XEVNT_SGL	bad signature length
 * XEVNT_SIG	signature not verified
 * XEVNT_TSP	bad timestamp
 */
static int
crypto_verify(
	struct exten *ep,	/* extension pointer */
	struct value *vp,	/* value pointer */
	struct peer *peer	/* peer structure pointer */
	)
{
	EVP_PKEY *pkey;		/* server public key */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp, tstamp1 = 0; /* timestamp */
	tstamp_t fstamp, fstamp1 = 0; /* filestamp */
	u_int	vallen;		/* value length */
	u_int	siglen;		/* signature length */
	u_int	opcode, len;
	int	i;

	/*
	 * We are extremely parannoyed. We require valid opcode, length,
	 * association ID, timestamp, filestamp, public key, digest,
	 * signature length and signature, where relevant. Note that
	 * preliminary length checks are done in the main loop.
	 */
	len = ntohl(ep->opcode) & 0x0000ffff;
	opcode = ntohl(ep->opcode) & 0xffff0000;

	/*
	 * Check for valid value header, association ID and extension
	 * field length. Remember, it is not an error to receive an
	 * unsolicited response; however, the response ID must match
	 * the association ID.
	 */
	if (opcode & CRYPTO_ERROR)
		return (XEVNT_ERR);

 	if (len < VALUE_LEN)
		return (XEVNT_LEN);

	if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
	    MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
		if (ntohl(ep->associd) != peer->assoc)
			return (XEVNT_ERR);
	} else {
		if (ntohl(ep->associd) != peer->associd)
			return (XEVNT_ERR);
	}

	/*
	 * We have a valid value header. Check for valid value and
	 * signature field lengths. The extension field length must be
	 * long enough to contain the value header, value and signature.
	 * Note both the value and signature field lengths are rounded
	 * up to the next word (4 octets).
	 */
	vallen = ntohl(ep->vallen);
	if (   vallen == 0
	    || vallen > MAX_VALLEN)
		return (XEVNT_LEN);

	i = (vallen + 3) / 4;
	siglen = ntohl(ep->pkt[i++]);
	if (   siglen > MAX_VALLEN
	    || len - VALUE_LEN < ((vallen + 3) / 4) * 4
	    || len - VALUE_LEN - ((vallen + 3) / 4) * 4
	      < ((siglen + 3) / 4) * 4)
		return (XEVNT_LEN);

	/*
	 * Check for valid timestamp and filestamp. If the timestamp is
	 * zero, the sender is not synchronized and signatures are
	 * not possible. If nonzero the timestamp must not precede the
	 * filestamp. The timestamp and filestamp must not precede the
	 * corresponding values in the value structure, if present.
 	 */
	tstamp = ntohl(ep->tstamp);
	fstamp = ntohl(ep->fstamp);
	if (tstamp == 0)
		return (XEVNT_TSP);

	if (tstamp < fstamp)
		return (XEVNT_TSP);

	if (vp != NULL) {
		tstamp1 = ntohl(vp->tstamp);
		fstamp1 = ntohl(vp->fstamp);
		if (tstamp1 != 0 && fstamp1 != 0) {
			if (tstamp < tstamp1)
				return (XEVNT_TSP);

			if ((tstamp < fstamp1 || fstamp < fstamp1))
				return (XEVNT_FSP);
		}
	}

	/*
	 * At the time the certificate message is validated, the public
	 * key in the message is not available. Thus, don't try to
	 * verify the signature.
	 */
	if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
		return (XEVNT_OK);

	/*
	 * Check for valid signature length, public key and digest
	 * algorithm.
	 */
	if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
		pkey = sign_pkey;
	else
		pkey = peer->pkey;
	if (siglen == 0 || pkey == NULL || peer->digest == NULL)
		return (XEVNT_ERR);

	if (siglen != (u_int)EVP_PKEY_size(pkey))
		return (XEVNT_SGL);

	/*
	 * Darn, I thought we would never get here. Verify the
	 * signature. If the identity exchange is verified, light the
	 * proventic bit. What a relief.
	 */
	ctx = EVP_MD_CTX_new();
	EVP_VerifyInit(ctx, peer->digest);
	/* XXX: the "+ 12" needs to be at least documented... */
	EVP_VerifyUpdate(ctx, (u_char *)&ep->tstamp, vallen + 12);
	if (EVP_VerifyFinal(ctx, (u_char *)&ep->pkt[i], siglen,
	    pkey) <= 0) {
		EVP_MD_CTX_free(ctx);
		return (XEVNT_SIG);
	}
	EVP_MD_CTX_free(ctx);

	if (peer->crypto & CRYPTO_FLAG_VRFY)
		peer->crypto |= CRYPTO_FLAG_PROV;
	return (XEVNT_OK);
}


/*
 * crypto_encrypt - construct vp (encrypted cookie and signature) from
 * the public key and cookie.
 *
 * Returns:
 * XEVNT_OK	success
 * XEVNT_CKY	bad or missing cookie
 * XEVNT_PUB	bad or missing public key
 */
static int
crypto_encrypt(
	const u_char *ptr,	/* Public Key */
	u_int	vallen,		/* Length of Public Key */
	keyid_t	*cookie,	/* server cookie */
	struct value *vp	/* value pointer */
	)
{
	EVP_PKEY *pkey;		/* public key */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;	/* NTP timestamp */
	u_int32	temp32;
	u_char *puch;

	/*
	 * Extract the public key from the request.
	 */
	pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
	if (pkey == NULL) {
		msyslog(LOG_ERR, "crypto_encrypt: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_PUB);
	}

	/*
	 * Encrypt the cookie, encode in ASN.1 and sign.
	 */
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = hostval.tstamp;
	vallen = EVP_PKEY_size(pkey);
	vp->vallen = htonl(vallen);
	vp->ptr = emalloc(vallen);
	puch = vp->ptr;
	temp32 = htonl(*cookie);
	if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
	    EVP_PKEY_get0_RSA(pkey), RSA_PKCS1_OAEP_PADDING) <= 0) {
		msyslog(LOG_ERR, "crypto_encrypt: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		free(vp->ptr);
		EVP_PKEY_free(pkey);
		return (XEVNT_CKY);
	}
	EVP_PKEY_free(pkey);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, vallen);
	if (EVP_SignFinal(ctx, vp->sig, &vallen, sign_pkey)) {
		INSIST(vallen <= sign_siglen);
		vp->siglen = htonl(vallen);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_ident - construct extension field for identity scheme
 *
 * This routine determines which identity scheme is in use and
 * constructs an extension field for that scheme.
 *
 * Returns
 * CRYTPO_IFF	IFF scheme
 * CRYPTO_GQ	GQ scheme
 * CRYPTO_MV	MV scheme
 * CRYPTO_NULL	no available scheme
 */
u_int
crypto_ident(
	struct peer *peer	/* peer structure pointer */
	)
{
	char		filename[MAXFILENAME];
	const char *	scheme_name;
	u_int		scheme_id;

	/*
	 * We come here after the group trusted host has been found; its
	 * name defines the group name. Search the key cache for all
	 * keys matching the same group name in order IFF, GQ and MV.
	 * Use the first one available.
	 */
	scheme_name = NULL;
	if (peer->crypto & CRYPTO_FLAG_IFF) {
		scheme_name = "iff";
		scheme_id = CRYPTO_IFF;
	} else if (peer->crypto & CRYPTO_FLAG_GQ) {
		scheme_name = "gq";
		scheme_id = CRYPTO_GQ;
	} else if (peer->crypto & CRYPTO_FLAG_MV) {
		scheme_name = "mv";
		scheme_id = CRYPTO_MV;
	}

	if (scheme_name != NULL) {
		snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
		    scheme_name, peer->ident);
		peer->ident_pkey = crypto_key(filename, NULL,
		    &peer->srcadr);
		if (peer->ident_pkey != NULL)
			return scheme_id;
	}

	msyslog(LOG_NOTICE,
	    "crypto_ident: no identity parameters found for group %s",
	    peer->ident);

	return CRYPTO_NULL;
}


/*
 * crypto_args - construct extension field from arguments
 *
 * This routine creates an extension field with current timestamps and
 * specified opcode, association ID and optional string. Note that the
 * extension field is created here, but freed after the crypto_xmit()
 * call in the protocol module.
 *
 * Returns extension field pointer (no errors)
 *
 * XXX: opcode and len should really be 32-bit quantities and
 * we should make sure that str is not too big.
 */
struct exten *
crypto_args(
	struct peer *peer,	/* peer structure pointer */
	u_int	opcode,		/* operation code */
	associd_t associd,	/* association ID */
	char	*str		/* argument string */
	)
{
	tstamp_t tstamp;	/* NTP timestamp */
	struct exten *ep;	/* extension field pointer */
	u_int	len;		/* extension field length */
	size_t	slen = 0;

	tstamp = crypto_time();
	len = sizeof(struct exten);
	if (str != NULL) {
		slen = strlen(str);
		INSIST(slen < MAX_VALLEN);
		len += slen;
	}
	ep = emalloc_zero(len);
	if (opcode == 0)
		return (ep);

	REQUIRE(0 == (len    & ~0x0000ffff));
	REQUIRE(0 == (opcode & ~0xffff0000));

	ep->opcode = htonl(opcode + len);
	ep->associd = htonl(associd);
	ep->tstamp = htonl(tstamp);
	ep->fstamp = hostval.tstamp;
	ep->vallen = 0;
	if (str != NULL) {
		ep->vallen = htonl(slen);
		memcpy((char *)ep->pkt, str, slen);
	}
	return (ep);
}


/*
 * crypto_send - construct extension field from value components
 *
 * The value and signature fields are zero-padded to a word boundary.
 * Note: it is not polite to send a nonempty signature with zero
 * timestamp or a nonzero timestamp with an empty signature, but those
 * rules are not enforced here.
 *
 * XXX This code won't work on a box with 16-bit ints.
 */
int
crypto_send(
	struct exten *ep,	/* extension field pointer */
	struct value *vp,	/* value pointer */
	int	start		/* buffer offset */
	)
{
	u_int	len, vallen, siglen, opcode;
	u_int	i, j;

	/*
	 * Calculate extension field length and check for buffer
	 * overflow. Leave room for the MAC.
	 */
	len = 16;				/* XXX Document! */
	vallen = ntohl(vp->vallen);
	INSIST(vallen <= MAX_VALLEN);
	len += ((vallen + 3) / 4 + 1) * 4; 
	siglen = ntohl(vp->siglen);
	len += ((siglen + 3) / 4 + 1) * 4; 
	if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
		return (0);

	/*
	 * Copy timestamps.
	 */
	ep->tstamp = vp->tstamp;
	ep->fstamp = vp->fstamp;
	ep->vallen = vp->vallen;

	/*
	 * Copy value. If the data field is empty or zero length,
	 * encode an empty value with length zero.
	 */
	i = 0;
	if (vallen > 0 && vp->ptr != NULL) {
		j = vallen / 4;
		if (j * 4 < vallen)
			ep->pkt[i + j++] = 0;
		memcpy(&ep->pkt[i], vp->ptr, vallen);
		i += j;
	}

	/*
	 * Copy signature. If the signature field is empty or zero
	 * length, encode an empty signature with length zero.
	 */
	ep->pkt[i++] = vp->siglen;
	if (siglen > 0 && vp->sig != NULL) {
		j = siglen / 4;
		if (j * 4 < siglen)
			ep->pkt[i + j++] = 0;
		memcpy(&ep->pkt[i], vp->sig, siglen);
		/* i += j; */	/* We don't use i after this */
	}
	opcode = ntohl(ep->opcode);
	ep->opcode = htonl((opcode & 0xffff0000) | len); 
	ENSURE(len <= MAX_VALLEN);
	return (len);
}


/*
 * crypto_update - compute new public value and sign extension fields
 *
 * This routine runs periodically, like once a day, and when something
 * changes. It updates the timestamps on three value structures and one
 * value structure list, then signs all the structures:
 *
 * hostval	host name (not signed)
 * pubkey	public key
 * cinfo	certificate info/value list
 * tai_leap	leap values
 *
 * Filestamps are proventic data, so this routine runs only when the
 * host is synchronized to a proventicated source. Thus, the timestamp
 * is proventic and can be used to deflect clogging attacks.
 *
 * Returns void (no errors)
 */
void
crypto_update(void)
{
	EVP_MD_CTX *ctx;	/* message digest context */
	struct cert_info *cp;	/* certificate info/value */
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	u_int32	*ptr;
	u_int	len;
	leap_result_t leap_data;

	hostval.tstamp = htonl(crypto_time());
	if (hostval.tstamp == 0)
		return;

	ctx = EVP_MD_CTX_new();

	/*
	 * Sign public key and timestamps. The filestamp is derived from
	 * the host key file extension from wherever the file was
	 * generated. 
	 */
	if (pubkey.vallen != 0) {
		pubkey.tstamp = hostval.tstamp;
		pubkey.siglen = 0;
		if (pubkey.sig == NULL)
			pubkey.sig = emalloc(sign_siglen);
		EVP_SignInit(ctx, sign_digest);
		EVP_SignUpdate(ctx, (u_char *)&pubkey, 12);
		EVP_SignUpdate(ctx, pubkey.ptr, ntohl(pubkey.vallen));
		if (EVP_SignFinal(ctx, pubkey.sig, &len, sign_pkey)) {
			INSIST(len <= sign_siglen);
			pubkey.siglen = htonl(len);
		}
	}

	/*
	 * Sign certificates and timestamps. The filestamp is derived
	 * from the certificate file extension from wherever the file
	 * was generated. Note we do not throw expired certificates
	 * away; they may have signed younger ones.
	 */
	for (cp = cinfo; cp != NULL; cp = cp->link) {
		cp->cert.tstamp = hostval.tstamp;
		cp->cert.siglen = 0;
		if (cp->cert.sig == NULL)
			cp->cert.sig = emalloc(sign_siglen);
		EVP_SignInit(ctx, sign_digest);
		EVP_SignUpdate(ctx, (u_char *)&cp->cert, 12);
		EVP_SignUpdate(ctx, cp->cert.ptr,
		    ntohl(cp->cert.vallen));
		if (EVP_SignFinal(ctx, cp->cert.sig, &len, sign_pkey)) {
			INSIST(len <= sign_siglen);
			cp->cert.siglen = htonl(len);
		}
	}

	/*
	 * Sign leapseconds values and timestamps. Note it is not an
	 * error to return null values.
	 */
	tai_leap.tstamp = hostval.tstamp;
	tai_leap.fstamp = hostval.fstamp;

	/* Get the leap second era. We might need a full lookup early
	 * after start, when the cache is not yet loaded.
	 */
	leapsec_frame(&leap_data);
	if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
		time_t   now    = time(NULL);
		uint32_t nowntp = (uint32_t)now + JAN_1970;
		leapsec_query(&leap_data, nowntp, &now);
	}

	/* Create the data block. The protocol does not work without. */
	len = 3 * sizeof(u_int32);
	if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
		free(tai_leap.ptr);
		tai_leap.ptr = emalloc(len);
		tai_leap.vallen = htonl(len);
	}
	ptr = (u_int32 *)tai_leap.ptr;
	if (leap_data.tai_offs > 10) {
		/* create a TAI / leap era block. The end time is a
		 * fake -- maybe we can do better.
		 */
		ptr[0] = htonl(leap_data.tai_offs);
		ptr[1] = htonl(leap_data.ebase.d_s.lo);
		if (leap_data.ttime.d_s.hi >= 0)
			ptr[2] = htonl(leap_data.ttime.D_s.lo +  7*86400);
		else
			ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
	} else {
		/* no leap era available */
		memset(ptr, 0, len);
	}
	if (tai_leap.sig == NULL)
		tai_leap.sig = emalloc(sign_siglen);
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&tai_leap, 12);
	EVP_SignUpdate(ctx, tai_leap.ptr, len);
	if (EVP_SignFinal(ctx, tai_leap.sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		tai_leap.siglen = htonl(len);
	}
	crypto_flags |= CRYPTO_FLAG_TAI;

	snprintf(statstr, sizeof(statstr), "signature update ts %u",
	    ntohl(hostval.tstamp)); 
	record_crypto_stats(NULL, statstr);
	DPRINTF(1, ("crypto_update: %s\n", statstr));
	EVP_MD_CTX_free(ctx);
}

/*
 * crypto_update_taichange - eventually trigger crypto_update
 *
 * This is called when a change in 'sys_tai' is detected. This will
 * happen shortly after a leap second is detected, but unhappily also
 * early after system start; also, the crypto stuff might be unused and
 * an unguarded call to crypto_update() causes a crash.
 *
 * This function makes sure that there already *is* a valid crypto block
 * for the use with autokey, and only calls 'crypto_update()' if it can
 * succeed.
 *
 * Returns void (no errors)
 */
void
crypto_update_taichange(void)
{
	static const u_int len = 3 * sizeof(u_int32);

	/* check if the signing digest algo is available */
	if (sign_digest == NULL || sign_pkey == NULL)
		return;

	/* check size of TAI extension block */
	if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
		return;

	/* crypto_update should at least not crash here! */
	crypto_update();
}

/*
 * value_free - free value structure components.
 *
 * Returns void (no errors)
 */
void
value_free(
	struct value *vp	/* value structure */
	)
{
	if (vp->ptr != NULL)
		free(vp->ptr);
	if (vp->sig != NULL)
		free(vp->sig);
	memset(vp, 0, sizeof(struct value));
}


/*
 * crypto_time - returns current NTP time.
 *
 * Returns NTP seconds if in synch, 0 otherwise
 */
tstamp_t
crypto_time()
{
	l_fp	tstamp;		/* NTP time */

	L_CLR(&tstamp);
	if (sys_leap != LEAP_NOTINSYNC)
		get_systime(&tstamp);
	return (tstamp.l_ui);
}


/*
 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
 *
 */
static
void
asn_to_calendar	(
	ASN1_TIME *asn1time,	/* pointer to ASN1_TIME structure */
	struct calendar *pjd	/* pointer to result */
	)
{
	size_t	len;		/* length of ASN1_TIME string */
	char	v[24];		/* writable copy of ASN1_TIME string */
	unsigned long	temp;	/* result from strtoul */

	/*
	 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
	 * Or YYYYMMDDHHMMSSZ.
	 * Note that the YY, MM, DD fields start with one, the HH, MM,
	 * SS fields start with zero and the Z character is ignored.
	 * Also note that two-digit years less than 50 map to years greater than
	 * 100. Dontcha love ASN.1? Better than MIL-188.
	 */
	len = asn1time->length;
	REQUIRE(len < sizeof(v));
	(void)strncpy(v, (char *)(asn1time->data), len);
	REQUIRE(len >= 13);
	temp = strtoul(v+len-3, NULL, 10);
	pjd->second = temp;
	v[len-3] = '\0';

	temp = strtoul(v+len-5, NULL, 10);
	pjd->minute = temp;
	v[len-5] = '\0';

	temp = strtoul(v+len-7, NULL, 10);
	pjd->hour = temp;
	v[len-7] = '\0';

	temp = strtoul(v+len-9, NULL, 10);
	pjd->monthday = temp;
	v[len-9] = '\0';

	temp = strtoul(v+len-11, NULL, 10);
	pjd->month = temp;
	v[len-11] = '\0';

	temp = strtoul(v, NULL, 10);
	/* handle two-digit years */
	if (temp < 50UL)
	    temp += 100UL;
	if (temp < 150UL)
	    temp += 1900UL;
	pjd->year = temp;

	pjd->yearday = pjd->weekday = 0;
	return;
}


/*
 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
 *
 * Returns void (no errors)
 */
static void
bighash(
	BIGNUM	*bn,		/* BIGNUM * from */
	BIGNUM	*bk		/* BIGNUM * to */
	)
{
	EVP_MD_CTX *ctx;	/* message digest context */
	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
	u_char	*ptr;		/* a BIGNUM as binary string */
	u_int	len;

	len = BN_num_bytes(bn);
	ptr = emalloc(len);
	BN_bn2bin(bn, ptr);
	ctx = EVP_MD_CTX_new();
	EVP_DigestInit(ctx, EVP_md5());
	EVP_DigestUpdate(ctx, ptr, len);
	EVP_DigestFinal(ctx, dgst, &len);
	EVP_MD_CTX_free(ctx);
	BN_bin2bn(dgst, len, bk);
	free(ptr);
}


/*
 ***********************************************************************
 *								       *
 * The following routines implement the Schnorr (IFF) identity scheme  *
 *								       *
 ***********************************************************************
 *
 * The Schnorr (IFF) identity scheme is intended for use when
 * certificates are generated by some other trusted certificate
 * authority and the certificate cannot be used to convey public
 * parameters. There are two kinds of files: encrypted server files that
 * contain private and public values and nonencrypted client files that
 * contain only public values. New generations of server files must be
 * securely transmitted to all servers of the group; client files can be
 * distributed by any means. The scheme is self contained and
 * independent of new generations of host keys, sign keys and
 * certificates.
 *
 * The IFF values hide in a DSA cuckoo structure which uses the same
 * parameters. The values are used by an identity scheme based on DSA
 * cryptography and described in Stimson p. 285. The p is a 512-bit
 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
 * private random group key b (0 < b < q) and public key v = g^b, then
 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
 * Alice challenges Bob to confirm identity using the protocol described
 * below.
 *
 * How it works
 *
 * The scheme goes like this. Both Alice and Bob have the public primes
 * p, q and generator g. The TA gives private key b to Bob and public
 * key v to Alice.
 *
 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
 * the IFF request message. Bob rolls new random k (0 < k < q), then
 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
 * to Alice in the response message. Besides making the response
 * shorter, the hash makes it effectivey impossible for an intruder to
 * solve for b by observing a number of these messages.
 * 
 * Alice receives the response and computes g^y v^r mod p. After a bit
 * of algebra, this simplifies to g^k. If the hash of this result
 * matches hash(x), Alice knows that Bob has the group key b. The signed
 * response binds this knowledge to Bob's private key and the public key
 * previously received in his certificate.
 *
 * crypto_alice - construct Alice's challenge in IFF scheme
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ID	bad or missing group key
 * XEVNT_PUB	bad or missing public key
 */
static int
crypto_alice(
	struct peer *peer,	/* peer pointer */
	struct value *vp	/* value pointer */
	)
{
	DSA	*dsa;		/* IFF parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;
	u_int	len;
	const BIGNUM *q;

	/*
	 * The identity parameters must have correct format and content.
	 */
	if (peer->ident_pkey == NULL) {
		msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
		return (XEVNT_ID);
	}

	if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_alice: defective key");
		return (XEVNT_PUB);
	}

	/*
	 * Roll new random r (0 < r < q).
	 */
	if (peer->iffval != NULL)
		BN_free(peer->iffval);
	peer->iffval = BN_new();
	DSA_get0_pqg(dsa, NULL, &q, NULL);
	len = BN_num_bytes(q);
	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod q*/
	bctx = BN_CTX_new();
	BN_mod(peer->iffval, peer->iffval, q, bctx);
	BN_CTX_free(bctx);

	/*
	 * Sign and send to Bob. The filestamp is from the local file.
	 */
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(peer->ident_pkey->fstamp);
	vp->vallen = htonl(len);
	vp->ptr = emalloc(len);
	BN_bn2bin(peer->iffval, vp->ptr);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_bob - construct Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_ID	bad or missing group key
 */
static int
crypto_bob(
	struct exten *ep,	/* extension pointer */
	struct value *vp	/* value pointer */
	)
{
	DSA	*dsa;		/* IFF parameters */
	DSA_SIG	*sdsa;		/* DSA signature context fake */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;	/* NTP timestamp */
	BIGNUM	*bn, *bk, *r;
	u_char	*ptr;
	u_int	len;		/* extension field value length */
	const BIGNUM *p, *q, *g;
	const BIGNUM *priv_key;

	/*
	 * If the IFF parameters are not valid, something awful
	 * happened or we are being tormented.
	 */
	if (iffkey_info == NULL) {
		msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
		return (XEVNT_ID);
	}
	dsa = EVP_PKEY_get0_DSA(iffkey_info->pkey);
	DSA_get0_pqg(dsa, &p, &q, &g);
	DSA_get0_key(dsa, NULL, &priv_key);

	/*
	 * Extract r from the challenge.
	 */
	len = exten_payload_size(ep);
	if (len == 0 || len > MAX_VALLEN)
		return (XEVNT_LEN);
	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
		msyslog(LOG_ERR, "crypto_bob: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}

	/*
	 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
	 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
	 */
	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
	sdsa = DSA_SIG_new();
	BN_rand(bk, len * 8, -1, 1);		/* k */
	BN_mod_mul(bn, priv_key, r, q, bctx); /* b r mod q */
	BN_add(bn, bn, bk);
	BN_mod(bn, bn, q, bctx);		/* k + b r mod q */
	BN_mod_exp(bk, g, bk, p, bctx); /* g^k mod p */
	bighash(bk, bk);
	DSA_SIG_set0(sdsa, bn, bk);
	BN_CTX_free(bctx);
	BN_free(r);
#ifdef DEBUG
	if (debug > 1)
		DSA_print_fp(stdout, dsa, 0);
#endif

	/*
	 * Encode the values in ASN.1 and sign. The filestamp is from
	 * the local file.
	 */
	len = i2d_DSA_SIG(sdsa, NULL);
	if (len == 0) {
		msyslog(LOG_ERR, "crypto_bob: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		DSA_SIG_free(sdsa);
		return (XEVNT_ERR);
	}
	if (len > MAX_VALLEN) {
		msyslog(LOG_ERR, "crypto_bob: signature is too big: %u",
		    len);
		DSA_SIG_free(sdsa);
		return (XEVNT_LEN);
	}
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(iffkey_info->fstamp);
	vp->vallen = htonl(len);
	ptr = emalloc(len);
	vp->ptr = ptr;
	i2d_DSA_SIG(sdsa, &ptr);
	DSA_SIG_free(sdsa);
	if (tstamp == 0)
		return (XEVNT_OK);

	/* XXX: more validation to make sure the sign fits... */
	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_iff - verify Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_FSP	bad filestamp
 * XEVNT_ID	bad or missing group key
 * XEVNT_PUB	bad or missing public key
 */
int
crypto_iff(
	struct exten *ep,	/* extension pointer */
	struct peer *peer	/* peer structure pointer */
	)
{
	DSA	*dsa;		/* IFF parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	DSA_SIG	*sdsa;		/* DSA parameters */
	BIGNUM	*bn, *bk;
	u_int	len;
	const u_char *ptr;
	int	temp;
	const BIGNUM *p, *g;
	const BIGNUM *r, *s;
	const BIGNUM *pub_key;

	/*
	 * If the IFF parameters are not valid or no challenge was sent,
	 * something awful happened or we are being tormented.
	 */
	if (peer->ident_pkey == NULL) {
		msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
		return (XEVNT_ID);
	}
	if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
		msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
		    ntohl(ep->fstamp));
		return (XEVNT_FSP);
	}
	if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_iff: defective key");
		return (XEVNT_PUB);
	}
	if (peer->iffval == NULL) {
		msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
		return (XEVNT_ID);
	}

	/*
	 * Extract the k + b r and g^k values from the response.
	 */
	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
	len = ntohl(ep->vallen);
	ptr = (u_char *)ep->pkt;
	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
		BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
		msyslog(LOG_ERR, "crypto_iff: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}

	/*
	 * Compute g^(k + b r) g^(q - b)r mod p.
	 */
	DSA_get0_key(dsa, &pub_key, NULL);
	DSA_get0_pqg(dsa, &p, NULL, &g);
	DSA_SIG_get0(sdsa, &r, &s);
	BN_mod_exp(bn, pub_key, peer->iffval, p, bctx);
	BN_mod_exp(bk, g, r, p, bctx);
	BN_mod_mul(bn, bn, bk, p, bctx);

	/*
	 * Verify the hash of the result matches hash(x).
	 */
	bighash(bn, bn);
	temp = BN_cmp(bn, s);
	BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
	BN_free(peer->iffval);
	peer->iffval = NULL;
	DSA_SIG_free(sdsa);
	if (temp == 0)
		return (XEVNT_OK);

	msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
	return (XEVNT_ID);
}


/*
 ***********************************************************************
 *								       *
 * The following routines implement the Guillou-Quisquater (GQ)        *
 * identity scheme                                                     *
 *								       *
 ***********************************************************************
 *
 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
 * the certificate can be used to convey public parameters. The scheme
 * uses a X509v3 certificate extension field do convey the public key of
 * a private key known only to servers. There are two kinds of files:
 * encrypted server files that contain private and public values and
 * nonencrypted client files that contain only public values. New
 * generations of server files must be securely transmitted to all
 * servers of the group; client files can be distributed by any means.
 * The scheme is self contained and independent of new generations of
 * host keys and sign keys. The scheme is self contained and independent
 * of new generations of host keys and sign keys.
 *
 * The GQ parameters hide in a RSA cuckoo structure which uses the same
 * parameters. The values are used by an identity scheme based on RSA
 * cryptography and described in Stimson p. 300 (with errors). The 512-
 * bit public modulus is n = p q, where p and q are secret large primes.
 * The TA rolls private random group key b as RSA exponent. These values
 * are known to all group members.
 *
 * When rolling new certificates, a server recomputes the private and
 * public keys. The private key u is a random roll, while the public key
 * is the inverse obscured by the group key v = (u^-1)^b. These values
 * replace the private and public keys normally generated by the RSA
 * scheme. Alice challenges Bob to confirm identity using the protocol
 * described below.
 *
 * How it works
 *
 * The scheme goes like this. Both Alice and Bob have the same modulus n
 * and some random b as the group key. These values are computed and
 * distributed in advance via secret means, although only the group key
 * b is truly secret. Each has a private random private key u and public
 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
 * can regenerate the key pair from time to time without affecting
 * operations. The public key is conveyed on the certificate in an
 * extension field; the private key is never revealed.
 *
 * Alice rolls new random challenge r and sends to Bob in the GQ
 * request message. Bob rolls new random k, then computes y = k u^r mod
 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
 * message. Besides making the response shorter, the hash makes it
 * effectivey impossible for an intruder to solve for b by observing
 * a number of these messages.
 * 
 * Alice receives the response and computes y^b v^r mod n. After a bit
 * of algebra, this simplifies to k^b. If the hash of this result
 * matches hash(x), Alice knows that Bob has the group key b. The signed
 * response binds this knowledge to Bob's private key and the public key
 * previously received in his certificate.
 *
 * crypto_alice2 - construct Alice's challenge in GQ scheme
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ID	bad or missing group key
 * XEVNT_PUB	bad or missing public key
 */
static int
crypto_alice2(
	struct peer *peer,	/* peer pointer */
	struct value *vp	/* value pointer */
	)
{
	RSA	*rsa;		/* GQ parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;
	u_int	len;
	const BIGNUM *n;

	/*
	 * The identity parameters must have correct format and content.
	 */
	if (peer->ident_pkey == NULL)
		return (XEVNT_ID);

	if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_alice2: defective key");
		return (XEVNT_PUB);
	}

	/*
	 * Roll new random r (0 < r < n).
	 */
	if (peer->iffval != NULL)
		BN_free(peer->iffval);
	peer->iffval = BN_new();
	RSA_get0_key(rsa, &n, NULL, NULL);
	len = BN_num_bytes(n);
	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod n */
	bctx = BN_CTX_new();
	BN_mod(peer->iffval, peer->iffval, n, bctx);
	BN_CTX_free(bctx);

	/*
	 * Sign and send to Bob. The filestamp is from the local file.
	 */
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(peer->ident_pkey->fstamp);
	vp->vallen = htonl(len);
	vp->ptr = emalloc(len);
	BN_bn2bin(peer->iffval, vp->ptr);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_bob2 - construct Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_ID	bad or missing group key
 */
static int
crypto_bob2(
	struct exten *ep,	/* extension pointer */
	struct value *vp	/* value pointer */
	)
{
	RSA	*rsa;		/* GQ parameters */
	DSA_SIG	*sdsa;		/* DSA parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;	/* NTP timestamp */
	BIGNUM	*r, *k, *g, *y;
	u_char	*ptr;
	u_int	len;
	int	s_len;
	const BIGNUM *n, *p, *e;

	/*
	 * If the GQ parameters are not valid, something awful
	 * happened or we are being tormented.
	 */
	if (gqkey_info == NULL) {
		msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
		return (XEVNT_ID);
	}
	rsa = EVP_PKEY_get0_RSA(gqkey_info->pkey);
	RSA_get0_key(rsa, &n, &p, &e);

	/*
	 * Extract r from the challenge.
	 */
	len = exten_payload_size(ep);
	if (len == 0 || len > MAX_VALLEN)
		return (XEVNT_LEN);
	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
		msyslog(LOG_ERR, "crypto_bob2: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}

	/*
	 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
	 * x = k^b mod n, then sends (y, hash(x)) to Alice. 
	 */
	bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
	sdsa = DSA_SIG_new();
	BN_rand(k, len * 8, -1, 1);		/* k */
	BN_mod(k, k, n, bctx);
	BN_mod_exp(y, p, r, n, bctx); /* u^r mod n */
	BN_mod_mul(y, k, y, n, bctx);	/* k u^r mod n */
	BN_mod_exp(g, k, e, n, bctx); /* k^b mod n */
	bighash(g, g);
	DSA_SIG_set0(sdsa, y, g);
	BN_CTX_free(bctx);
	BN_free(r); BN_free(k);
#ifdef DEBUG
	if (debug > 1)
		RSA_print_fp(stdout, rsa, 0);
#endif
 
	/*
	 * Encode the values in ASN.1 and sign. The filestamp is from
	 * the local file.
	 */
	len = s_len = i2d_DSA_SIG(sdsa, NULL);
	if (s_len <= 0) {
		msyslog(LOG_ERR, "crypto_bob2: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		DSA_SIG_free(sdsa);
		return (XEVNT_ERR);
	}
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(gqkey_info->fstamp);
	vp->vallen = htonl(len);
	ptr = emalloc(len);
	vp->ptr = ptr;
	i2d_DSA_SIG(sdsa, &ptr);
	DSA_SIG_free(sdsa);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_gq - verify Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_FSP	bad filestamp
 * XEVNT_ID	bad or missing group keys
 * XEVNT_PUB	bad or missing public key
 */
int
crypto_gq(
	struct exten *ep,	/* extension pointer */
	struct peer *peer	/* peer structure pointer */
	)
{
	RSA	*rsa;		/* GQ parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	DSA_SIG	*sdsa;		/* RSA signature context fake */
	BIGNUM	*y, *v;
	const u_char *ptr;
	long	len;
	u_int	temp;
	const BIGNUM *n, *e;
	const BIGNUM *r, *s;

	/*
	 * If the GQ parameters are not valid or no challenge was sent,
	 * something awful happened or we are being tormented. Note that
	 * the filestamp on the local key file can be greater than on
	 * the remote parameter file if the keys have been refreshed.
	 */
	if (peer->ident_pkey == NULL) {
		msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
		return (XEVNT_ID);
	}
	if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
		msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
		    ntohl(ep->fstamp));
		return (XEVNT_FSP);
	}
	if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_gq: defective key");
		return (XEVNT_PUB);
	}
	RSA_get0_key(rsa, &n, NULL, &e);
	if (peer->iffval == NULL) {
		msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
		return (XEVNT_ID);
	}

	/*
	 * Extract the y = k u^r and hash(x = k^b) values from the
	 * response.
	 */
	bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
	len = ntohl(ep->vallen);
	ptr = (u_char *)ep->pkt;
	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
		BN_CTX_free(bctx); BN_free(y); BN_free(v);
		msyslog(LOG_ERR, "crypto_gq: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}
	DSA_SIG_get0(sdsa, &r, &s);

	/*
	 * Compute v^r y^b mod n.
	 */
	if (peer->grpkey == NULL) {
		msyslog(LOG_NOTICE, "crypto_gq: missing group key");
		return (XEVNT_ID);
	}
	BN_mod_exp(v, peer->grpkey, peer->iffval, n, bctx);
						/* v^r mod n */
	BN_mod_exp(y, r, e, n, bctx); /* y^b mod n */
	BN_mod_mul(y, v, y, n, bctx);	/* v^r y^b mod n */

	/*
	 * Verify the hash of the result matches hash(x).
	 */
	bighash(y, y);
	temp = BN_cmp(y, s);
	BN_CTX_free(bctx); BN_free(y); BN_free(v);
	BN_free(peer->iffval);
	peer->iffval = NULL;
	DSA_SIG_free(sdsa);
	if (temp == 0)
		return (XEVNT_OK);

	msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
	return (XEVNT_ID);
}


/*
 ***********************************************************************
 *								       *
 * The following routines implement the Mu-Varadharajan (MV) identity  *
 * scheme                                                              *
 *								       *
 ***********************************************************************
 *
 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
 * servers broadcast messages to clients, but clients never send
 * messages to servers. There is one encryption key for the server and a
 * separate decryption key for each client. It operated something like a
 * pay-per-view satellite broadcasting system where the session key is
 * encrypted by the broadcaster and the decryption keys are held in a
 * tamperproof set-top box.
 *
 * The MV parameters and private encryption key hide in a DSA cuckoo
 * structure which uses the same parameters, but generated in a
 * different way. The values are used in an encryption scheme similar to
 * El Gamal cryptography and a polynomial formed from the expansion of
 * product terms (x - x[j]), as described in Mu, Y., and V.
 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
 * 223-231. The paper has significant errors and serious omissions.
 *
 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
 * project into Zp* as exponents of g. Sometimes we have to compute an
 * inverse b^-1 of random b in Zq, but for that purpose we require
 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
 * relatively small, like 30. These are the parameters of the scheme and
 * they are expensive to compute.
 *
 * We set up an instance of the scheme as follows. A set of random
 * values x[j] mod q (j = 1...n), are generated as the zeros of a
 * polynomial of order n. The product terms (x - x[j]) are expanded to
 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
 * used as exponents of the generator g mod p to generate the private
 * encryption key A. The pair (gbar, ghat) of public server keys and the
 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
 * to construct the decryption keys. The devil is in the details.
 *
 * This routine generates a private server encryption file including the
 * private encryption key E and partial decryption keys gbar and ghat.
 * It then generates public client decryption files including the public
 * keys xbar[j] and xhat[j] for each client j. The partial decryption
 * files are used to compute the inverse of E. These values are suitably
 * blinded so secrets are not revealed.
 *
 * The distinguishing characteristic of this scheme is the capability to
 * revoke keys. Included in the calculation of E, gbar and ghat is the
 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
 * subsequently removed from the product and E, gbar and ghat
 * recomputed, the jth client will no longer be able to compute E^-1 and
 * thus unable to decrypt the messageblock.
 *
 * How it works
 *
 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
 * ghat) and Alice has the client values (p, xbar, xhat).
 *
 * Alice rolls new random nonce r mod p and sends to Bob in the MV
 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
 * mod p and sends (y, gbar^k, ghat^k) to Alice.
 * 
 * Alice receives the response and computes the inverse (E^k)^-1 from
 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
 * decrypts y and verifies it matches the original r. The signed
 * response binds this knowledge to Bob's private key and the public key
 * previously received in his certificate.
 *
 * crypto_alice3 - construct Alice's challenge in MV scheme
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ID	bad or missing group key
 * XEVNT_PUB	bad or missing public key
 */
static int
crypto_alice3(
	struct peer *peer,	/* peer pointer */
	struct value *vp	/* value pointer */
	)
{
	DSA	*dsa;		/* MV parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;
	u_int	len;
	const BIGNUM *p;

	/*
	 * The identity parameters must have correct format and content.
	 */
	if (peer->ident_pkey == NULL)
		return (XEVNT_ID);

	if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_alice3: defective key");
		return (XEVNT_PUB);
	}
	DSA_get0_pqg(dsa, &p, NULL, NULL);

	/*
	 * Roll new random r (0 < r < q).
	 */
	if (peer->iffval != NULL)
		BN_free(peer->iffval);
	peer->iffval = BN_new();
	len = BN_num_bytes(p);
	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod p */
	bctx = BN_CTX_new();
	BN_mod(peer->iffval, peer->iffval, p, bctx);
	BN_CTX_free(bctx);

	/*
	 * Sign and send to Bob. The filestamp is from the local file.
	 */
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(peer->ident_pkey->fstamp);
	vp->vallen = htonl(len);
	vp->ptr = emalloc(len);
	BN_bn2bin(peer->iffval, vp->ptr);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_bob3 - construct Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 */
static int
crypto_bob3(
	struct exten *ep,	/* extension pointer */
	struct value *vp	/* value pointer */
	)
{
	DSA	*dsa;		/* MV parameters */
	DSA	*sdsa;		/* DSA signature context fake */
	BN_CTX	*bctx;		/* BIGNUM context */
	EVP_MD_CTX *ctx;	/* signature context */
	tstamp_t tstamp;	/* NTP timestamp */
	BIGNUM	*r, *k, *u;
	u_char	*ptr;
	u_int	len;
	const BIGNUM *p, *q, *g;
	const BIGNUM *pub_key, *priv_key;
	BIGNUM *sp, *sq, *sg;

	/*
	 * If the MV parameters are not valid, something awful
	 * happened or we are being tormented.
	 */
	if (mvkey_info == NULL) {
		msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
		return (XEVNT_ID);
	}
	dsa = EVP_PKEY_get0_DSA(mvkey_info->pkey);
	DSA_get0_pqg(dsa, &p, &q, &g);
	DSA_get0_key(dsa, &pub_key, &priv_key);

	/*
	 * Extract r from the challenge.
	 */
	len = exten_payload_size(ep);
	if (len == 0 || len > MAX_VALLEN)
		return (XEVNT_LEN);
	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
		msyslog(LOG_ERR, "crypto_bob3: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}

	/*
	 * Bob rolls random k (0 < k < q), making sure it is not a
	 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
	 * and ghat^k) to Alice.
	 */
	bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
	sdsa = DSA_new();
	sp = BN_new(); sq = BN_new(); sg = BN_new();
	while (1) {
		BN_rand(k, BN_num_bits(q), 0, 0);
		BN_mod(k, k, q, bctx);
		BN_gcd(u, k, q, bctx);
		if (BN_is_one(u))
			break;
	}
	BN_mod_exp(u, g, k, p, bctx); /* A^k r */
	BN_mod_mul(sp, u, r, p, bctx);
	BN_mod_exp(sq, priv_key, k, p, bctx); /* gbar */
	BN_mod_exp(sg, pub_key, k, p, bctx); /* ghat */
	DSA_set0_key(sdsa, BN_dup(pub_key), NULL);
	DSA_set0_pqg(sdsa, sp, sq, sg);
	BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
#ifdef DEBUG
	if (debug > 1)
		DSA_print_fp(stdout, sdsa, 0);
#endif

	/*
	 * Encode the values in ASN.1 and sign. The filestamp is from
	 * the local file.
	 */
	memset(vp, 0, sizeof(struct value));
	tstamp = crypto_time();
	vp->tstamp = htonl(tstamp);
	vp->fstamp = htonl(mvkey_info->fstamp);
	len = i2d_DSAparams(sdsa, NULL);
	if (len == 0) {
		msyslog(LOG_ERR, "crypto_bob3: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		DSA_free(sdsa);
		return (XEVNT_ERR);
	}
	vp->vallen = htonl(len);
	ptr = emalloc(len);
	vp->ptr = ptr;
	i2d_DSAparams(sdsa, &ptr);
	DSA_free(sdsa);
	if (tstamp == 0)
		return (XEVNT_OK);

	vp->sig = emalloc(sign_siglen);
	ctx = EVP_MD_CTX_new();
	EVP_SignInit(ctx, sign_digest);
	EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
	EVP_SignUpdate(ctx, vp->ptr, len);
	if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
		INSIST(len <= sign_siglen);
		vp->siglen = htonl(len);
	}
	EVP_MD_CTX_free(ctx);
	return (XEVNT_OK);
}


/*
 * crypto_mv - verify Bob's response to Alice's challenge
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_ERR	protocol error
 * XEVNT_FSP	bad filestamp
 * XEVNT_ID	bad or missing group key
 * XEVNT_PUB	bad or missing public key
 */
int
crypto_mv(
	struct exten *ep,	/* extension pointer */
	struct peer *peer	/* peer structure pointer */
	)
{
	DSA	*dsa;		/* MV parameters */
	DSA	*sdsa;		/* DSA parameters */
	BN_CTX	*bctx;		/* BIGNUM context */
	BIGNUM	*k, *u, *v;
	u_int	len;
	const u_char *ptr;
	int	temp;
	const BIGNUM *p;
	const BIGNUM *pub_key, *priv_key;
	const BIGNUM *sp, *sq, *sg;

	/*
	 * If the MV parameters are not valid or no challenge was sent,
	 * something awful happened or we are being tormented.
	 */
	if (peer->ident_pkey == NULL) {
		msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
		return (XEVNT_ID);
	}
	if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
		msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
		    ntohl(ep->fstamp));
		return (XEVNT_FSP);
	}
	if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
		msyslog(LOG_NOTICE, "crypto_mv: defective key");
		return (XEVNT_PUB);
	}
	DSA_get0_pqg(dsa, &p, NULL, NULL);
	DSA_get0_key(dsa, &pub_key, &priv_key);
	if (peer->iffval == NULL) {
		msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
		return (XEVNT_ID);
	}

	/*
	 * Extract the y, gbar and ghat values from the response.
	 */
	bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
	len = ntohl(ep->vallen);
	ptr = (u_char *)ep->pkt;
	if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
		msyslog(LOG_ERR, "crypto_mv: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_ERR);
	}
	DSA_get0_pqg(sdsa, &sp, &sq, &sg);

	/*
	 * Compute (gbar^xhat ghat^xbar) mod p.
	 */
	BN_mod_exp(u, sq, pub_key, p, bctx);
	BN_mod_exp(v, sg, priv_key, p, bctx);
	BN_mod_mul(u, u, v, p, bctx);
	BN_mod_mul(u, u, sp, p, bctx);

	/*
	 * The result should match r.
	 */
	temp = BN_cmp(u, peer->iffval);
	BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
	BN_free(peer->iffval);
	peer->iffval = NULL;
	DSA_free(sdsa);
	if (temp == 0)
		return (XEVNT_OK);

	msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
	return (XEVNT_ID);
}


/*
 ***********************************************************************
 *								       *
 * The following routines are used to manipulate certificates          *
 *								       *
 ***********************************************************************
 */
/*
 * cert_sign - sign x509 certificate equest and update value structure.
 *
 * The certificate request includes a copy of the host certificate,
 * which includes the version number, subject name and public key of the
 * host. The resulting certificate includes these values plus the
 * serial number, issuer name and valid interval of the server. The
 * valid interval extends from the current time to the same time one
 * year hence. This may extend the life of the signed certificate beyond
 * that of the signer certificate.
 *
 * It is convenient to use the NTP seconds of the current time as the
 * serial number. In the value structure the timestamp is the current
 * time and the filestamp is taken from the extension field. Note this
 * routine is called only when the client clock is synchronized to a
 * proventic source, so timestamp comparisons are valid.
 *
 * The host certificate is valid from the time it was generated for a
 * period of one year. A signed certificate is valid from the time of
 * signature for a period of one year, but only the host certificate (or
 * sign certificate if used) is actually used to encrypt and decrypt
 * signatures. The signature trail is built from the client via the
 * intermediate servers to the trusted server. Each signature on the
 * trail must be valid at the time of signature, but it could happen
 * that a signer certificate expire before the signed certificate, which
 * remains valid until its expiration. 
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_CRT	bad or missing certificate
 * XEVNT_PER	host certificate expired
 * XEVNT_PUB	bad or missing public key
 * XEVNT_VFY	certificate not verified
 */
static int
cert_sign(
	struct exten *ep,	/* extension field pointer */
	struct value *vp	/* value pointer */
	)
{
	X509	*req;		/* X509 certificate request */
	X509	*cert;		/* X509 certificate */
	X509_EXTENSION *ext;	/* certificate extension */
	ASN1_INTEGER *serial;	/* serial number */
	X509_NAME *subj;	/* distinguished (common) name */
	EVP_PKEY *pkey;		/* public key */
	EVP_MD_CTX *ctx;	/* message digest context */
	tstamp_t tstamp;	/* NTP timestamp */
	struct calendar tscal;
	u_int	len;
	const u_char *cptr;
	u_char *ptr;
	int	i, temp;

	/*
	 * Decode ASN.1 objects and construct certificate structure.
	 * Make sure the system clock is synchronized to a proventic
	 * source.
	 */
	tstamp = crypto_time();
	if (tstamp == 0)
		return (XEVNT_TSP);

	len = exten_payload_size(ep);
	if (len == 0 || len > MAX_VALLEN)
		return (XEVNT_LEN);
	cptr = (void *)ep->pkt;
	if ((req = d2i_X509(NULL, &cptr, len)) == NULL) {
		msyslog(LOG_ERR, "cert_sign: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (XEVNT_CRT);
	}
	/*
	 * Extract public key and check for errors.
	 */
	if ((pkey = X509_get_pubkey(req)) == NULL) {
		msyslog(LOG_ERR, "cert_sign: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		X509_free(req);
		return (XEVNT_PUB);
	}

	/*
	 * Generate X509 certificate signed by this server. If this is a
	 * trusted host, the issuer name is the group name; otherwise,
	 * it is the host name. Also copy any extensions that might be
	 * present.
	 */
	cert = X509_new();
	X509_set_version(cert, X509_get_version(req));
	serial = ASN1_INTEGER_new();
	ASN1_INTEGER_set(serial, tstamp);
	X509_set_serialNumber(cert, serial);
	X509_gmtime_adj(X509_get_notBefore(cert), 0L);
	X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
	subj = X509_get_issuer_name(cert);
	X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
	    hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
	subj = X509_get_subject_name(req);
	X509_set_subject_name(cert, subj);
	X509_set_pubkey(cert, pkey);
	temp = X509_get_ext_count(req);
	for (i = 0; i < temp; i++) {
		ext = X509_get_ext(req, i);
		INSIST(X509_add_ext(cert, ext, -1));
	}
	X509_free(req);

	/*
	 * Sign and verify the client certificate, but only if the host
	 * certificate has not expired.
	 */
	(void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
	if ((calcomp(&tscal, &(cert_host->first)) < 0)
	|| (calcomp(&tscal, &(cert_host->last)) > 0)) {
		X509_free(cert);
		return (XEVNT_PER);
	}
	X509_sign(cert, sign_pkey, sign_digest);
	if (X509_verify(cert, sign_pkey) <= 0) {
		msyslog(LOG_ERR, "cert_sign: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		X509_free(cert);
		return (XEVNT_VFY);
	}
	len = i2d_X509(cert, NULL);

	/*
	 * Build and sign the value structure. We have to sign it here,
	 * since the response has to be returned right away. This is a
	 * clogging hazard.
	 */
	memset(vp, 0, sizeof(struct value));
	vp->tstamp = htonl(tstamp);
	vp->fstamp = ep->fstamp;
	vp->vallen = htonl(len);
	vp->ptr = emalloc(len);
	ptr = vp->ptr;
	i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
	vp->siglen = 0;
	if (tstamp != 0) {
		vp->sig = emalloc(sign_siglen);
		ctx = EVP_MD_CTX_new();
		EVP_SignInit(ctx, sign_digest);
		EVP_SignUpdate(ctx, (u_char *)vp, 12);
		EVP_SignUpdate(ctx, vp->ptr, len);
		if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
			INSIST(len <= sign_siglen);
			vp->siglen = htonl(len);
		}
		EVP_MD_CTX_free(ctx);
	}
#ifdef DEBUG
	if (debug > 1)
		X509_print_fp(stdout, cert);
#endif
	X509_free(cert);
	return (XEVNT_OK);
}


/*
 * cert_install - install certificate in certificate cache
 *
 * This routine encodes an extension field into a certificate info/value
 * structure. It searches the certificate list for duplicates and
 * expunges whichever is older. Finally, it inserts this certificate
 * first on the list.
 *
 * Returns certificate info pointer if valid, NULL if not.
 */
struct cert_info *
cert_install(
	struct exten *ep,	/* cert info/value */
	struct peer *peer	/* peer structure */
	)
{
	struct cert_info *cp, *xp, **zp;

	/*
	 * Parse and validate the signed certificate. If valid,
	 * construct the info/value structure; otherwise, scamper home
	 * empty handed.
	 */
	if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
	    (tstamp_t)ntohl(ep->fstamp))) == NULL)
		return (NULL);

	/*
	 * Scan certificate list looking for another certificate with
	 * the same subject and issuer. If another is found with the
	 * same or older filestamp, unlink it and return the goodies to
	 * the heap. If another is found with a later filestamp, discard
	 * the new one and leave the building with the old one.
	 *
	 * Make a note to study this issue again. An earlier certificate
	 * with a long lifetime might be overtaken by a later
	 * certificate with a short lifetime, thus invalidating the
	 * earlier signature. However, we gotta find a way to leak old
	 * stuff from the cache, so we do it anyway. 
	 */
	zp = &cinfo;
	for (xp = cinfo; xp != NULL; xp = xp->link) {
		if (strcmp(cp->subject, xp->subject) == 0 &&
		    strcmp(cp->issuer, xp->issuer) == 0) {
			if (ntohl(cp->cert.fstamp) <=
			    ntohl(xp->cert.fstamp)) {
				cert_free(cp);
				cp = xp;
			} else {
				*zp = xp->link;
				cert_free(xp);
				xp = NULL;
			}
			break;
		}
		zp = &xp->link;
	}
	if (xp == NULL) {
		cp->link = cinfo;
		cinfo = cp;
	}
	cp->flags |= CERT_VALID;
	crypto_update();
	return (cp);
}


/*
 * cert_hike - verify the signature using the issuer public key
 *
 * Returns
 * XEVNT_OK	success
 * XEVNT_CRT	bad or missing certificate
 * XEVNT_PER	host certificate expired
 * XEVNT_VFY	certificate not verified
 */
int
cert_hike(
	struct peer *peer,	/* peer structure pointer */
	struct cert_info *yp	/* issuer certificate */
	)
{
	struct cert_info *xp;	/* subject certificate */
	X509	*cert;		/* X509 certificate */
	const u_char *ptr;

	/*
	 * Save the issuer on the new certificate, but remember the old
	 * one.
	 */
	if (peer->issuer != NULL)
		free(peer->issuer);
	peer->issuer = estrdup(yp->issuer);
	xp = peer->xinfo;
	peer->xinfo = yp;

	/*
	 * If subject Y matches issuer Y, then the certificate trail is
	 * complete. If Y is not trusted, the server certificate has yet
	 * been signed, so keep trying. Otherwise, save the group key
	 * and light the valid bit. If the host certificate is trusted,
	 * do not execute a sign exchange. If no identity scheme is in
	 * use, light the identity and proventic bits.
	 */
	if (strcmp(yp->subject, yp->issuer) == 0) {
		if (!(yp->flags & CERT_TRUST))
			return (XEVNT_OK);

		/*
		 * If the server has an an identity scheme, fetch the
		 * identity credentials. If not, the identity is
		 * verified only by the trusted certificate. The next
		 * signature will set the server proventic.
		 */
		peer->crypto |= CRYPTO_FLAG_CERT;
		peer->grpkey = yp->grpkey;
		if (peer->ident == NULL || !(peer->crypto &
		    CRYPTO_FLAG_MASK))
			peer->crypto |= CRYPTO_FLAG_VRFY;
	}

	/*
	 * If X exists, verify signature X using public key Y.
	 */
	if (xp == NULL)
		return (XEVNT_OK);

	ptr = (u_char *)xp->cert.ptr;
	cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
	if (cert == NULL) {
		xp->flags |= CERT_ERROR;
		return (XEVNT_CRT);
	}
	if (X509_verify(cert, yp->pkey) <= 0) {
		X509_free(cert);
		xp->flags |= CERT_ERROR;
		return (XEVNT_VFY);
	}
	X509_free(cert);

	/*
	 * Signature X is valid only if it begins during the
	 * lifetime of Y. 
	 */
	if ((calcomp(&(xp->first), &(yp->first)) < 0)
	|| (calcomp(&(xp->first), &(yp->last)) > 0)) {
		xp->flags |= CERT_ERROR;
		return (XEVNT_PER);
	}
	xp->flags |= CERT_SIGN;
	return (XEVNT_OK);
}


/*
 * cert_parse - parse x509 certificate and create info/value structures.
 *
 * The server certificate includes the version number, issuer name,
 * subject name, public key and valid date interval. If the issuer name
 * is the same as the subject name, the certificate is self signed and
 * valid only if the server is configured as trustable. If the names are
 * different, another issuer has signed the server certificate and
 * vouched for it. In this case the server certificate is valid if
 * verified by the issuer public key.
 *
 * Returns certificate info/value pointer if valid, NULL if not.
 */
struct cert_info *		/* certificate information structure */
cert_parse(
	const u_char *asn1cert,	/* X509 certificate */
	long	len,		/* certificate length */
	tstamp_t fstamp		/* filestamp */
	)
{
	X509	*cert;		/* X509 certificate */
	struct cert_info *ret;	/* certificate info/value */
	BIO	*bp;
	char	pathbuf[MAXFILENAME];
	const u_char *ptr;
	char	*pch;
	int	cnt, i;
	struct calendar fscal;

	/*
	 * Decode ASN.1 objects and construct certificate structure.
	 */
	ptr = asn1cert;
	if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
		msyslog(LOG_ERR, "cert_parse: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		return (NULL);
	}
#ifdef DEBUG
	if (debug > 1)
		X509_print_fp(stdout, cert);
#endif

	/*
	 * Extract version, subject name and public key.
	 */
	ret = emalloc_zero(sizeof(*ret));
	if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
		msyslog(LOG_ERR, "cert_parse: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		cert_free(ret);
		X509_free(cert);
		return (NULL);
	}
	ret->version = X509_get_version(cert);
	X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
	    sizeof(pathbuf));
	pch = strstr(pathbuf, "CN=");
	if (NULL == pch) {
		msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
		    pathbuf);
		cert_free(ret);
		X509_free(cert);
		return (NULL);
	}
	ret->subject = estrdup(pch + 3);

	/*
	 * Extract remaining objects. Note that the NTP serial number is
	 * the NTP seconds at the time of signing, but this might not be
	 * the case for other authority. We don't bother to check the
	 * objects at this time, since the real crunch can happen only
	 * when the time is valid but not yet certificated.
	 */
	ret->nid = X509_get_signature_nid(cert);
	ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
	ret->serial =
	    (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
	X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
	    sizeof(pathbuf));
	if ((pch = strstr(pathbuf, "CN=")) == NULL) {
		msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
		    pathbuf);
		cert_free(ret);
		X509_free(cert);
		return (NULL);
	}
	ret->issuer = estrdup(pch + 3);
	asn_to_calendar(X509_get_notBefore(cert), &(ret->first));
	asn_to_calendar(X509_get_notAfter(cert), &(ret->last));

	/*
	 * Extract extension fields. These are ad hoc ripoffs of
	 * currently assigned functions and will certainly be changed
	 * before prime time.
	 */
	cnt = X509_get_ext_count(cert);
	for (i = 0; i < cnt; i++) {
		X509_EXTENSION *ext;
		ASN1_OBJECT *obj;
		int nid;
		ASN1_OCTET_STRING *data;

		ext = X509_get_ext(cert, i);
		obj = X509_EXTENSION_get_object(ext);
		nid = OBJ_obj2nid(obj);

		switch (nid) {

		/*
		 * If a key_usage field is present, we decode whether
		 * this is a trusted or private certificate. This is
		 * dorky; all we want is to compare NIDs, but OpenSSL
		 * insists on BIO text strings.
		 */
		case NID_ext_key_usage:
			bp = BIO_new(BIO_s_mem());
			X509V3_EXT_print(bp, ext, 0, 0);
			BIO_gets(bp, pathbuf, sizeof(pathbuf));
			BIO_free(bp);
			if (strcmp(pathbuf, "Trust Root") == 0)
				ret->flags |= CERT_TRUST;
			else if (strcmp(pathbuf, "Private") == 0)
				ret->flags |= CERT_PRIV;
			DPRINTF(1, ("cert_parse: %s: %s\n",
				    OBJ_nid2ln(nid), pathbuf));
			break;

		/*
		 * If a NID_subject_key_identifier field is present, it
		 * contains the GQ public key.
		 */
		case NID_subject_key_identifier:
			data = X509_EXTENSION_get_data(ext);
			ret->grpkey = BN_bin2bn(&data->data[2],
			    data->length - 2, NULL);
			/* fall through */
		default:
			DPRINTF(1, ("cert_parse: %s\n",
				    OBJ_nid2ln(nid)));
			break;
		}
	}
	if (strcmp(ret->subject, ret->issuer) == 0) {

		/*
		 * If certificate is self signed, verify signature.
		 */
		if (X509_verify(cert, ret->pkey) <= 0) {
			msyslog(LOG_NOTICE,
			    "cert_parse: signature not verified %s",
			    ret->subject);
			cert_free(ret);
			X509_free(cert);
			return (NULL);
		}
	} else {

		/*
		 * Check for a certificate loop.
		 */
		if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
			msyslog(LOG_NOTICE,
			    "cert_parse: certificate trail loop %s",
			    ret->subject);
			cert_free(ret);
			X509_free(cert);
			return (NULL);
		}
	}

	/*
	 * Verify certificate valid times. Note that certificates cannot
	 * be retroactive.
	 */
	(void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
	if ((calcomp(&(ret->first), &(ret->last)) > 0)
	|| (calcomp(&(ret->first), &fscal) < 0)) {
		msyslog(LOG_NOTICE,
		    "cert_parse: invalid times %s first %u-%02u-%02uT%02u:%02u:%02u last %u-%02u-%02uT%02u:%02u:%02u fstamp %u-%02u-%02uT%02u:%02u:%02u",
		    ret->subject,
		    ret->first.year, ret->first.month, ret->first.monthday,
		    ret->first.hour, ret->first.minute, ret->first.second,
		    ret->last.year, ret->last.month, ret->last.monthday,
		    ret->last.hour, ret->last.minute, ret->last.second,
		    fscal.year, fscal.month, fscal.monthday,
		    fscal.hour, fscal.minute, fscal.second);
		cert_free(ret);
		X509_free(cert);
		return (NULL);
	}

	/*
	 * Build the value structure to sign and send later.
	 */
	ret->cert.fstamp = htonl(fstamp);
	ret->cert.vallen = htonl(len);
	ret->cert.ptr = emalloc(len);
	memcpy(ret->cert.ptr, asn1cert, len);
	X509_free(cert);
	return (ret);
}


/*
 * cert_free - free certificate information structure
 */
void
cert_free(
	struct cert_info *cinf	/* certificate info/value structure */ 
	)
{
	if (cinf->pkey != NULL)
		EVP_PKEY_free(cinf->pkey);
	if (cinf->subject != NULL)
		free(cinf->subject);
	if (cinf->issuer != NULL)
		free(cinf->issuer);
	if (cinf->grpkey != NULL)
		BN_free(cinf->grpkey);
	value_free(&cinf->cert);
	free(cinf);
}


/*
 * crypto_key - load cryptographic parameters and keys
 *
 * This routine searches the key cache for matching name in the form
 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
 * and <name> is the host/group name. If not found, it tries to load a
 * PEM-encoded file of the same name and extracts the filestamp from
 * the first line of the file name. It returns the key pointer if valid,
 * NULL if not.
 */
static struct pkey_info *
crypto_key(
	char	*cp,		/* file name */
	char	*passwd1,	/* password */
	sockaddr_u *addr 	/* IP address */
	)
{
	FILE	*str;		/* file handle */
	struct pkey_info *pkp;	/* generic key */
	EVP_PKEY *pkey = NULL;	/* public/private key */
	tstamp_t fstamp;
	char	filename[MAXFILENAME]; /* name of key file */
	char	linkname[MAXFILENAME]; /* filestamp buffer) */
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	char	*ptr;

	/*
	 * Search the key cache for matching key and name.
	 */
	for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
		if (strcmp(cp, pkp->name) == 0)
			return (pkp);
	}  

	/*
	 * Open the key file. If the first character of the file name is
	 * not '/', prepend the keys directory string. If something goes
	 * wrong, abandon ship.
	 */
	if (*cp == '/')
		strlcpy(filename, cp, sizeof(filename));
	else
		snprintf(filename, sizeof(filename), "%s/%s", keysdir,
		    cp);
	str = fopen(filename, "r");
	if (str == NULL)
		return (NULL);

	/*
	 * Read the filestamp, which is contained in the first line.
	 */
	if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
		msyslog(LOG_ERR, "crypto_key: empty file %s",
		    filename);
		fclose(str);
		return (NULL);
	}
	if ((ptr = strrchr(ptr, '.')) == NULL) {
		msyslog(LOG_ERR, "crypto_key: no filestamp %s",
		    filename);
		fclose(str);
		return (NULL);
	}
	if (sscanf(++ptr, "%u", &fstamp) != 1) {
		msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
		    filename);
		fclose(str);
		return (NULL);
	}

	/*
	 * Read and decrypt PEM-encoded private key. If it fails to
	 * decrypt, game over.
	 */
	pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
	fclose(str);
	if (pkey == NULL) {
		msyslog(LOG_ERR, "crypto_key: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		exit (-1);
	}

	/*
	 * Make a new entry in the key cache.
	 */
	pkp = emalloc(sizeof(struct pkey_info));
	pkp->link = pkinfo;
	pkinfo = pkp;
	pkp->pkey = pkey;
	pkp->name = estrdup(cp);
	pkp->fstamp = fstamp;

	/*
	 * Leave tracks in the cryptostats.
	 */
	if ((ptr = strrchr(linkname, '\n')) != NULL)
		*ptr = '\0'; 
	snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
	    EVP_PKEY_size(pkey) * 8);
	record_crypto_stats(addr, statstr);
	
	DPRINTF(1, ("crypto_key: %s\n", statstr));
#ifdef DEBUG
	if (debug > 1) {
		if (EVP_PKEY_base_id(pkey) == EVP_PKEY_DSA)
			DSA_print_fp(stdout, EVP_PKEY_get0_DSA(pkey), 0);
		else if (EVP_PKEY_base_id(pkey) == EVP_PKEY_RSA)
			RSA_print_fp(stdout, EVP_PKEY_get0_RSA(pkey), 0);
	}
#endif
	return (pkp);
}


/*
 ***********************************************************************
 *								       *
 * The following routines are used only at initialization time         *
 *								       *
 ***********************************************************************
 */
/*
 * crypto_cert - load certificate from file
 *
 * This routine loads an X.509 RSA or DSA certificate from a file and
 * constructs a info/cert value structure for this machine. The
 * structure includes a filestamp extracted from the file name. Later
 * the certificate can be sent to another machine on request.
 *
 * Returns certificate info/value pointer if valid, NULL if not.
 */
static struct cert_info *	/* certificate information */
crypto_cert(
	char	*cp		/* file name */
	)
{
	struct cert_info *ret; /* certificate information */
	FILE	*str;		/* file handle */
	char	filename[MAXFILENAME]; /* name of certificate file */
	char	linkname[MAXFILENAME]; /* filestamp buffer */
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	tstamp_t fstamp;	/* filestamp */
	long	len;
	char	*ptr;
	char	*name, *header;
	u_char	*data;

	/*
	 * Open the certificate file. If the first character of the file
	 * name is not '/', prepend the keys directory string. If
	 * something goes wrong, abandon ship.
	 */
	if (*cp == '/')
		strlcpy(filename, cp, sizeof(filename));
	else
		snprintf(filename, sizeof(filename), "%s/%s", keysdir,
		    cp);
	str = fopen(filename, "r");
	if (str == NULL)
		return (NULL);

	/*
	 * Read the filestamp, which is contained in the first line.
	 */
	if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
		msyslog(LOG_ERR, "crypto_cert: empty file %s",
		    filename);
		fclose(str);
		return (NULL);
	}
	if ((ptr = strrchr(ptr, '.')) == NULL) {
		msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
		    filename);
		fclose(str);
		return (NULL);
	}
	if (sscanf(++ptr, "%u", &fstamp) != 1) {
		msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
		    filename);
		fclose(str);
		return (NULL);
	}

	/*
	 * Read PEM-encoded certificate and install.
	 */
	if (!PEM_read(str, &name, &header, &data, &len)) {
		msyslog(LOG_ERR, "crypto_cert: %s",
		    ERR_error_string(ERR_get_error(), NULL));
		fclose(str);
		return (NULL);
	}
	fclose(str);
	free(header);
	if (strcmp(name, "CERTIFICATE") != 0) {
		msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
		    name);
		free(name);
		free(data);
		return (NULL);
	}
	free(name);

	/*
	 * Parse certificate and generate info/value structure. The
	 * pointer and copy nonsense is due something broken in Solaris.
	 */
	ret = cert_parse(data, len, fstamp);
	free(data);
	if (ret == NULL)
		return (NULL);

	if ((ptr = strrchr(linkname, '\n')) != NULL)
		*ptr = '\0'; 
	snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
	    &linkname[2], ret->flags, len);
	record_crypto_stats(NULL, statstr);
	DPRINTF(1, ("crypto_cert: %s\n", statstr));
	return (ret);
}


/*
 * crypto_setup - load keys, certificate and identity parameters
 *
 * This routine loads the public/private host key and certificate. If
 * available, it loads the public/private sign key, which defaults to
 * the host key. The host key must be RSA, but the sign key can be
 * either RSA or DSA. If a trusted certificate, it loads the identity
 * parameters. In either case, the public key on the certificate must
 * agree with the sign key.
 *
 * Required but missing files and inconsistent data and errors are
 * fatal. Allowing configuration to continue would be hazardous and
 * require really messy error checks.
 */
void
crypto_setup(void)
{
	struct pkey_info *pinfo; /* private/public key */
	char	filename[MAXFILENAME]; /* file name buffer */
	char	hostname[MAXFILENAME]; /* host name buffer */
	char	*randfile;
	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
	l_fp	seed;		/* crypto PRNG seed as NTP timestamp */
	u_int	len;
	int	bytes;
	u_char	*ptr;

	/*
	 * Check for correct OpenSSL version and avoid initialization in
	 * the case of multiple crypto commands.
	 */
	if (crypto_flags & CRYPTO_FLAG_ENAB) {
		msyslog(LOG_NOTICE,
		    "crypto_setup: spurious crypto command");
		return;
	}
	ssl_check_version();

	/*
	 * Load required random seed file and seed the random number
	 * generator. Be default, it is found as .rnd in the user home
	 * directory. The root home directory may be / or /root,
	 * depending on the system. Wiggle the contents a bit and write
	 * it back so the sequence does not repeat when we next restart.
	 */
	if (!RAND_status()) {
		if (rand_file == NULL) {
			RAND_file_name(filename, sizeof(filename));
			randfile = filename;
		} else if (*rand_file != '/') {
			snprintf(filename, sizeof(filename), "%s/%s",
			    keysdir, rand_file);
			randfile = filename;
		} else
			randfile = rand_file;

		if ((bytes = RAND_load_file(randfile, -1)) == 0) {
			msyslog(LOG_ERR,
			    "crypto_setup: random seed file %s missing",
			    randfile);
			exit (-1);
		}
		arc4random_buf(&seed, sizeof(l_fp));
		RAND_seed(&seed, sizeof(l_fp));
		RAND_write_file(randfile);
		DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
			    SSLeay(), randfile, bytes));
	}

	/*
	 * Initialize structures.
	 */
	gethostname(hostname, sizeof(hostname));
	if (host_filename != NULL)
		strlcpy(hostname, host_filename, sizeof(hostname));
	if (passwd == NULL)
		passwd = estrdup(hostname);
	memset(&hostval, 0, sizeof(hostval));
	memset(&pubkey, 0, sizeof(pubkey));
	memset(&tai_leap, 0, sizeof(tai_leap));

	/*
	 * Load required host key from file "ntpkey_host_<hostname>". If
	 * no host key file is not found or has invalid password, life
	 * as we know it ends. The host key also becomes the default
	 * sign key. 
	 */
	snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
	pinfo = crypto_key(filename, passwd, NULL);
	if (pinfo == NULL) {
		msyslog(LOG_ERR,
		    "crypto_setup: host key file %s not found or corrupt",
		    filename);
		exit (-1);
	}
	if (EVP_PKEY_base_id(pinfo->pkey) != EVP_PKEY_RSA) {
		msyslog(LOG_ERR,
		    "crypto_setup: host key is not RSA key type");
		exit (-1);
	}
	host_pkey = pinfo->pkey;
	sign_pkey = host_pkey;
	hostval.fstamp = htonl(pinfo->fstamp);
	
	/*
	 * Construct public key extension field for agreement scheme.
	 */
	len = i2d_PublicKey(host_pkey, NULL);
	ptr = emalloc(len);
	pubkey.ptr = ptr;
	i2d_PublicKey(host_pkey, &ptr);
	pubkey.fstamp = hostval.fstamp;
	pubkey.vallen = htonl(len);

	/*
	 * Load optional sign key from file "ntpkey_sign_<hostname>". If
	 * available, it becomes the sign key.
	 */
	snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
	pinfo = crypto_key(filename, passwd, NULL);
	if (pinfo != NULL)
		sign_pkey = pinfo->pkey;

	/*
	 * Load required certificate from file "ntpkey_cert_<hostname>".
	 */
	snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
	cinfo = crypto_cert(filename);
	if (cinfo == NULL) {
		msyslog(LOG_ERR,
		    "crypto_setup: certificate file %s not found or corrupt",
		    filename);
		exit (-1);
	}
	cert_host = cinfo;
	sign_digest = cinfo->digest;
	sign_siglen = EVP_PKEY_size(sign_pkey);
	if (cinfo->flags & CERT_PRIV)
		crypto_flags |= CRYPTO_FLAG_PRIV;

	/*
	 * The certificate must be self-signed.
	 */
	if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
		msyslog(LOG_ERR,
		    "crypto_setup: certificate %s is not self-signed",
		    filename);
		exit (-1);
	}
	hostval.ptr = estrdup(cinfo->subject);
	hostval.vallen = htonl(strlen(cinfo->subject));
	sys_hostname = hostval.ptr;
	ptr = (u_char *)strchr(sys_hostname, '@');
	if (ptr != NULL)
		sys_groupname = estrdup((char *)++ptr);
	if (ident_filename != NULL)
		strlcpy(hostname, ident_filename, sizeof(hostname));

	/*
	 * Load optional IFF parameters from file
	 * "ntpkey_iffkey_<hostname>".
	 */
	snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
	    hostname);
	iffkey_info = crypto_key(filename, passwd, NULL);
	if (iffkey_info != NULL)
		crypto_flags |= CRYPTO_FLAG_IFF;

	/*
	 * Load optional GQ parameters from file
	 * "ntpkey_gqkey_<hostname>".
	 */
	snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
	    hostname);
	gqkey_info = crypto_key(filename, passwd, NULL);
	if (gqkey_info != NULL)
		crypto_flags |= CRYPTO_FLAG_GQ;

	/*
	 * Load optional MV parameters from file
	 * "ntpkey_mvkey_<hostname>".
	 */
	snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
	    hostname);
	mvkey_info = crypto_key(filename, passwd, NULL);
	if (mvkey_info != NULL)
		crypto_flags |= CRYPTO_FLAG_MV;

	/*
	 * We met the enemy and he is us. Now strike up the dance.
	 */
	crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
	snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
	    crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
	record_crypto_stats(NULL, statstr);
	DPRINTF(1, ("crypto_setup: %s\n", statstr));
}


/*
 * crypto_config - configure data from the crypto command.
 */
void
crypto_config(
	int	item,		/* configuration item */
	char	*cp		/* item name */
	)
{
	int	nid;

	DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));

	switch (item) {

	/*
	 * Set host name (host).
	 */
	case CRYPTO_CONF_PRIV:
		if (NULL != host_filename)
			free(host_filename);
		host_filename = estrdup(cp);
		break;

	/*
	 * Set group name (ident).
	 */
	case CRYPTO_CONF_IDENT:
		if (NULL != ident_filename)
			free(ident_filename);
		ident_filename = estrdup(cp);
		break;

	/*
	 * Set private key password (pw).
	 */
	case CRYPTO_CONF_PW:
		if (NULL != passwd)
			free(passwd);
		passwd = estrdup(cp);
		break;

	/*
	 * Set random seed file name (randfile).
	 */
	case CRYPTO_CONF_RAND:
		if (NULL != rand_file)
			free(rand_file);
		rand_file = estrdup(cp);
		break;

	/*
	 * Set message digest NID.
	 */
	case CRYPTO_CONF_NID:
		nid = OBJ_sn2nid(cp);
		if (nid == 0)
			msyslog(LOG_ERR,
			    "crypto_config: invalid digest name %s", cp);
		else
			crypto_nid = nid;
		break;
	}
}

/*
 * Get the  payload size (internal value length) of an extension packet.
 * If the inner value size does not match the outer packet size (that
 * is, the value would end behind the frame given by the opcode/size
 * field) the function will effectively return UINT_MAX. If the frame is
 * too short to hold a variable-sized value, the return value is zero.
 */
static u_int
exten_payload_size(
	const struct exten * ep)
{
	typedef const u_char *BPTR;
	
	size_t extn_size;
	size_t data_size;
	size_t head_size;

	data_size = 0;
	if (NULL != ep) {
		head_size = (BPTR)(&ep->vallen + 1) - (BPTR)ep;
		extn_size = (uint16_t)(ntohl(ep->opcode) & 0x0000ffff);
		if (extn_size >= head_size) {
			data_size = (uint32_t)ntohl(ep->vallen);
			if (data_size > extn_size - head_size)
				data_size = ~(size_t)0u;
		}
	}
	return (u_int)data_size;
}
# else	/* !AUTOKEY follows */
int ntp_crypto_bs_pubkey;
# endif	/* !AUTOKEY */