summaryrefslogtreecommitdiff
path: root/openssl1.0.0/engines/pkcs11/hw_pk11.c
blob: 7f3571438f95c657828b6c7b534d17e284e21a46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
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
/*
 * Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
 */

/* crypto/engine/hw_pk11.c */
/*
 * This product includes software developed by the OpenSSL Project for
 * use in the OpenSSL Toolkit (http://www.openssl.org/).
 *
 * This project also referenced hw_pkcs11-0.9.7b.patch written by
 * Afchine Madjlessi.
 */
/*
 * ====================================================================
 * Copyright (c) 2000-2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <strings.h>

#include <openssl/e_os2.h>
#include <openssl/crypto.h>
#include <openssl/engine.h>
#include <openssl/dso.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/md5.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_RSA
#include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#include <openssl/rand.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/aes.h>
#include <cryptlib.h>
#include <dlfcn.h>
#include <pthread.h>

#ifndef OPENSSL_NO_HW
#ifndef OPENSSL_NO_HW_PK11

/* label for debug messages printed on stderr */
#define	PK11_DBG	"PKCS#11 ENGINE DEBUG"
/* prints a lot of debug messages on stderr about slot selection process */
#undef	DEBUG_SLOT_SELECTION
/*
 * Solaris specific code. See comment at check_hw_mechanisms() for more
 * information.
 */
#if defined(__SVR4) && defined(__sun)
#define	SOLARIS_HW_SLOT_SELECTION
#endif

#ifdef	SOLARIS_HW_SLOT_SELECTION
#include <sys/auxv.h>
#endif

#ifdef DEBUG_SLOT_SELECTION
#define	DEBUG_SLOT_SEL(...) fprintf(stderr, __VA_ARGS__)
#else
#define	DEBUG_SLOT_SEL(...)
#endif


#include <security/cryptoki.h>
#include <security/pkcs11.h>
#include "hw_pk11.h"
#include "hw_pk11_uri.h"

#define	PK11_ENGINE_LIB_NAME "PKCS#11 engine"
#include "hw_pk11_err.c"

#ifdef	SOLARIS_AES_CTR
/*
 * NIDs for AES counter mode that will be defined during the engine
 * initialization.
 */
int NID_aes_128_ctr = NID_undef;
int NID_aes_192_ctr = NID_undef;
int NID_aes_256_ctr = NID_undef;
#endif	/* SOLARIS_AES_CTR */

/*
 * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
 * uri_struct manipulation, and static token info. All of that is used by the
 * RSA keys by reference feature.
 */
pthread_mutex_t *uri_lock = NULL;

#ifdef	SOLARIS_HW_SLOT_SELECTION
/*
 * Tables for symmetric ciphers and digest mechs found in the pkcs11_kernel
 * library. See comment at check_hw_mechanisms() for more information.
 */
int *hw_cnids;
int *hw_dnids;
#endif	/* SOLARIS_HW_SLOT_SELECTION */

/* PKCS#11 session caches and their locks for all operation types */
static PK11_CACHE session_cache[OP_MAX];

/*
 * We cache the flags so that we do not have to run C_GetTokenInfo() again when
 * logging into the token.
 */
CK_FLAGS pubkey_token_flags;

/*
 * As stated in v2.20, 11.7 Object Management Function, in section for
 * C_FindObjectsInit(), at most one search operation may be active at a given
 * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
 * grouped together to form one atomic search operation. This is already
 * ensured by the property of unique PKCS#11 session handle used for each
 * PK11_SESSION object.
 *
 * This is however not the biggest concern - maintaining consistency of the
 * underlying object store is more important. The same section of the spec also
 * says that one thread can be in the middle of a search operation while another
 * thread destroys the object matching the search template which would result in
 * invalid handle returned from the search operation.
 *
 * Hence, the following locks are used for both protection of the object stores.
 * They are also used for active list protection.
 */
pthread_mutex_t *find_lock[OP_MAX] = { NULL };

/*
 * lists of asymmetric key handles which are active (referenced by at least one
 * PK11_SESSION structure, either held by a thread or present in free_session
 * list) for given algorithm type
 */
PK11_active *active_list[OP_MAX] = { NULL };

/*
 * Create all secret key objects in a global session so that they are available
 * to use for other sessions. These other sessions may be opened or closed
 * without losing the secret key objects.
 */
static CK_SESSION_HANDLE	global_session = CK_INVALID_HANDLE;

/* Index for the supported ciphers */
enum pk11_cipher_id {
	PK11_DES_CBC,
	PK11_DES3_CBC,
	PK11_DES_ECB,
	PK11_DES3_ECB,
	PK11_RC4,
	PK11_AES_128_CBC,
	PK11_AES_192_CBC,
	PK11_AES_256_CBC,
	PK11_AES_128_ECB,
	PK11_AES_192_ECB,
	PK11_AES_256_ECB,
	PK11_BLOWFISH_CBC,
#ifdef	SOLARIS_AES_CTR
	PK11_AES_128_CTR,
	PK11_AES_192_CTR,
	PK11_AES_256_CTR,
#endif	/* SOLARIS_AES_CTR */
	PK11_CIPHER_MAX
};

/* Index for the supported digests */
enum pk11_digest_id {
	PK11_MD5,
	PK11_SHA1,
	PK11_SHA224,
	PK11_SHA256,
	PK11_SHA384,
	PK11_SHA512,
	PK11_DIGEST_MAX
};

typedef struct PK11_CIPHER_st
	{
	enum pk11_cipher_id	id;
	int			nid;
	int			iv_len;
	int			min_key_len;
	int			max_key_len;
	CK_KEY_TYPE		key_type;
	CK_MECHANISM_TYPE	mech_type;
	} PK11_CIPHER;

typedef struct PK11_DIGEST_st
	{
	enum pk11_digest_id	id;
	int			nid;
	CK_MECHANISM_TYPE	mech_type;
	} PK11_DIGEST;

/* ENGINE level stuff */
static int pk11_init(ENGINE *e);
static int pk11_library_init(ENGINE *e);
static int pk11_finish(ENGINE *e);
static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
static int pk11_destroy(ENGINE *e);

/* RAND stuff */
static void pk11_rand_seed(const void *buf, int num);
static void pk11_rand_add(const void *buf, int num, double add_entropy);
static void pk11_rand_cleanup(void);
static int pk11_rand_bytes(unsigned char *buf, int num);
static int pk11_rand_status(void);

/* These functions are also used in other files */
PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);

/* active list manipulation functions used in this file */
extern int pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type);
extern void pk11_free_active_list(PK11_OPTYPE type);

#ifndef OPENSSL_NO_RSA
int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
#endif
#ifndef OPENSSL_NO_DSA
int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
#endif
#ifndef OPENSSL_NO_DH
int pk11_destroy_dh_key_objects(PK11_SESSION *session);
int pk11_destroy_dh_object(PK11_SESSION *session, CK_BBOOL uselock);
#endif

/* Local helper functions */
static int pk11_free_all_sessions(void);
static int pk11_free_session_list(PK11_OPTYPE optype);
static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype);
static int pk11_destroy_cipher_key_objects(PK11_SESSION *session);
static int pk11_destroy_object(CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE oh,
    CK_BBOOL persistent);
static const char *get_PK11_LIBNAME(void);
static void free_PK11_LIBNAME(void);
static long set_PK11_LIBNAME(const char *name);

/* Symmetric cipher and digest support functions */
static int cipher_nid_to_pk11(int nid);
#ifdef	SOLARIS_AES_CTR
static int pk11_add_NID(char *sn, char *ln);
static int pk11_add_aes_ctr_NIDs(void);
#endif	/* SOLARIS_AES_CTR */
static int pk11_usable_ciphers(const int **nids);
static int pk11_usable_digests(const int **nids);
static int pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
	const unsigned char *iv, int enc);
static int pk11_cipher_final(PK11_SESSION *sp);
static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
	const unsigned char *in, size_t inl);
static int pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
static int pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
	const int **nids, int nid);
static int pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
	const int **nids, int nid);
static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp);
static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
	int key_len);
static int md_nid_to_pk11(int nid);
static int pk11_digest_init(EVP_MD_CTX *ctx);
static int pk11_digest_update(EVP_MD_CTX *ctx, const void *data,
	size_t count);
static int pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md);
static int pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
static int pk11_digest_cleanup(EVP_MD_CTX *ctx);

static int pk11_choose_slots(int *any_slot_found);
static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
    CK_SLOT_ID current_slot, int *current_slot_n_cipher,
    int *local_cipher_nids);
static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
    CK_SLOT_ID current_slot, int *current_slot_n_digest,
    int *local_digest_nids);
static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR, int slot_id,
    int *current_slot_n_cipher, int *local_cipher_nids,
    PK11_CIPHER *cipher);
static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
    int *current_slot_n_digest, int *local_digest_nids,
    PK11_DIGEST *digest);

static int pk11_init_all_locks(void);
static void pk11_free_all_locks(void);

#ifdef	SOLARIS_HW_SLOT_SELECTION
static int check_hw_mechanisms(void);
static int nid_in_table(int nid, int *nid_table);
static int hw_aes_instruction_set_present(void);
#endif	/* SOLARIS_HW_SLOT_SELECTION */

#define	TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type)	\
	{								\
	if (uselock)							\
		LOCK_OBJSTORE(alg_type);				\
	if (pk11_active_delete(obj_hdl, alg_type) == 1)			\
		{							\
		retval = pk11_destroy_object(sp->session, obj_hdl,	\
		    sp->persistent);					\
		}							\
	if (uselock)							\
		UNLOCK_OBJSTORE(alg_type);				\
	}

static int cipher_nids[PK11_CIPHER_MAX];
static int digest_nids[PK11_DIGEST_MAX];
static int cipher_count		= 0;
static int digest_count		= 0;
static CK_BBOOL pk11_have_rsa	= CK_FALSE;
static CK_BBOOL pk11_have_dsa	= CK_FALSE;
static CK_BBOOL pk11_have_dh	= CK_FALSE;
static CK_BBOOL pk11_have_random = CK_FALSE;

/*
 * Static list of ciphers.
 * Note, that ciphers array is indexed by member PK11_CIPHER.id,
 * thus ciphers[i].id == i
 * Rows must be kept in sync with enum pk11_cipher_id.
 */
static PK11_CIPHER ciphers[] =
	{
	{ PK11_DES_CBC,		NID_des_cbc,		8,	 8,   8,
		CKK_DES,	CKM_DES_CBC, },
	{ PK11_DES3_CBC,	NID_des_ede3_cbc,	8,	24,  24,
		CKK_DES3,	CKM_DES3_CBC, },
	{ PK11_DES_ECB,		NID_des_ecb,		0,	 8,   8,
		CKK_DES,	CKM_DES_ECB, },
	{ PK11_DES3_ECB,	NID_des_ede3_ecb,	0,	24,  24,
		CKK_DES3,	CKM_DES3_ECB, },
	{ PK11_RC4,		NID_rc4,		0,	16, 256,
		CKK_RC4,	CKM_RC4, },
	{ PK11_AES_128_CBC,	NID_aes_128_cbc,	16,	16,  16,
		CKK_AES,	CKM_AES_CBC, },
	{ PK11_AES_192_CBC,	NID_aes_192_cbc,	16,	24,  24,
		CKK_AES,	CKM_AES_CBC, },
	{ PK11_AES_256_CBC,	NID_aes_256_cbc,	16,	32,  32,
		CKK_AES,	CKM_AES_CBC, },
	{ PK11_AES_128_ECB,	NID_aes_128_ecb,	0,	16,  16,
		CKK_AES,	CKM_AES_ECB, },
	{ PK11_AES_192_ECB,	NID_aes_192_ecb,	0,	24,  24,
		CKK_AES,	CKM_AES_ECB, },
	{ PK11_AES_256_ECB,	NID_aes_256_ecb,	0,	32,  32,
		CKK_AES,	CKM_AES_ECB, },
	{ PK11_BLOWFISH_CBC,	NID_bf_cbc,		8,	16,  16,
		CKK_BLOWFISH,	CKM_BLOWFISH_CBC, },
#ifdef	SOLARIS_AES_CTR
	/* we don't know the correct NIDs until the engine is initialized */
	{ PK11_AES_128_CTR,	NID_undef,		16,	16,  16,
		CKK_AES,	CKM_AES_CTR, },
	{ PK11_AES_192_CTR,	NID_undef,		16,	24,  24,
		CKK_AES,	CKM_AES_CTR, },
	{ PK11_AES_256_CTR,	NID_undef,		16,	32,  32,
		CKK_AES,	CKM_AES_CTR, },
#endif	/* SOLARIS_AES_CTR */
	};

/*
 * Static list of digests.
 * Note, that digests array is indexed by member PK11_DIGEST.id,
 * thus digests[i].id == i
 * Rows must be kept in sync with enum pk11_digest_id.
 */
static PK11_DIGEST digests[] =
	{
	{PK11_MD5,	NID_md5,	CKM_MD5, },
	{PK11_SHA1,	NID_sha1,	CKM_SHA_1, },
	{PK11_SHA224,	NID_sha224,	CKM_SHA224, },
	{PK11_SHA256,	NID_sha256,	CKM_SHA256, },
	{PK11_SHA384,	NID_sha384,	CKM_SHA384, },
	{PK11_SHA512,	NID_sha512,	CKM_SHA512, },
	{0,		NID_undef,	0xFFFF, },
	};

/*
 * Structure to be used for the cipher_data/md_data in
 * EVP_CIPHER_CTX/EVP_MD_CTX structures in order to use the same pk11
 * session in multiple cipher_update calls
 */
typedef struct PK11_CIPHER_STATE_st
	{
	PK11_SESSION	*sp;
	} PK11_CIPHER_STATE;


/*
 * libcrypto EVP stuff - this is how we get wired to EVP so the engine gets
 * called when libcrypto requests a cipher NID.
 *
 * Note how the PK11_CIPHER_STATE is used here.
 */

/* DES CBC EVP */
static const EVP_CIPHER pk11_des_cbc =
	{
	NID_des_cbc,
	8, 8, 8,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

/* 3DES CBC EVP */
static const EVP_CIPHER pk11_3des_cbc =
	{
	NID_des_ede3_cbc,
	8, 24, 8,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

/*
 * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
 * get_asn1_parameters fields are set to NULL.
 */
static const EVP_CIPHER pk11_des_ecb =
	{
	NID_des_ecb,
	8, 8, 8,
	EVP_CIPH_ECB_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};

static const EVP_CIPHER pk11_3des_ecb =
	{
	NID_des_ede3_ecb,
	8, 24, 8,
	EVP_CIPH_ECB_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};


static const EVP_CIPHER pk11_aes_128_cbc =
	{
	NID_aes_128_cbc,
	16, 16, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

static const EVP_CIPHER pk11_aes_192_cbc =
	{
	NID_aes_192_cbc,
	16, 24, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

static const EVP_CIPHER pk11_aes_256_cbc =
	{
	NID_aes_256_cbc,
	16, 32, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

/*
 * ECB modes don't use IV so that's why set_asn1_parameters and
 * get_asn1_parameters are set to NULL.
 */
static const EVP_CIPHER pk11_aes_128_ecb =
	{
	NID_aes_128_ecb,
	16, 16, 0,
	EVP_CIPH_ECB_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};

static const EVP_CIPHER pk11_aes_192_ecb =
	{
	NID_aes_192_ecb,
	16, 24, 0,
	EVP_CIPH_ECB_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};

static const EVP_CIPHER pk11_aes_256_ecb =
	{
	NID_aes_256_ecb,
	16, 32, 0,
	EVP_CIPH_ECB_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};

#ifdef	SOLARIS_AES_CTR
/*
 * NID_undef's will be changed to the AES counter mode NIDs as soon they are
 * created in pk11_library_init(). Note that the need to change these structures
 * is the reason why we don't define them with the const keyword.
 */
static EVP_CIPHER pk11_aes_128_ctr =
	{
	NID_undef,
	16, 16, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

static EVP_CIPHER pk11_aes_192_ctr =
	{
	NID_undef,
	16, 24, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

static EVP_CIPHER pk11_aes_256_ctr =
	{
	NID_undef,
	16, 32, 16,
	EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};
#endif	/* SOLARIS_AES_CTR */

static const EVP_CIPHER pk11_bf_cbc =
	{
	NID_bf_cbc,
	8, 16, 8,
	EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CBC_MODE,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	EVP_CIPHER_set_asn1_iv,
	EVP_CIPHER_get_asn1_iv,
	NULL
	};

static const EVP_CIPHER pk11_rc4 =
	{
	NID_rc4,
	1, 16, 0,
	EVP_CIPH_VARIABLE_LENGTH,
	pk11_cipher_init,
	pk11_cipher_do_cipher,
	pk11_cipher_cleanup,
	sizeof (PK11_CIPHER_STATE),
	NULL,
	NULL,
	NULL
	};

static const EVP_MD pk11_md5 =
	{
	NID_md5,
	NID_md5WithRSAEncryption,
	MD5_DIGEST_LENGTH,
	0,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	MD5_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

static const EVP_MD pk11_sha1 =
	{
	NID_sha1,
	NID_sha1WithRSAEncryption,
	SHA_DIGEST_LENGTH,
	EVP_MD_FLAG_PKEY_METHOD_SIGNATURE|EVP_MD_FLAG_DIGALGID_ABSENT,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	SHA_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

static const EVP_MD pk11_sha224 =
	{
	NID_sha224,
	NID_sha224WithRSAEncryption,
	SHA224_DIGEST_LENGTH,
	EVP_MD_FLAG_PKEY_METHOD_SIGNATURE|EVP_MD_FLAG_DIGALGID_ABSENT,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	/* SHA-224 uses the same cblock size as SHA-256 */
	SHA256_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

static const EVP_MD pk11_sha256 =
	{
	NID_sha256,
	NID_sha256WithRSAEncryption,
	SHA256_DIGEST_LENGTH,
	EVP_MD_FLAG_PKEY_METHOD_SIGNATURE|EVP_MD_FLAG_DIGALGID_ABSENT,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	SHA256_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

static const EVP_MD pk11_sha384 =
	{
	NID_sha384,
	NID_sha384WithRSAEncryption,
	SHA384_DIGEST_LENGTH,
	EVP_MD_FLAG_PKEY_METHOD_SIGNATURE|EVP_MD_FLAG_DIGALGID_ABSENT,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	/* SHA-384 uses the same cblock size as SHA-512 */
	SHA512_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

static const EVP_MD pk11_sha512 =
	{
	NID_sha512,
	NID_sha512WithRSAEncryption,
	SHA512_DIGEST_LENGTH,
	EVP_MD_FLAG_PKEY_METHOD_SIGNATURE|EVP_MD_FLAG_DIGALGID_ABSENT,
	pk11_digest_init,
	pk11_digest_update,
	pk11_digest_final,
	pk11_digest_copy,
	pk11_digest_cleanup,
	EVP_PKEY_RSA_method,
	SHA512_CBLOCK,
	sizeof (PK11_CIPHER_STATE),
	};

/*
 * Initialization function. Sets up various PKCS#11 library components.
 * The definitions for control commands specific to this engine
 */
#define	PK11_CMD_SO_PATH		ENGINE_CMD_BASE
static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
	{
		{
		PK11_CMD_SO_PATH,
		"SO_PATH",
		"Specifies the path to the 'pkcs#11' shared library",
		ENGINE_CMD_FLAG_STRING
		},
		{0, NULL, NULL, 0}
	};


static RAND_METHOD pk11_random =
	{
	pk11_rand_seed,
	pk11_rand_bytes,
	pk11_rand_cleanup,
	pk11_rand_add,
	pk11_rand_bytes,
	pk11_rand_status
	};


/* Constants used when creating the ENGINE */
static const char *engine_pk11_id = "pkcs11";
static const char *engine_pk11_name = "PKCS #11 engine support";

CK_FUNCTION_LIST_PTR pFuncList = NULL;
static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";

/*
 * This is a static string constant for the DSO file name and the function
 * symbol names to bind to. We set it in the Configure script based on whether
 * this is 32 or 64 bit build.
 */
static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;

static CK_BBOOL pk11_true = CK_TRUE;
static CK_BBOOL pk11_false = CK_FALSE;
/* Needed in hw_pk11_pub.c as well so that's why it is not static. */
CK_SLOT_ID pubkey_SLOTID = 0;
static CK_SLOT_ID rand_SLOTID = 0;
static CK_SLOT_ID SLOTID = 0;
static CK_BBOOL pk11_library_initialized = CK_FALSE;
static CK_BBOOL pk11_atfork_initialized = CK_FALSE;
static int pk11_pid = 0;
static ENGINE* pk11_engine = NULL;

static DSO *pk11_dso = NULL;

/* allocate and initialize all locks used by the engine itself */
static int pk11_init_all_locks(void)
	{
	int type;

#ifndef OPENSSL_NO_RSA
	find_lock[OP_RSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
	if (find_lock[OP_RSA] == NULL)
		goto malloc_err;
	(void) pthread_mutex_init(find_lock[OP_RSA], NULL);
#endif /* OPENSSL_NO_RSA */

	if ((uri_lock = OPENSSL_malloc(sizeof (pthread_mutex_t))) == NULL)
		goto malloc_err;
	(void) pthread_mutex_init(uri_lock, NULL);

#ifndef OPENSSL_NO_DSA
	find_lock[OP_DSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
	if (find_lock[OP_DSA] == NULL)
		goto malloc_err;
	(void) pthread_mutex_init(find_lock[OP_DSA], NULL);
#endif /* OPENSSL_NO_DSA */

#ifndef OPENSSL_NO_DH
	find_lock[OP_DH] = OPENSSL_malloc(sizeof (pthread_mutex_t));
	if (find_lock[OP_DH] == NULL)
		goto malloc_err;
	(void) pthread_mutex_init(find_lock[OP_DH], NULL);
#endif /* OPENSSL_NO_DH */

	for (type = 0; type < OP_MAX; type++)
		{
		session_cache[type].lock =
		    OPENSSL_malloc(sizeof (pthread_mutex_t));
		if (session_cache[type].lock == NULL)
			goto malloc_err;
		(void) pthread_mutex_init(session_cache[type].lock, NULL);
		}

	return (1);

malloc_err:
	pk11_free_all_locks();
	PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
	return (0);
	}

static void pk11_free_all_locks(void)
	{
	int type;

#ifndef OPENSSL_NO_RSA
	if (find_lock[OP_RSA] != NULL)
		{
		(void) pthread_mutex_destroy(find_lock[OP_RSA]);
		OPENSSL_free(find_lock[OP_RSA]);
		find_lock[OP_RSA] = NULL;
		}
#endif /* OPENSSL_NO_RSA */
#ifndef OPENSSL_NO_DSA
	if (find_lock[OP_DSA] != NULL)
		{
		(void) pthread_mutex_destroy(find_lock[OP_DSA]);
		OPENSSL_free(find_lock[OP_DSA]);
		find_lock[OP_DSA] = NULL;
		}
#endif /* OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_DH
	if (find_lock[OP_DH] != NULL)
		{
		(void) pthread_mutex_destroy(find_lock[OP_DH]);
		OPENSSL_free(find_lock[OP_DH]);
		find_lock[OP_DH] = NULL;
		}
#endif /* OPENSSL_NO_DH */

	for (type = 0; type < OP_MAX; type++)
		{
		if (session_cache[type].lock != NULL)
			{
			(void) pthread_mutex_destroy(session_cache[type].lock);
			OPENSSL_free(session_cache[type].lock);
			session_cache[type].lock = NULL;
			}
		}
	/* Free uri_lock */
	(void) pthread_mutex_destroy(uri_lock);
	OPENSSL_free(uri_lock);
	uri_lock = NULL;
	}

/*
 * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
 */
static int bind_pk11(ENGINE *e)
	{
#ifndef OPENSSL_NO_RSA
	const RSA_METHOD *rsa = NULL;
	RSA_METHOD *pk11_rsa = PK11_RSA();
#endif	/* OPENSSL_NO_RSA */
	if (!pk11_library_initialized)
		if (!pk11_library_init(e))
			return (0);

	if (!ENGINE_set_id(e, engine_pk11_id) ||
	    !ENGINE_set_name(e, engine_pk11_name) ||
	    !ENGINE_set_ciphers(e, pk11_engine_ciphers) ||
	    !ENGINE_set_digests(e, pk11_engine_digests))
		return (0);

	if (!ENGINE_set_pkey_meths(e, pk11_engine_pkey_methods))
		return (0);

#ifndef OPENSSL_NO_RSA
	if (pk11_have_rsa == CK_TRUE)
		{
		if (!ENGINE_set_RSA(e, PK11_RSA()) ||
		    !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
		    !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
			return (0);
		DEBUG_SLOT_SEL("%s: registered RSA\n", PK11_DBG);
		}
#endif	/* OPENSSL_NO_RSA */
#ifndef OPENSSL_NO_DSA
	if (pk11_have_dsa == CK_TRUE)
		{
		if (!ENGINE_set_DSA(e, PK11_DSA()))
			return (0);
		DEBUG_SLOT_SEL("%s: registered DSA\n", PK11_DBG);
		}
#endif	/* OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_DH
	if (pk11_have_dh == CK_TRUE)
		{
		if (!ENGINE_set_DH(e, PK11_DH()))
			return (0);
		DEBUG_SLOT_SEL("%s: registered DH\n", PK11_DBG);
		}
#endif	/* OPENSSL_NO_DH */
	if (pk11_have_random)
		{
		if (!ENGINE_set_RAND(e, &pk11_random))
			return (0);
		DEBUG_SLOT_SEL("%s: registered random\n", PK11_DBG);
		}
	if (!ENGINE_set_init_function(e, pk11_init) ||
	    !ENGINE_set_destroy_function(e, pk11_destroy) ||
	    !ENGINE_set_finish_function(e, pk11_finish) ||
	    !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
	    !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
		return (0);

/*
 * Apache calls OpenSSL function RSA_blinding_on() once during startup
 * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
 * here, we wire it back to the OpenSSL software implementation.
 * Since it is used only once, performance is not a concern.
 */
#ifndef OPENSSL_NO_RSA
	rsa = RSA_PKCS1_SSLeay();
	pk11_rsa->rsa_mod_exp = rsa->rsa_mod_exp;
	pk11_rsa->bn_mod_exp = rsa->bn_mod_exp;
#endif	/* OPENSSL_NO_RSA */

	/* Ensure the pk11 error handling is set up */
	ERR_load_pk11_strings();

	return (1);
	}

/* Dynamic engine support is disabled at a higher level for Solaris */
#ifdef	ENGINE_DYNAMIC_SUPPORT
static int bind_helper(ENGINE *e, const char *id)
	{
	if (id && (strcmp(id, engine_pk11_id) != 0))
		return (0);

	if (!bind_pk11(e))
		return (0);

	return (1);
	}

IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)

#else
static ENGINE *engine_pk11(void)
	{
	ENGINE *ret = ENGINE_new();

	if (!ret)
		return (NULL);

	if (!bind_pk11(ret))
		{
		ENGINE_free(ret);
		return (NULL);
		}

	return (ret);
	}

int
pk11_engine_loaded()
	{
	ENGINE *e;
	int rtrn = 0;

	if ((e = ENGINE_by_id(engine_pk11_id)) != NULL)
		{
		rtrn = 1;
		ENGINE_free(e);
		}
	return (rtrn);
	}

void
ENGINE_load_pk11(void)
	{
	ENGINE *e_pk11 = NULL;

	/*
	 * Do not attempt to load the engine twice!
	 * Multiple instances would share static variables from this file.
	 */
	if (pk11_engine_loaded())
		return;

	/*
	 * Do not use dynamic PKCS#11 library on Solaris due to
	 * security reasons. We will link it in statically.
	 */
	/* Attempt to load PKCS#11 library */
	if (!pk11_dso)
		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);

	if (pk11_dso == NULL)
		{
		PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
		return;
		}

	e_pk11 = engine_pk11();
	if (!e_pk11)
		{
		DSO_free(pk11_dso);
		pk11_dso = NULL;
		return;
		}

	/*
	 * At this point, the pk11 shared library is either dynamically
	 * loaded or statically linked in. So, initialize the pk11
	 * library before calling ENGINE_set_default since the latter
	 * needs cipher and digest algorithm information
	 */
	if (!pk11_library_init(e_pk11))
		{
		DSO_free(pk11_dso);
		pk11_dso = NULL;
		ENGINE_free(e_pk11);
		return;
		}

	ENGINE_add(e_pk11);

	ENGINE_free(e_pk11);
	ERR_clear_error();
	}
#endif	/* ENGINE_DYNAMIC_SUPPORT */

/*
 * These are the static string constants for the DSO file name and
 * the function symbol names to bind to.
 */
static const char *PK11_LIBNAME = NULL;

static const char *get_PK11_LIBNAME(void)
	{
	if (PK11_LIBNAME)
		return (PK11_LIBNAME);

	return (def_PK11_LIBNAME);
	}

static void free_PK11_LIBNAME(void)
	{
	if (PK11_LIBNAME)
		OPENSSL_free((void*)PK11_LIBNAME);

	PK11_LIBNAME = NULL;
	}

static long set_PK11_LIBNAME(const char *name)
	{
	free_PK11_LIBNAME();

	return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
	}

/* acquire all engine specific mutexes before fork */
static void pk11_fork_prepare(void)
	{
	int i;

	if (!pk11_library_initialized)
		return;

	LOCK_OBJSTORE(OP_RSA);
	LOCK_OBJSTORE(OP_DSA);
	LOCK_OBJSTORE(OP_DH);
	(void) pthread_mutex_lock(uri_lock);
	for (i = 0; i < OP_MAX; i++)
		{
		(void) pthread_mutex_lock(session_cache[i].lock);
		}
	}

/* release all engine specific mutexes */
static void pk11_fork_parent(void)
	{
	int i;

	if (!pk11_library_initialized)
		return;

	for (i = OP_MAX - 1; i >= 0; i--)
		{
		(void) pthread_mutex_unlock(session_cache[i].lock);
		}
	UNLOCK_OBJSTORE(OP_DH);
	UNLOCK_OBJSTORE(OP_DSA);
	UNLOCK_OBJSTORE(OP_RSA);
	(void) pthread_mutex_unlock(uri_lock);
	}

/*
 * same situation as in parent - we need to unlock all locks to make them
 * accessible to all threads.
 */
static void pk11_fork_child(void)
	{
	int i;

	if (!pk11_library_initialized)
		return;

	for (i = OP_MAX - 1; i >= 0; i--)
		{
		(void) pthread_mutex_unlock(session_cache[i].lock);
		}
	UNLOCK_OBJSTORE(OP_DH);
	UNLOCK_OBJSTORE(OP_DSA);
	UNLOCK_OBJSTORE(OP_RSA);
	(void) pthread_mutex_unlock(uri_lock);
	}

/* Initialization function for the pk11 engine */
static int pk11_init(ENGINE *e)
{
	return (pk11_library_init(e));
}

/*
 * Helper function that unsets reference to current engine (pk11_engine = NULL).
 *
 * Use of local variable only seems clumsy, it needs to be this way!
 * This is to prevent double free in the unlucky scenario:
 *     ENGINE_free calls pk11_destroy calls pk11_finish calls ENGINE_free
 * Setting pk11_engine to NULL prior to ENGINE_free() avoids this.
 */
static void pk11_engine_free()
	{
	ENGINE* old_engine = pk11_engine;

	if (old_engine) {
		pk11_engine = NULL;
		ENGINE_free(old_engine);
	}
	}

/*
 * Initialization function. Sets up various PKCS#11 library components.
 * It selects a slot based on predefined critiera. In the process, it also
 * count how many ciphers and digests to support. Since the cipher and
 * digest information is needed when setting default engine, this function
 * needs to be called before calling ENGINE_set_default.
 */
/* ARGSUSED */
static int pk11_library_init(ENGINE *e)
	{
	CK_C_GetFunctionList p;
	CK_RV rv = CKR_OK;
	CK_INFO info;
	CK_ULONG ul_state_len;
	int any_slot_found;
	int i;

	if (e != pk11_engine)
		{
		pk11_engine_free();
		pk11_engine = e;
		ENGINE_up_ref(e);
		}

	/*
	 * pk11_library_initialized is set to 0 in pk11_finish() which is called
	 * from ENGINE_finish(). However, if there is still at least one
	 * existing functional reference to the engine (see engine(3) for more
	 * information), pk11_finish() is skipped. For example, this can happen
	 * if an application forgets to clear one cipher context. In case of a
	 * fork() when the application is finishing the engine so that it can be
	 * reinitialized in the child, forgotten functional reference causes
	 * pk11_library_initialized to stay 1. In that case we need the PID
	 * check so that we properly initialize the engine again.
	 */
	if (pk11_library_initialized)
		{
		if (pk11_pid == getpid())
			{
			return (1);
			}
		else
			{
			global_session = CK_INVALID_HANDLE;
			/*
			 * free the locks first to prevent memory leak in case
			 * the application calls fork() without finishing the
			 * engine first.
			 */
			pk11_free_all_locks();
			}
		}


	/* Attempt to load PKCS#11 library */
	if (!pk11_dso)
		{
		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
		if (pk11_dso == NULL)
			{
			PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
			goto err;
			}
		}

#ifdef	SOLARIS_AES_CTR
	/*
	 * We must do this before we start working with slots since we need all
	 * NIDs there.
	 */
	if (pk11_add_aes_ctr_NIDs() == 0)
		goto err;
#endif	/* SOLARIS_AES_CTR */

#ifdef	SOLARIS_HW_SLOT_SELECTION
	if (check_hw_mechanisms() == 0)
		goto err;
#endif	/* SOLARIS_HW_SLOT_SELECTION */

	/* get the C_GetFunctionList function from the loaded library */
	p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
		PK11_GET_FUNCTION_LIST);
	if (!p)
		{
		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
		goto err;
		}

	/* get the full function list from the loaded library */
	rv = p(&pFuncList);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
		goto err;
		}

	rv = pFuncList->C_Initialize(NULL_PTR);
	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
		{
		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
		goto err;
		}

	rv = pFuncList->C_GetInfo(&info);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
		goto err;
		}

	if (pk11_choose_slots(&any_slot_found) == 0)
		goto err;

	/*
	 * The library we use, set in def_PK11_LIBNAME, may not offer any
	 * slot(s). In that case, we must not proceed but we must not return an
	 * error. The reason is that applications that try to set up the PKCS#11
	 * engine don't exit on error during the engine initialization just
	 * because no slot was present.
	 */
	if (any_slot_found == 0)
		return (1);

	if (global_session == CK_INVALID_HANDLE)
		{
		/* Open the global_session for the new process */
		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
			NULL_PTR, NULL_PTR, &global_session);
		if (rv != CKR_OK)
			{
			PK11err_add_data(PK11_F_LIBRARY_INIT,
			    PK11_R_OPENSESSION, rv);
			goto err;
			}
		}

	/*
	 * Disable digest if C_GetOperationState is not supported since
	 * this function is required by OpenSSL digest copy function
	 */
	if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
			== CKR_FUNCTION_NOT_SUPPORTED) {
		DEBUG_SLOT_SEL("%s: C_GetOperationState() not supported, "
		    "setting digest_count to 0\n", PK11_DBG);
		digest_count = 0;
	}

	pk11_library_initialized = CK_TRUE;
	pk11_pid = getpid();
	/*
	 * if initialization of the locks fails pk11_init_all_locks()
	 * will do the cleanup.
	 */
	if (!pk11_init_all_locks())
		goto err;
	for (i = 0; i < OP_MAX; i++)
		session_cache[i].head = NULL;
	/*
	 * initialize active lists. We only use active lists
	 * for asymmetric ciphers.
	 */
	for (i = 0; i < OP_MAX; i++)
		active_list[i] = NULL;

	if (!pk11_atfork_initialized)
		{
		if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
		    pk11_fork_child) != 0)
			{
			PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
			goto err;
			}
		pk11_atfork_initialized = CK_TRUE;
		}

	return (1);

err:
	return (0);
	}

/* Destructor (complements the "ENGINE_pk11()" constructor) */
/* ARGSUSED */
static int pk11_destroy(ENGINE *e)
	{
	int rtn = 1;

	free_PK11_LIBNAME();
	ERR_unload_pk11_strings();
	if (pk11_library_initialized == CK_TRUE)
		rtn = pk11_finish(e);

	return (rtn);
	}

/*
 * Termination function to clean up the session, the token, and the pk11
 * library.
 */
/* ARGSUSED */
static int pk11_finish(ENGINE *e)
	{
	int i;

	/*
	 * Make sure, right engine instance is being destroyed.
	 * Engine e may be the wrong instance if
	 * 	1) either someone calls ENGINE_load_pk11 twice
	 * 	2) or last ref. to an already finished engine is being destroyed
	 */
	if (e != pk11_engine)
		goto err;

	if (pk11_dso == NULL)
		{
		PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
		goto err;
		}

	OPENSSL_assert(pFuncList != NULL);

	if (pk11_free_all_sessions() == 0)
		goto err;

	/* free all active lists */
	for (i = 0; i < OP_MAX; i++)
		pk11_free_active_list(i);

	pFuncList->C_CloseSession(global_session);
	global_session = CK_INVALID_HANDLE;

	/*
	 * Since we are part of a library (libcrypto.so), calling this function
	 * may have side-effects.
	 */
#if 0
	pFuncList->C_Finalize(NULL);
#endif
#ifdef	SOLARIS_AES_CTR
	{
		ASN1_OBJECT *ob = NULL;
		if (NID_aes_128_ctr != NID_undef) {
			ob = OBJ_nid2obj(NID_aes_128_ctr);
			if (ob != NULL)
				ASN1_OBJECT_free(ob);
		}
		if (NID_aes_192_ctr != NID_undef) {
			ob = OBJ_nid2obj(NID_aes_192_ctr);
			if (ob != NULL)
				ASN1_OBJECT_free(ob);
		}
		if (NID_aes_256_ctr != NID_undef) {
			ob = OBJ_nid2obj(NID_aes_256_ctr);
			if (ob != NULL)
				ASN1_OBJECT_free(ob);
		}
	}
#endif

	if (!DSO_free(pk11_dso))
		{
		PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
		goto err;
		}
	pk11_dso = NULL;
	pFuncList = NULL;
	pk11_library_initialized = CK_FALSE;
	pk11_pid = 0;
	pk11_engine_free();
	/*
	 * There is no way how to unregister atfork handlers (other than
	 * unloading the library) so we just free the locks. For this reason
	 * the atfork handlers check if the engine is initialized and bail out
	 * immediately if not. This is necessary in case a process finishes
	 * the engine before calling fork().
	 */
	pk11_free_all_locks();

	return (1);

err:
	return (0);
	}

/* Standard engine interface function to set the dynamic library path */
/* ARGSUSED */
static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
	{
	int initialized = ((pk11_dso == NULL) ? 0 : 1);

	switch (cmd)
		{
	case PK11_CMD_SO_PATH:
		if (p == NULL)
			{
			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
			return (0);
			}

		if (initialized)
			{
			PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
			return (0);
			}

		return (set_PK11_LIBNAME((const char *)p));
	default:
		break;
		}

	PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);

	return (0);
	}


/* Required function by the engine random interface. It does nothing here */
static void pk11_rand_cleanup(void)
	{
	return;
	}

/* ARGSUSED */
static void pk11_rand_add(const void *buf, int num, double add)
	{
	PK11_SESSION *sp;

	if ((sp = pk11_get_session(OP_RAND)) == NULL)
		return;

	/*
	 * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
	 * the calling functions do not care anyway
	 */
	pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
	pk11_return_session(sp, OP_RAND);

	return;
	}

static void pk11_rand_seed(const void *buf, int num)
	{
	pk11_rand_add(buf, num, 0);
	}

static int pk11_rand_bytes(unsigned char *buf, int num)
	{
	CK_RV rv;
	PK11_SESSION *sp;

	if ((sp = pk11_get_session(OP_RAND)) == NULL)
		return (0);

	rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM, rv);
		pk11_return_session(sp, OP_RAND);
		return (0);
		}

	pk11_return_session(sp, OP_RAND);
	return (1);
	}

/* Required function by the engine random interface. It does nothing here */
static int pk11_rand_status(void)
	{
	return (1);
	}

/* Free all BIGNUM structures from PK11_SESSION. */
static void pk11_free_nums(PK11_SESSION *sp, PK11_OPTYPE optype)
	{
	switch (optype)
		{
#ifndef	OPENSSL_NO_RSA
		case OP_RSA:
			if (sp->opdata_rsa_n_num != NULL)
				{
				BN_free(sp->opdata_rsa_n_num);
				sp->opdata_rsa_n_num = NULL;
				}
			if (sp->opdata_rsa_e_num != NULL)
				{
				BN_free(sp->opdata_rsa_e_num);
				sp->opdata_rsa_e_num = NULL;
				}
			if (sp->opdata_rsa_d_num != NULL)
				{
				BN_free(sp->opdata_rsa_d_num);
				sp->opdata_rsa_d_num = NULL;
				}
			break;
#endif
#ifndef	OPENSSL_NO_DSA
		case OP_DSA:
			if (sp->opdata_dsa_pub_num != NULL)
				{
				BN_free(sp->opdata_dsa_pub_num);
				sp->opdata_dsa_pub_num = NULL;
				}
			if (sp->opdata_dsa_priv_num != NULL)
				{
				BN_free(sp->opdata_dsa_priv_num);
				sp->opdata_dsa_priv_num = NULL;
				}
			break;
#endif
#ifndef	OPENSSL_NO_DH
		case OP_DH:
			if (sp->opdata_dh_priv_num != NULL)
				{
				BN_free(sp->opdata_dh_priv_num);
				sp->opdata_dh_priv_num = NULL;
				}
			break;
#endif
		default:
			break;
		}
	}

/*
 * Get new PK11_SESSION structure ready for use. Every process must have
 * its own freelist of PK11_SESSION structures so handle fork() here
 * by destroying the old and creating new freelist.
 * The returned PK11_SESSION structure is disconnected from the freelist.
 */
PK11_SESSION *
pk11_get_session(PK11_OPTYPE optype)
	{
	PK11_SESSION *sp = NULL, *sp1, *freelist;
	pthread_mutex_t *freelist_lock;
	static pid_t pid = 0;
	pid_t new_pid;
	CK_RV rv;

	switch (optype)
		{
		case OP_RSA:
		case OP_DSA:
		case OP_DH:
		case OP_RAND:
		case OP_DIGEST:
		case OP_CIPHER:
			freelist_lock = session_cache[optype].lock;
			break;
		default:
			PK11err(PK11_F_GET_SESSION,
				PK11_R_INVALID_OPERATION_TYPE);
			return (NULL);
		}
	(void) pthread_mutex_lock(freelist_lock);

	/*
	 * Will use it to find out if we forked. We cannot use the PID field in
	 * the session structure because we could get a newly allocated session
	 * here, with no PID information.
	 */
	if (pid == 0)
		pid = getpid();

	freelist = session_cache[optype].head;
	sp = freelist;

	/*
	 * If the free list is empty, allocate new uninitialized (filled
	 * with zeroes) PK11_SESSION structure otherwise return first
	 * structure from the freelist.
	 */
	if (sp == NULL)
		{
		if ((sp = OPENSSL_malloc(sizeof (PK11_SESSION))) == NULL)
			{
			PK11err(PK11_F_GET_SESSION,
				PK11_R_MALLOC_FAILURE);
			goto err;
			}
		(void) memset(sp, 0, sizeof (PK11_SESSION));

		/*
		 * It is a new session so it will look like a cache miss to the
		 * code below. So, we must not try to to destroy its members so
		 * mark them as unused.
		 */
		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
		}
	else
		freelist = sp->next;

	/*
	 * Check whether we have forked. In that case, we must get rid of all
	 * inherited sessions and start allocating new ones.
	 */
	if (pid != (new_pid = getpid()))
		{
		pid = new_pid;

		/*
		 * We are a new process and thus need to free any inherited
		 * PK11_SESSION objects aside from the first session (sp) which
		 * is the only PK11_SESSION structure we will reuse (for the
		 * head of the list).
		 */
		while ((sp1 = freelist) != NULL)
			{
			freelist = sp1->next;
			/*
			 * NOTE: we do not want to call pk11_free_all_sessions()
			 * here because it would close underlying PKCS#11
			 * sessions and destroy all objects.
			 */
			pk11_free_nums(sp1, optype);
			OPENSSL_free(sp1);
			}

		/* we have to free the active list as well. */
		pk11_free_active_list(optype);

		/* Initialize the process */
		rv = pFuncList->C_Initialize(NULL_PTR);
		if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
			{
			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_INITIALIZE,
			    rv);
			OPENSSL_free(sp);
			sp = NULL;
			goto err;
			}

		/*
		 * Choose slot here since the slot table is different on this
		 * process. If we are here then we must have found at least one
		 * usable slot before so we don't need to check any_slot_found.
		 * See pk11_library_init()'s usage of this function for more
		 * information.
		 */
#ifdef	SOLARIS_HW_SLOT_SELECTION
		if (check_hw_mechanisms() == 0)
			goto err;
#endif	/* SOLARIS_HW_SLOT_SELECTION */
		if (pk11_choose_slots(NULL) == 0)
			goto err;

		/* Open the global_session for the new process */
		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
			NULL_PTR, NULL_PTR, &global_session);
		if (rv != CKR_OK)
			{
			PK11err_add_data(PK11_F_GET_SESSION, PK11_R_OPENSESSION,
			    rv);
			OPENSSL_free(sp);
			sp = NULL;
			goto err;
			}

		/*
		 * It is an inherited session from our parent so it needs
		 * re-initialization.
		 */
		if (pk11_setup_session(sp, optype) == 0)
			{
			OPENSSL_free(sp);
			sp = NULL;
			goto err;
			}
		if (pk11_token_relogin(sp->session) == 0)
			{
			/*
			 * We will keep the session in the cache list and let
			 * the caller cope with the situation.
			 */
			freelist = sp;
			sp = NULL;
			goto err;
			}
		}

	if (sp->pid == 0)
		{
		/* It is a new session and needs initialization. */
		if (pk11_setup_session(sp, optype) == 0)
			{
			OPENSSL_free(sp);
			sp = NULL;
			}
		}

	/* set new head for the list of PK11_SESSION objects */
	session_cache[optype].head = freelist;

err:
	if (sp != NULL)
		sp->next = NULL;

	(void) pthread_mutex_unlock(freelist_lock);

	return (sp);
	}


void
pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype)
	{
	pthread_mutex_t *freelist_lock;
	PK11_SESSION *freelist;

	/*
	 * If this is a session from the parent it will be taken care of and
	 * freed in pk11_get_session() as part of the post-fork clean up the
	 * next time we will ask for a new session.
	 */
	if (sp == NULL || sp->pid != getpid())
		return;

	switch (optype)
		{
		case OP_RSA:
		case OP_DSA:
		case OP_DH:
		case OP_RAND:
		case OP_DIGEST:
		case OP_CIPHER:
			freelist_lock = session_cache[optype].lock;
			break;
		default:
			PK11err(PK11_F_RETURN_SESSION,
				PK11_R_INVALID_OPERATION_TYPE);
			return;
		}

	(void) pthread_mutex_lock(freelist_lock);
	freelist = session_cache[optype].head;
	sp->next = freelist;
	session_cache[optype].head = sp;
	(void) pthread_mutex_unlock(freelist_lock);
	}


/* Destroy all objects. This function is called when the engine is finished */
static int pk11_free_all_sessions()
	{
	int ret = 1;
	int type;

#ifndef OPENSSL_NO_RSA
	(void) pk11_destroy_rsa_key_objects(NULL);
#endif	/* OPENSSL_NO_RSA */
#ifndef OPENSSL_NO_DSA
	(void) pk11_destroy_dsa_key_objects(NULL);
#endif	/* OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_DH
	(void) pk11_destroy_dh_key_objects(NULL);
#endif	/* OPENSSL_NO_DH */
	(void) pk11_destroy_cipher_key_objects(NULL);

	/*
	 * We try to release as much as we can but any error means that we will
	 * return 0 on exit.
	 */
	for (type = 0; type < OP_MAX; type++)
		{
		if (pk11_free_session_list(type) == 0)
			ret = 0;
		}

	return (ret);
	}

/*
 * Destroy session structures from the linked list specified. Free as many
 * sessions as possible but any failure in C_CloseSession() means that we
 * return an error on return.
 */
static int pk11_free_session_list(PK11_OPTYPE optype)
	{
	CK_RV rv;
	PK11_SESSION *sp = NULL;
	PK11_SESSION *freelist = NULL;
	pid_t mypid = getpid();
	pthread_mutex_t *freelist_lock;
	int ret = 1;

	switch (optype)
		{
		case OP_RSA:
		case OP_DSA:
		case OP_DH:
		case OP_RAND:
		case OP_DIGEST:
		case OP_CIPHER:
			freelist_lock = session_cache[optype].lock;
			break;
		default:
			PK11err(PK11_F_FREE_ALL_SESSIONS,
				PK11_R_INVALID_OPERATION_TYPE);
			return (0);
		}

	(void) pthread_mutex_lock(freelist_lock);
	freelist = session_cache[optype].head;
	while ((sp = freelist) != NULL)
		{
		if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
			{
			rv = pFuncList->C_CloseSession(sp->session);
			if (rv != CKR_OK)
				{
				PK11err_add_data(PK11_F_FREE_ALL_SESSIONS,
					PK11_R_CLOSESESSION, rv);
				ret = 0;
				}
			}
		freelist = sp->next;
		pk11_free_nums(sp, optype);
		OPENSSL_free(sp);
		}

	(void) pthread_mutex_unlock(freelist_lock);
	return (ret);
	}


static int
pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype)
	{
	CK_RV rv;
	CK_SLOT_ID myslot;

	switch (optype)
		{
		case OP_RSA:
		case OP_DSA:
		case OP_DH:
			myslot = pubkey_SLOTID;
			break;
		case OP_RAND:
			myslot = rand_SLOTID;
			break;
		case OP_DIGEST:
		case OP_CIPHER:
			myslot = SLOTID;
			break;
		default:
			PK11err(PK11_F_SETUP_SESSION,
			    PK11_R_INVALID_OPERATION_TYPE);
			return (0);
		}

	sp->session = CK_INVALID_HANDLE;
	DEBUG_SLOT_SEL("%s: myslot=%d optype=%d\n", PK11_DBG, myslot, optype);
	rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
		NULL_PTR, NULL_PTR, &sp->session);
	if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
		{
		/*
		 * We are probably a child process so force the
		 * reinitialize of the session
		 */
		pk11_library_initialized = CK_FALSE;
		if (!pk11_library_init(NULL))
			return (0);
		rv = pFuncList->C_OpenSession(myslot, CKF_SERIAL_SESSION,
			NULL_PTR, NULL_PTR, &sp->session);
		}
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION, rv);
		return (0);
		}

	sp->pid = getpid();

	switch (optype)
		{
#ifndef OPENSSL_NO_RSA
		case OP_RSA:
			sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
			sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
			sp->opdata_rsa_pub = NULL;
			sp->opdata_rsa_n_num = NULL;
			sp->opdata_rsa_e_num = NULL;
			sp->opdata_rsa_priv = NULL;
			sp->opdata_rsa_d_num = NULL;
			break;
#endif	/* OPENSSL_NO_RSA */
#ifndef OPENSSL_NO_DSA
		case OP_DSA:
			sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
			sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
			sp->opdata_dsa_pub = NULL;
			sp->opdata_dsa_pub_num = NULL;
			sp->opdata_dsa_priv = NULL;
			sp->opdata_dsa_priv_num = NULL;
			break;
#endif	/* OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_DH
		case OP_DH:
			sp->opdata_dh_key = CK_INVALID_HANDLE;
			sp->opdata_dh = NULL;
			sp->opdata_dh_priv_num = NULL;
			break;
#endif	/* OPENSSL_NO_DH */
		case OP_CIPHER:
			sp->opdata_cipher_key = CK_INVALID_HANDLE;
			sp->opdata_encrypt = -1;
			break;
		}

	/*
	 * We always initialize the session as containing a non-persistent
	 * object. The key load functions set it to persistent if that is so.
	 */
	sp->persistent = CK_FALSE;
	return (1);
	}

#ifndef OPENSSL_NO_RSA
/*
 * Destroy all non-NULL RSA parameters. For the RSA keys by reference code,
 * public components 'n'/'e' are the key components we use to check for the
 * cache hit even for the private keys. So, no matter whether we are destroying
 * a public or a private key, we always free what we can.
 */
static void
destroy_all_rsa_params(PK11_SESSION *sp)
	{
	if (sp->opdata_rsa_n_num != NULL)
		{
		BN_free(sp->opdata_rsa_n_num);
		sp->opdata_rsa_n_num = NULL;
		}
	if (sp->opdata_rsa_e_num != NULL)
		{
		BN_free(sp->opdata_rsa_e_num);
		sp->opdata_rsa_e_num = NULL;
		}
	if (sp->opdata_rsa_d_num != NULL)
		{
		BN_free(sp->opdata_rsa_d_num);
		sp->opdata_rsa_d_num = NULL;
		}
	}

/* Destroy RSA public key from single session. */
int
pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
	{
	int ret = 0;

	if (sp->opdata_rsa_pub_key != CK_INVALID_HANDLE)
		{
		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_pub_key,
		    ret, uselock, OP_RSA);
		sp->opdata_rsa_pub_key = CK_INVALID_HANDLE;
		sp->opdata_rsa_pub = NULL;
		destroy_all_rsa_params(sp);
		}

	return (ret);
	}

/* Destroy RSA private key from single session. */
int
pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
	{
	int ret = 0;

	if (sp->opdata_rsa_priv_key != CK_INVALID_HANDLE)
		{
		TRY_OBJ_DESTROY(sp, sp->opdata_rsa_priv_key,
		    ret, uselock, OP_RSA);
		sp->opdata_rsa_priv_key = CK_INVALID_HANDLE;
		sp->opdata_rsa_priv = NULL;
		destroy_all_rsa_params(sp);
		}

	return (ret);
	}

/*
 * Destroy RSA key object wrapper. If session is NULL, try to destroy all
 * objects in the free list.
 */
int
pk11_destroy_rsa_key_objects(PK11_SESSION *session)
	{
	int ret = 1;
	PK11_SESSION *sp = NULL;
	PK11_SESSION *local_free_session;
	CK_BBOOL uselock = CK_TRUE;

	if (session != NULL)
		local_free_session = session;
	else
		{
		(void) pthread_mutex_lock(session_cache[OP_RSA].lock);
		local_free_session = session_cache[OP_RSA].head;
		uselock = CK_FALSE;
		}

	/*
	 * go through the list of sessions and delete key objects
	 */
	while ((sp = local_free_session) != NULL)
		{
		local_free_session = sp->next;

		/*
		 * Do not terminate list traversal if one of the
		 * destroy operations fails.
		 */
		if (pk11_destroy_rsa_object_pub(sp, uselock) == 0)
			{
			ret = 0;
			continue;
			}
		if (pk11_destroy_rsa_object_priv(sp, uselock) == 0)
			{
			ret = 0;
			continue;
			}
		}

	if (session == NULL)
		(void) pthread_mutex_unlock(session_cache[OP_RSA].lock);

	return (ret);
	}
#endif	/* OPENSSL_NO_RSA */

#ifndef OPENSSL_NO_DSA
/* Destroy DSA public key from single session. */
int
pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock)
	{
	int ret = 0;

	if (sp->opdata_dsa_pub_key != CK_INVALID_HANDLE)
		{
		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_pub_key,
		    ret, uselock, OP_DSA);
		sp->opdata_dsa_pub_key = CK_INVALID_HANDLE;
		sp->opdata_dsa_pub = NULL;
		if (sp->opdata_dsa_pub_num != NULL)
			{
			BN_free(sp->opdata_dsa_pub_num);
			sp->opdata_dsa_pub_num = NULL;
			}
		}

	return (ret);
	}

/* Destroy DSA private key from single session. */
int
pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock)
	{
	int ret = 0;

	if (sp->opdata_dsa_priv_key != CK_INVALID_HANDLE)
		{
		TRY_OBJ_DESTROY(sp, sp->opdata_dsa_priv_key,
		    ret, uselock, OP_DSA);
		sp->opdata_dsa_priv_key = CK_INVALID_HANDLE;
		sp->opdata_dsa_priv = NULL;
		if (sp->opdata_dsa_priv_num != NULL)
			{
			BN_free(sp->opdata_dsa_priv_num);
			sp->opdata_dsa_priv_num = NULL;
			}
		}

	return (ret);
	}

/*
 * Destroy DSA key object wrapper. If session is NULL, try to destroy all
 * objects in the free list.
 */
int
pk11_destroy_dsa_key_objects(PK11_SESSION *session)
	{
	int ret = 1;
	PK11_SESSION *sp = NULL;
	PK11_SESSION *local_free_session;
	CK_BBOOL uselock = CK_TRUE;

	if (session != NULL)
		local_free_session = session;
	else
		{
		(void) pthread_mutex_lock(session_cache[OP_DSA].lock);
		local_free_session = session_cache[OP_DSA].head;
		uselock = CK_FALSE;
		}

	/*
	 * go through the list of sessions and delete key objects
	 */
	while ((sp = local_free_session) != NULL)
		{
		local_free_session = sp->next;

		/*
		 * Do not terminate list traversal if one of the
		 * destroy operations fails.
		 */
		if (pk11_destroy_dsa_object_pub(sp, uselock) == 0)
			{
			ret = 0;
			continue;
			}
		if (pk11_destroy_dsa_object_priv(sp, uselock) == 0)
			{
			ret = 0;
			continue;
			}
		}

	if (session == NULL)
		(void) pthread_mutex_unlock(session_cache[OP_DSA].lock);

	return (ret);
	}
#endif	/* OPENSSL_NO_DSA */

#ifndef OPENSSL_NO_DH
/* Destroy DH key from single session. */
int
pk11_destroy_dh_object(PK11_SESSION *sp, CK_BBOOL uselock)
	{
	int ret = 0;

	if (sp->opdata_dh_key != CK_INVALID_HANDLE)
		{
		TRY_OBJ_DESTROY(sp, sp->opdata_dh_key,
		    ret, uselock, OP_DH);
		sp->opdata_dh_key = CK_INVALID_HANDLE;
		sp->opdata_dh = NULL;
		if (sp->opdata_dh_priv_num != NULL)
			{
			BN_free(sp->opdata_dh_priv_num);
			sp->opdata_dh_priv_num = NULL;
			}
		}

	return (ret);
	}

/*
 * Destroy DH key object wrapper.
 *
 * arg0: pointer to PKCS#11 engine session structure
 *       if session is NULL, try to destroy all objects in the free list
 */
int
pk11_destroy_dh_key_objects(PK11_SESSION *session)
	{
	int ret = 1;
	PK11_SESSION *sp = NULL;
	PK11_SESSION *local_free_session;
	CK_BBOOL uselock = CK_TRUE;

	if (session != NULL)
		local_free_session = session;
	else
		{
		(void) pthread_mutex_lock(session_cache[OP_DH].lock);
		local_free_session = session_cache[OP_DH].head;
		uselock = CK_FALSE;
		}

	while ((sp = local_free_session) != NULL)
		{
		local_free_session = sp->next;

		/*
		 * Do not terminate list traversal if one of the
		 * destroy operations fails.
		 */
		if (pk11_destroy_dh_object(sp, uselock) == 0)
			{
			ret = 0;
			continue;
			}
		}
err:
	if (session == NULL)
		(void) pthread_mutex_unlock(session_cache[OP_DH].lock);

	return (ret);
	}
#endif	/* OPENSSL_NO_DH */

static int
pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh,
    CK_BBOOL persistent)
	{
	CK_RV rv;

	/*
	 * We never try to destroy persistent objects which are the objects
	 * stored in the keystore. Also, we always use read-only sessions so
	 * C_DestroyObject() would be returning CKR_SESSION_READ_ONLY here.
	 */
	if (persistent == CK_TRUE)
		return (1);

	rv = pFuncList->C_DestroyObject(session, oh);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT,
		    rv);
		return (0);
		}

	return (1);
	}


/* Symmetric ciphers and digests support functions */

static int
cipher_nid_to_pk11(int nid)
	{
	int i;

	for (i = 0; i < PK11_CIPHER_MAX; i++)
		if (ciphers[i].nid == nid)
			return (ciphers[i].id);
	return (-1);
	}

static int
pk11_usable_ciphers(const int **nids)
	{
	if (cipher_count > 0)
		*nids = cipher_nids;
	else
		*nids = NULL;
	return (cipher_count);
	}

static int
pk11_usable_digests(const int **nids)
	{
	if (digest_count > 0)
		*nids = digest_nids;
	else
		*nids = NULL;
	return (digest_count);
	}

/*
 * Init context for encryption or decryption using a symmetric key.
 */
static int pk11_init_symmetric(EVP_CIPHER_CTX *ctx, PK11_CIPHER *pcipher,
	PK11_SESSION *sp, CK_MECHANISM_PTR pmech)
	{
	CK_RV rv;
#ifdef	SOLARIS_AES_CTR
	CK_AES_CTR_PARAMS ctr_params;
#endif	/* SOLARIS_AES_CTR */

	/*
	 * We expect pmech->mechanism to be already set and
	 * pParameter/ulParameterLen initialized to NULL/0 before
	 * pk11_init_symmetric() is called.
	 */
	OPENSSL_assert(pmech->mechanism != NULL);
	OPENSSL_assert(pmech->pParameter == NULL);
	OPENSSL_assert(pmech->ulParameterLen == 0);

#ifdef	SOLARIS_AES_CTR
	if (ctx->cipher->nid == NID_aes_128_ctr ||
	    ctx->cipher->nid == NID_aes_192_ctr ||
	    ctx->cipher->nid == NID_aes_256_ctr)
		{
		pmech->pParameter = (void *)(&ctr_params);
		pmech->ulParameterLen = sizeof (ctr_params);
		/*
		 * For now, we are limited to the fixed length of the counter,
		 * it covers the whole counter block. That's what RFC 4344
		 * needs. For more information on internal structure of the
		 * counter block, see RFC 3686. If needed in the future, we can
		 * add code so that the counter length can be set via
		 * ENGINE_ctrl() function.
		 */
		ctr_params.ulCounterBits = AES_BLOCK_SIZE * 8;
		OPENSSL_assert(pcipher->iv_len == AES_BLOCK_SIZE);
		(void) memcpy(ctr_params.cb, ctx->iv, AES_BLOCK_SIZE);
		}
	else
#endif	/* SOLARIS_AES_CTR */
		{
		if (pcipher->iv_len > 0)
			{
			pmech->pParameter = (void *)ctx->iv;
			pmech->ulParameterLen = pcipher->iv_len;
			}
		}

	/* if we get here, the encryption needs to be reinitialized */
	if (ctx->encrypt)
		rv = pFuncList->C_EncryptInit(sp->session, pmech,
			sp->opdata_cipher_key);
	else
		rv = pFuncList->C_DecryptInit(sp->session, pmech,
			sp->opdata_cipher_key);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_CIPHER_INIT, ctx->encrypt ?
		    PK11_R_ENCRYPTINIT : PK11_R_DECRYPTINIT, rv);
		pk11_return_session(sp, OP_CIPHER);
		return (0);
		}

	return (1);
	}

/* ARGSUSED */
static int
pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
    const unsigned char *iv, int enc)
	{
	CK_MECHANISM mech;
	int index;
	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
	PK11_SESSION *sp;
	PK11_CIPHER *p_ciph_table_row;

	state->sp = NULL;

	index = cipher_nid_to_pk11(ctx->cipher->nid);
	if (index < 0 || index >= PK11_CIPHER_MAX)
		return (0);

	p_ciph_table_row = &ciphers[index];
	/*
	 * iv_len in the ctx->cipher structure is the maximum IV length for the
	 * current cipher and it must be less or equal to the IV length in our
	 * ciphers table. The key length must be in the allowed interval. From
	 * all cipher modes that the PKCS#11 engine supports only RC4 allows a
	 * key length to be in some range, all other NIDs have a precise key
	 * length. Every application can define its own EVP functions so this
	 * code serves as a sanity check.
	 *
	 * Note that the reason why the IV length in ctx->cipher might be
	 * greater than the actual length is that OpenSSL uses BLOCK_CIPHER_defs
	 * macro to define functions that return EVP structures for all DES
	 * modes. So, even ECB modes get 8 byte IV.
	 */
	if (ctx->cipher->iv_len < p_ciph_table_row->iv_len ||
	    ctx->key_len < p_ciph_table_row->min_key_len ||
	    ctx->key_len > p_ciph_table_row->max_key_len) {
		PK11err(PK11_F_CIPHER_INIT, PK11_R_KEY_OR_IV_LEN_PROBLEM);
		return (0);
	}

	if ((sp = pk11_get_session(OP_CIPHER)) == NULL)
		return (0);

	/* if applicable, the mechanism parameter is used for IV */
	mech.mechanism = p_ciph_table_row->mech_type;
	mech.pParameter = NULL;
	mech.ulParameterLen = 0;

	/* The key object is destroyed here if it is not the current key. */
	(void) check_new_cipher_key(sp, key, ctx->key_len);

	/*
	 * If the key is the same and the encryption is also the same, then
	 * just reuse it. However, we must not forget to reinitialize the
	 * context that was finalized in pk11_cipher_cleanup().
	 */
	if (sp->opdata_cipher_key != CK_INVALID_HANDLE &&
	    sp->opdata_encrypt == ctx->encrypt)
		{
		state->sp = sp;
		if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
			return (0);

		return (1);
		}

	/*
	 * Check if the key has been invalidated. If so, a new key object
	 * needs to be created.
	 */
	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
		{
		sp->opdata_cipher_key = pk11_get_cipher_key(
			ctx, key, p_ciph_table_row->key_type, sp);
		}

	if (sp->opdata_encrypt != ctx->encrypt && sp->opdata_encrypt != -1)
		{
		/*
		 * The previous encryption/decryption is different. Need to
		 * terminate the previous * active encryption/decryption here.
		 */
		if (!pk11_cipher_final(sp))
			{
			pk11_return_session(sp, OP_CIPHER);
			return (0);
			}
		}

	if (sp->opdata_cipher_key == CK_INVALID_HANDLE)
		{
		pk11_return_session(sp, OP_CIPHER);
		return (0);
		}

	/* now initialize the context with a new key */
	if (pk11_init_symmetric(ctx, p_ciph_table_row, sp, &mech) == 0)
		return (0);

	sp->opdata_encrypt = ctx->encrypt;
	state->sp = sp;

	return (1);
	}

/*
 * When reusing the same key in an encryption/decryption session for a
 * decryption/encryption session, we need to close the active session
 * and recreate a new one. Note that the key is in the global session so
 * that it needs not be recreated.
 *
 * It is more appropriate to use C_En/DecryptFinish here. At the time of this
 * development, these two functions in the PKCS#11 libraries used return
 * unexpected errors when passing in 0 length output. It may be a good
 * idea to try them again if performance is a problem here and fix
 * C_En/DecryptFinial if there are bugs there causing the problem.
 */
static int
pk11_cipher_final(PK11_SESSION *sp)
	{
	CK_RV rv;

	rv = pFuncList->C_CloseSession(sp->session);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION, rv);
		return (0);
		}

	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
		NULL_PTR, NULL_PTR, &sp->session);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION, rv);
		return (0);
		}

	return (1);
	}

/*
 * An engine interface function. The calling function allocates sufficient
 * memory for the output buffer "out" to hold the results.
 */
static int
pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
	const unsigned char *in, size_t inl)
	{
	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
	PK11_SESSION *sp;
	CK_RV rv;
	unsigned long outl = inl;

	if (state == NULL || state->sp == NULL)
		return (0);

	sp = (PK11_SESSION *) state->sp;

	if (!inl)
		return (1);

	/* RC4 is the only stream cipher we support */
	if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
		return (0);

	if (ctx->encrypt)
		{
		rv = pFuncList->C_EncryptUpdate(sp->session,
			(unsigned char *)in, inl, out, &outl);

		if (rv != CKR_OK)
			{
			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
			    PK11_R_ENCRYPTUPDATE, rv);
			return (0);
			}
		}
	else
		{
		rv = pFuncList->C_DecryptUpdate(sp->session,
			(unsigned char *)in, inl, out, &outl);

		if (rv != CKR_OK)
			{
			PK11err_add_data(PK11_F_CIPHER_DO_CIPHER,
			    PK11_R_DECRYPTUPDATE, rv);
			return (0);
			}
		}

	/*
	 * For DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
	 * the same size of input.
	 * The application has guaranteed to call the block ciphers with
	 * correctly aligned buffers.
	 */
	if (inl != outl)
		return (0);

	return (1);
	}

/*
 * Return the session to the pool. Calling C_EncryptFinal() and C_DecryptFinal()
 * here is the right thing because in EVP_DecryptFinal_ex(), engine's
 * do_cipher() is not even called, and in EVP_EncryptFinal_ex() it is called but
 * the engine can't find out that it's the finalizing call. We wouldn't
 * necessarily have to finalize the context here since reinitializing it with
 * C_(Encrypt|Decrypt)Init() should be fine but for the sake of correctness,
 * let's do it. Some implementations might leak memory if the previously used
 * context is initialized without finalizing it first.
 */
static int
pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
	{
	CK_RV rv;
	CK_ULONG len = EVP_MAX_BLOCK_LENGTH;
	CK_BYTE buf[EVP_MAX_BLOCK_LENGTH];
	PK11_CIPHER_STATE *state = ctx->cipher_data;

	if (state != NULL && state->sp != NULL)
		{
		/*
		 * We are not interested in the data here, we just need to get
		 * rid of the context.
		 */
		if (ctx->encrypt)
			rv = pFuncList->C_EncryptFinal(
			    state->sp->session, buf, &len);
		else
			rv = pFuncList->C_DecryptFinal(
			    state->sp->session, buf, &len);

		if (rv != CKR_OK)
			{
			PK11err_add_data(PK11_F_CIPHER_CLEANUP, ctx->encrypt ?
			    PK11_R_ENCRYPTFINAL : PK11_R_DECRYPTFINAL, rv);
			pk11_return_session(state->sp, OP_CIPHER);
			return (0);
			}

		pk11_return_session(state->sp, OP_CIPHER);
		state->sp = NULL;
		}

	return (1);
	}

/*
 * Registered by the ENGINE when used to find out how to deal with
 * a particular NID in the ENGINE. This says what we'll do at the
 * top level - note, that list is restricted by what we answer with
 */
/* ARGSUSED */
static int
pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
	const int **nids, int nid)
	{
	if (!cipher)
		return (pk11_usable_ciphers(nids));

	switch (nid)
		{
		case NID_des_ede3_cbc:
			*cipher = &pk11_3des_cbc;
			break;
		case NID_des_cbc:
			*cipher = &pk11_des_cbc;
			break;
		case NID_des_ede3_ecb:
			*cipher = &pk11_3des_ecb;
			break;
		case NID_des_ecb:
			*cipher = &pk11_des_ecb;
			break;
		case NID_aes_128_cbc:
			*cipher = &pk11_aes_128_cbc;
			break;
		case NID_aes_192_cbc:
			*cipher = &pk11_aes_192_cbc;
			break;
		case NID_aes_256_cbc:
			*cipher = &pk11_aes_256_cbc;
			break;
		case NID_aes_128_ecb:
			*cipher = &pk11_aes_128_ecb;
			break;
		case NID_aes_192_ecb:
			*cipher = &pk11_aes_192_ecb;
			break;
		case NID_aes_256_ecb:
			*cipher = &pk11_aes_256_ecb;
			break;
		case NID_bf_cbc:
			*cipher = &pk11_bf_cbc;
			break;
		case NID_rc4:
			*cipher = &pk11_rc4;
			break;
		default:
#ifdef	SOLARIS_AES_CTR
			/*
			 * These can't be in separated cases because the NIDs
			 * here are not constants.
			 */
			if (nid == NID_aes_128_ctr)
				*cipher = &pk11_aes_128_ctr;
			else if (nid == NID_aes_192_ctr)
				*cipher = &pk11_aes_192_ctr;
			else if (nid == NID_aes_256_ctr)
				*cipher = &pk11_aes_256_ctr;
			else
#endif	/* SOLARIS_AES_CTR */
			*cipher = NULL;
			break;
		}
	return (*cipher != NULL);
	}

/* ARGSUSED */
static int
pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
	const int **nids, int nid)
	{
	if (!digest)
		return (pk11_usable_digests(nids));

	switch (nid)
		{
		case NID_md5:
			*digest = &pk11_md5;
			break;
		/*
		 * A special case. For "openssl dgst -dss1 -engine pkcs11 ...",
		 * OpenSSL calls EVP_get_digestbyname() on "dss1" which ends up
		 * calling pk11_engine_digests() for NID_dsa. Internally, if an
		 * engine is not used, OpenSSL uses SHA1_Init() as expected for
		 * DSA. So, we must return pk11_sha1() for NID_dsa as well. Note
		 * that this must have changed between 0.9.8 and 1.0.0 since we
		 * did not have the problem with the 0.9.8 version.
		 */
		case NID_sha1:
		case NID_dsa:
			*digest = &pk11_sha1;
			break;
		case NID_sha224:
			*digest = &pk11_sha224;
			break;
		case NID_sha256:
			*digest = &pk11_sha256;
			break;
		case NID_sha384:
			*digest = &pk11_sha384;
			break;
		case NID_sha512:
			*digest = &pk11_sha512;
			break;
		default:
			*digest = NULL;
			break;
		}
	return (*digest != NULL);
	}


/* Create a secret key object in a PKCS#11 session */
static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
	{
	CK_RV rv;
	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
	CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
	CK_ULONG ul_key_attr_count = 6;

	CK_ATTRIBUTE  a_key_template[] =
		{
		{CKA_CLASS, (void*) NULL, sizeof (CK_OBJECT_CLASS)},
		{CKA_KEY_TYPE, (void*) NULL, sizeof (CK_KEY_TYPE)},
		{CKA_TOKEN, &pk11_false, sizeof (pk11_false)},
		{CKA_ENCRYPT, &pk11_true, sizeof (pk11_true)},
		{CKA_DECRYPT, &pk11_true, sizeof (pk11_true)},
		{CKA_VALUE, (void*) NULL, 0},
		};

	/*
	 * Create secret key object in global_session. All other sessions
	 * can use the key handles. Here is why:
	 * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
	 * It may then call DecryptInit and DecryptUpdate using the same key.
	 * To use the same key object, we need to call EncryptFinal with
	 * a 0 length message. Currently, this does not work for 3DES
	 * mechanism. To get around this problem, we close the session and
	 * then create a new session to use the same key object. When a session
	 * is closed, all the object handles will be invalid. Thus, create key
	 * objects in a global session, an individual session may be closed to
	 * terminate the active operation.
	 */
	CK_SESSION_HANDLE session = global_session;
	a_key_template[0].pValue = &obj_key;
	a_key_template[1].pValue = &key_type;
	a_key_template[5].pValue = (void *) key;
	a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;

	rv = pFuncList->C_CreateObject(session,
		a_key_template, ul_key_attr_count, &h_key);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT,
		    rv);
		goto err;
		}

	/*
	 * Save the key information used in this session.
	 * The max can be saved is PK11_KEY_LEN_MAX.
	 */
	sp->opdata_key_len = ctx->key_len > PK11_KEY_LEN_MAX ?
		PK11_KEY_LEN_MAX : ctx->key_len;
	(void) memcpy(sp->opdata_key, key, sp->opdata_key_len);
err:

	return (h_key);
	}

static int
md_nid_to_pk11(int nid)
	{
	int i;

	for (i = 0; i < PK11_DIGEST_MAX; i++)
		if (digests[i].nid == nid)
			return (digests[i].id);
	return (-1);
	}

static int
pk11_digest_init(EVP_MD_CTX *ctx)
	{
	CK_RV rv;
	CK_MECHANISM mech;
	int index;
	PK11_SESSION *sp;
	PK11_DIGEST *pdp;
	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;

	state->sp = NULL;

	index = md_nid_to_pk11(ctx->digest->type);
	if (index < 0 || index >= PK11_DIGEST_MAX)
		return (0);

	pdp = &digests[index];
	if ((sp = pk11_get_session(OP_DIGEST)) == NULL)
		return (0);

	/* at present, no parameter is needed for supported digests */
	mech.mechanism = pdp->mech_type;
	mech.pParameter = NULL;
	mech.ulParameterLen = 0;

	rv = pFuncList->C_DigestInit(sp->session, &mech);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT, rv);
		pk11_return_session(sp, OP_DIGEST);
		return (0);
		}

	state->sp = sp;

	return (1);
	}

static int
pk11_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
	{
	CK_RV rv;
	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;

	/* 0 length message will cause a failure in C_DigestFinal */
	if (count == 0)
		return (1);

	if (state == NULL || state->sp == NULL)
		return (0);

	rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
		count);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE, rv);
		pk11_return_session(state->sp, OP_DIGEST);
		state->sp = NULL;
		return (0);
		}

	return (1);
	}

static int
pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
	{
	CK_RV rv;
	unsigned long len;
	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
	len = ctx->digest->md_size;

	if (state == NULL || state->sp == NULL)
		return (0);

	rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL, rv);
		pk11_return_session(state->sp, OP_DIGEST);
		state->sp = NULL;
		return (0);
		}

	if (ctx->digest->md_size != len)
		return (0);

	/*
	 * Final is called and digest is returned, so return the session
	 * to the pool
	 */
	pk11_return_session(state->sp, OP_DIGEST);
	state->sp = NULL;

	return (1);
	}

static int
pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
	{
	CK_RV rv;
	int ret = 0;
	PK11_CIPHER_STATE *state, *state_to;
	CK_BYTE_PTR pstate = NULL;
	CK_ULONG ul_state_len;

	if (from->md_data == NULL || to->digest->ctx_size == 0)
		return (1);

	/* The copy-from state */
	state = (PK11_CIPHER_STATE *) from->md_data;
	if (state->sp == NULL)
		goto err;

	/* Initialize the copy-to state */
	if (!pk11_digest_init(to))
		goto err;
	state_to = (PK11_CIPHER_STATE *) to->md_data;

	/* Get the size of the operation state of the copy-from session */
	rv = pFuncList->C_GetOperationState(state->sp->session, NULL,
		&ul_state_len);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
		    rv);
		goto err;
		}
	if (ul_state_len == 0)
		{
		goto err;
		}

	pstate = OPENSSL_malloc(ul_state_len);
	if (pstate == NULL)
		{
		PK11err(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
		goto err;
		}

	/* Get the operation state of the copy-from session */
	rv = pFuncList->C_GetOperationState(state->sp->session, pstate,
		&ul_state_len);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE,
		    rv);
		goto err;
		}

	/* Set the operation state of the copy-to session */
	rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate,
		ul_state_len, 0, 0);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_DIGEST_COPY,
		    PK11_R_SET_OPERATION_STATE, rv);
		goto err;
		}

	ret = 1;
err:
	if (pstate != NULL)
		OPENSSL_free(pstate);

	return (ret);
	}

/* Return any pending session state to the pool */
static int
pk11_digest_cleanup(EVP_MD_CTX *ctx)
	{
	PK11_CIPHER_STATE *state = ctx->md_data;
	unsigned char buf[EVP_MAX_MD_SIZE];

	if (state != NULL && state->sp != NULL)
		{
		/*
		 * If state->sp is not NULL then pk11_digest_final() has not
		 * been called yet. We must call it now to free any memory
		 * that might have been allocated in the token when
		 * pk11_digest_init() was called. pk11_digest_final()
		 * will return the session to the cache.
		 */
		if (!pk11_digest_final(ctx, buf))
			return (0);
		}

	return (1);
	}

/*
 * Check if the new key is the same as the key object in the session. If the key
 * is the same, no need to create a new key object. Otherwise, the old key
 * object needs to be destroyed and a new one will be created. Return 1 for
 * cache hit, 0 for cache miss. Note that we must check the key length first
 * otherwise we could end up reusing a different, longer key with the same
 * prefix.
 */
static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
	int key_len)
	{
	if (sp->opdata_key_len != key_len ||
	    memcmp(sp->opdata_key, key, key_len) != 0)
		{
		(void) pk11_destroy_cipher_key_objects(sp);
		return (0);
		}
	return (1);
	}

/* Destroy one or more secret key objects. */
static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
	{
	int ret = 0;
	PK11_SESSION *sp = NULL;
	PK11_SESSION *local_free_session;

	if (session != NULL)
		local_free_session = session;
	else
		{
		(void) pthread_mutex_lock(session_cache[OP_CIPHER].lock);
		local_free_session = session_cache[OP_CIPHER].head;
		}

	while ((sp = local_free_session) != NULL)
		{
		local_free_session = sp->next;

		if (sp->opdata_cipher_key != CK_INVALID_HANDLE)
			{
			/*
			 * The secret key object is created in the
			 * global_session. See pk11_get_cipher_key().
			 */
			if (pk11_destroy_object(global_session,
				sp->opdata_cipher_key, CK_FALSE) == 0)
				goto err;
			sp->opdata_cipher_key = CK_INVALID_HANDLE;
			}
		}
	ret = 1;
err:

	if (session == NULL)
		(void) pthread_mutex_unlock(session_cache[OP_CIPHER].lock);

	return (ret);
	}


/*
 * Public key mechanisms optionally supported
 *
 * CKM_RSA_X_509
 * CKM_RSA_PKCS
 * CKM_DSA
 *
 * The first slot that supports at least one of those mechanisms is chosen as a
 * public key slot.
 *
 * Symmetric ciphers optionally supported
 *
 * CKM_DES3_CBC
 * CKM_DES_CBC
 * CKM_AES_CBC
 * CKM_DES3_ECB
 * CKM_DES_ECB
 * CKM_AES_ECB
 * CKM_AES_CTR
 * CKM_RC4
 * CKM_BLOWFISH_CBC
 *
 * Digests optionally supported
 *
 * CKM_MD5
 * CKM_SHA_1
 * CKM_SHA224
 * CKM_SHA256
 * CKM_SHA384
 * CKM_SHA512
 *
 * The output of this function is a set of global variables indicating which
 * mechanisms from RSA, DSA, DH and RAND are present, and also two arrays of
 * mechanisms, one for symmetric ciphers and one for digests. Also, 3 global
 * variables carry information about which slot was chosen for (a) public key
 * mechanisms, (b) random operations, and (c) symmetric ciphers and digests.
 */
static int
pk11_choose_slots(int *any_slot_found)
	{
	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
	CK_ULONG ulSlotCount = 0;
	CK_MECHANISM_INFO mech_info;
	CK_TOKEN_INFO token_info;
	int i;
	CK_RV rv;
	CK_SLOT_ID best_slot_sofar;
	CK_BBOOL found_candidate_slot = CK_FALSE;
	int slot_n_cipher = 0;
	int slot_n_digest = 0;
	CK_SLOT_ID current_slot = 0;
	int current_slot_n_cipher = 0;
	int current_slot_n_digest = 0;

	int local_cipher_nids[PK11_CIPHER_MAX];
	int local_digest_nids[PK11_DIGEST_MAX];

	/* let's initialize the output parameter */
	if (any_slot_found != NULL)
		*any_slot_found = 0;

	/* Get slot list for memory allocation */
	rv = pFuncList->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);

	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
		return (0);
		}

	/* it's not an error if we didn't find any providers */
	if (ulSlotCount == 0)
		{
		DEBUG_SLOT_SEL("%s: no crypto providers found\n", PK11_DBG);
		return (1);
		}

	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));

	if (pSlotList == NULL)
		{
		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_MALLOC_FAILURE);
		return (0);
		}

	/* Get the slot list for processing */
	rv = pFuncList->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
	if (rv != CKR_OK)
		{
		PK11err_add_data(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST, rv);
		OPENSSL_free(pSlotList);
		return (0);
		}

	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, def_PK11_LIBNAME);
	DEBUG_SLOT_SEL("%s: number of slots: %d\n", PK11_DBG, ulSlotCount);

	DEBUG_SLOT_SEL("%s: == checking rand slots ==\n", PK11_DBG);
	for (i = 0; i < ulSlotCount; i++)
		{
		current_slot = pSlotList[i];

		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);
		/* Check if slot has random support. */
		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
		if (rv != CKR_OK)
			continue;

		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
		    token_info.label);

		if (token_info.flags & CKF_RNG)
			{
			DEBUG_SLOT_SEL(
			    "%s: this token has CKF_RNG flag\n", PK11_DBG);
			pk11_have_random = CK_TRUE;
			rand_SLOTID = current_slot;
			break;
			}
		}

	DEBUG_SLOT_SEL("%s: == checking pubkey slots ==\n", PK11_DBG);

	pubkey_SLOTID = pSlotList[0];
	for (i = 0; i < ulSlotCount; i++)
		{
		CK_BBOOL slot_has_rsa = CK_FALSE;
		CK_BBOOL slot_has_dsa = CK_FALSE;
		CK_BBOOL slot_has_dh = CK_FALSE;
		current_slot = pSlotList[i];

		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);
		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
		if (rv != CKR_OK)
			continue;

		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
		    token_info.label);

#ifndef OPENSSL_NO_RSA
		/*
		 * Check if this slot is capable of signing and
		 * verifying with CKM_RSA_PKCS.
		 */
		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS,
			&mech_info);

		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
				(mech_info.flags & CKF_VERIFY)))
			{
			/*
			 * Check if this slot is capable of encryption,
			 * decryption, sign, and verify with CKM_RSA_X_509.
			 */
			rv = pFuncList->C_GetMechanismInfo(current_slot,
			    CKM_RSA_X_509, &mech_info);

			if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
			    (mech_info.flags & CKF_VERIFY) &&
			    (mech_info.flags & CKF_ENCRYPT) &&
			    (mech_info.flags & CKF_VERIFY_RECOVER) &&
			    (mech_info.flags & CKF_DECRYPT)))
				{
				slot_has_rsa = CK_TRUE;
				}
			}
#endif	/* OPENSSL_NO_RSA */

#ifndef OPENSSL_NO_DSA
		/*
		 * Check if this slot is capable of signing and
		 * verifying with CKM_DSA.
		 */
		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA,
			&mech_info);
		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
		    (mech_info.flags & CKF_VERIFY)))
			{
			slot_has_dsa = CK_TRUE;
			}

#endif	/* OPENSSL_NO_DSA */

#ifndef OPENSSL_NO_DH
		/*
		 * Check if this slot is capable of DH key generataion and
		 * derivation.
		 */
		rv = pFuncList->C_GetMechanismInfo(current_slot,
		    CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);

		if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
			{
			rv = pFuncList->C_GetMechanismInfo(current_slot,
				CKM_DH_PKCS_DERIVE, &mech_info);
			if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
				{
				slot_has_dh = CK_TRUE;
				}
			}
#endif	/* OPENSSL_NO_DH */

		if (!found_candidate_slot &&
		    (slot_has_rsa || slot_has_dsa || slot_has_dh))
			{
			DEBUG_SLOT_SEL(
			    "%s: potential slot: %d\n", PK11_DBG, current_slot);
			best_slot_sofar = current_slot;
			pk11_have_rsa = slot_has_rsa;
			pk11_have_dsa = slot_has_dsa;
			pk11_have_dh = slot_has_dh;
			found_candidate_slot = CK_TRUE;
			/*
			 * Cache the flags for later use. We might need those if
			 * RSA keys by reference feature is used.
			 */
			pubkey_token_flags = token_info.flags;
			DEBUG_SLOT_SEL(
			    "%s: setting found_candidate_slot to CK_TRUE\n",
			    PK11_DBG);
			DEBUG_SLOT_SEL("%s: best slot so far: %d\n", PK11_DBG,
			    best_slot_sofar);
			DEBUG_SLOT_SEL("%s: pubkey flags changed to "
			    "%lu.\n", PK11_DBG, pubkey_token_flags);
			}
		else
			{
			DEBUG_SLOT_SEL("%s: no rsa/dsa/dh\n", PK11_DBG);
			}
		} /* for */

	if (found_candidate_slot == CK_TRUE)
		{
		pubkey_SLOTID = best_slot_sofar;
		}

	found_candidate_slot = CK_FALSE;
	best_slot_sofar = 0;

	DEBUG_SLOT_SEL("%s: == checking cipher/digest ==\n", PK11_DBG);

	SLOTID = pSlotList[0];
	for (i = 0; i < ulSlotCount; i++)
		{
		DEBUG_SLOT_SEL("%s: checking slot: %d\n", PK11_DBG, i);

		current_slot = pSlotList[i];
		current_slot_n_cipher = 0;
		current_slot_n_digest = 0;
		(void) memset(local_cipher_nids, 0, sizeof (local_cipher_nids));
		(void) memset(local_digest_nids, 0, sizeof (local_digest_nids));

		pk11_find_symmetric_ciphers(pFuncList, current_slot,
		    &current_slot_n_cipher, local_cipher_nids);

		pk11_find_digests(pFuncList, current_slot,
		    &current_slot_n_digest, local_digest_nids);

		DEBUG_SLOT_SEL("%s: current_slot_n_cipher %d\n", PK11_DBG,
			current_slot_n_cipher);
		DEBUG_SLOT_SEL("%s: current_slot_n_digest %d\n", PK11_DBG,
			current_slot_n_digest);
		DEBUG_SLOT_SEL("%s: best cipher/digest slot so far: %d\n",
			PK11_DBG, best_slot_sofar);

		/*
		 * If the current slot supports more ciphers/digests than
		 * the previous best one we change the current best to this one,
		 * otherwise leave it where it is.
		 */
		if ((current_slot_n_cipher + current_slot_n_digest) >
		    (slot_n_cipher + slot_n_digest))
			{
			DEBUG_SLOT_SEL("%s: changing best slot to %d\n",
				PK11_DBG, current_slot);
			best_slot_sofar = SLOTID = current_slot;
			cipher_count = slot_n_cipher = current_slot_n_cipher;
			digest_count = slot_n_digest = current_slot_n_digest;
			(void) memcpy(cipher_nids, local_cipher_nids,
			    sizeof (local_cipher_nids));
			(void) memcpy(digest_nids, local_digest_nids,
			    sizeof (local_digest_nids));
			}
		}

	DEBUG_SLOT_SEL("%s: chosen pubkey slot: %d\n", PK11_DBG, pubkey_SLOTID);
	DEBUG_SLOT_SEL("%s: chosen rand slot: %d\n", PK11_DBG, rand_SLOTID);
	DEBUG_SLOT_SEL("%s: chosen cipher/digest slot: %d\n", PK11_DBG, SLOTID);
	DEBUG_SLOT_SEL("%s: pk11_have_rsa %d\n", PK11_DBG, pk11_have_rsa);
	DEBUG_SLOT_SEL("%s: pk11_have_dsa %d\n", PK11_DBG, pk11_have_dsa);
	DEBUG_SLOT_SEL("%s: pk11_have_dh %d\n", PK11_DBG, pk11_have_dh);
	DEBUG_SLOT_SEL("%s: pk11_have_random %d\n", PK11_DBG, pk11_have_random);
	DEBUG_SLOT_SEL("%s: cipher_count %d\n", PK11_DBG, cipher_count);
	DEBUG_SLOT_SEL("%s: digest_count %d\n", PK11_DBG, digest_count);

	if (pSlotList != NULL)
		OPENSSL_free(pSlotList);

#ifdef	SOLARIS_HW_SLOT_SELECTION
	OPENSSL_free(hw_cnids);
	OPENSSL_free(hw_dnids);
#endif	/* SOLARIS_HW_SLOT_SELECTION */

	if (any_slot_found != NULL)
		*any_slot_found = 1;
	return (1);
	}

static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR pflist,
    int slot_id, int *current_slot_n_cipher, int *local_cipher_nids,
    PK11_CIPHER *cipher)
	{
	CK_MECHANISM_INFO mech_info;
	CK_RV rv;

	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, cipher->mech_type);
	rv = pflist->C_GetMechanismInfo(slot_id, cipher->mech_type, &mech_info);

	if (rv != CKR_OK)
		{
		DEBUG_SLOT_SEL(" not found\n");
		return;
		}

	if ((mech_info.flags & CKF_ENCRYPT) &&
	    (mech_info.flags & CKF_DECRYPT))
		{
		if (mech_info.ulMinKeySize > cipher->min_key_len ||
		    mech_info.ulMaxKeySize < cipher->max_key_len)
			{
			DEBUG_SLOT_SEL(" engine key size range <%i-%i> does not"
			    " match mech range <%lu-%lu>\n",
			    cipher->min_key_len, cipher->max_key_len,
			    mech_info.ulMinKeySize, mech_info.ulMaxKeySize);
			return;
			}
#ifdef	SOLARIS_HW_SLOT_SELECTION
		if (nid_in_table(cipher->nid, hw_cnids))
#endif	/* SOLARIS_HW_SLOT_SELECTION */
			{
			DEBUG_SLOT_SEL(" usable\n");
			local_cipher_nids[(*current_slot_n_cipher)++] =
			    cipher->nid;
			}
#ifdef	SOLARIS_HW_SLOT_SELECTION
		else
			{
			DEBUG_SLOT_SEL(
			    " rejected, software implementation only\n");
			}
#endif	/* SOLARIS_HW_SLOT_SELECTION */
		}
	else
		{
		DEBUG_SLOT_SEL(" unusable\n");
		}

	return;
	}

static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
    int *current_slot_n_digest, int *local_digest_nids, PK11_DIGEST *digest)
	{
	CK_MECHANISM_INFO mech_info;
	CK_RV rv;

	DEBUG_SLOT_SEL("%s: checking mech: %x", PK11_DBG, digest->mech_type);
	rv = pflist->C_GetMechanismInfo(slot_id, digest->mech_type, &mech_info);

	if (rv != CKR_OK)
		{
		DEBUG_SLOT_SEL(" not found\n");
		return;
		}

	if (mech_info.flags & CKF_DIGEST)
		{
#ifdef	SOLARIS_HW_SLOT_SELECTION
		if (nid_in_table(digest->nid, hw_dnids))
#endif	/* SOLARIS_HW_SLOT_SELECTION */
			{
			DEBUG_SLOT_SEL(" usable\n");
			local_digest_nids[(*current_slot_n_digest)++] =
			    digest->nid;
			}
#ifdef	SOLARIS_HW_SLOT_SELECTION
		else
			{
			DEBUG_SLOT_SEL(
			    " rejected, software implementation only\n");
			}
#endif	/* SOLARIS_HW_SLOT_SELECTION */
		}
	else
		{
		DEBUG_SLOT_SEL(" unusable\n");
		}

	return;
	}

#ifdef	SOLARIS_AES_CTR
/* create a new NID when we have no OID for that mechanism */
static int pk11_add_NID(char *sn, char *ln)
	{
	ASN1_OBJECT *o;
	int nid;

	if ((o = ASN1_OBJECT_create(OBJ_new_nid(1), (unsigned char *)"",
	    1, sn, ln)) == NULL)
		{
		return (0);
		}

	/* will return NID_undef on error */
	nid = OBJ_add_object(o);
	ASN1_OBJECT_free(o);

	return (nid);
	}

/*
 * Create new NIDs for AES counter mode. OpenSSL doesn't support them now so we
 * have to help ourselves here.
 */
static int pk11_add_aes_ctr_NIDs(void)
	{
	/* are we already set? */
	if (NID_aes_256_ctr != NID_undef)
		return (1);

	/*
	 * There are no official names for AES counter modes yet so we just
	 * follow the format of those that exist.
	 */
	if ((NID_aes_128_ctr = pk11_add_NID("AES-128-CTR", "aes-128-ctr")) ==
	    NID_undef)
		goto err;
	ciphers[PK11_AES_128_CTR].nid = pk11_aes_128_ctr.nid = NID_aes_128_ctr;
	if ((NID_aes_192_ctr = pk11_add_NID("AES-192-CTR", "aes-192-ctr")) ==
	    NID_undef)
		goto err;
	ciphers[PK11_AES_192_CTR].nid = pk11_aes_192_ctr.nid = NID_aes_192_ctr;
	if ((NID_aes_256_ctr = pk11_add_NID("AES-256-CTR", "aes-256-ctr")) ==
	    NID_undef)
		goto err;
	ciphers[PK11_AES_256_CTR].nid = pk11_aes_256_ctr.nid = NID_aes_256_ctr;
	return (1);

err:
	PK11err(PK11_F_ADD_AES_CTR_NIDS, PK11_R_ADD_NID_FAILED);
	return (0);
	}
#endif	/* SOLARIS_AES_CTR */

/* Find what symmetric ciphers this slot supports. */
static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
    CK_SLOT_ID current_slot, int *current_slot_n_cipher, int *local_cipher_nids)
	{
	int i;

	for (i = 0; i < PK11_CIPHER_MAX; ++i)
		{
		pk11_get_symmetric_cipher(pflist, current_slot,
		    current_slot_n_cipher, local_cipher_nids, &ciphers[i]);
		}
	}

/* Find what digest algorithms this slot supports. */
static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
    CK_SLOT_ID current_slot, int *current_slot_n_digest, int *local_digest_nids)
	{
	int i;

	for (i = 0; i < PK11_DIGEST_MAX; ++i)
		{
		pk11_get_digest(pflist, current_slot, current_slot_n_digest,
		    local_digest_nids, &digests[i]);
		}
	}

#ifdef	SOLARIS_HW_SLOT_SELECTION
/*
 * It would be great if we could use pkcs11_kernel directly since this library
 * offers hardware slots only. That's the easiest way to achieve the situation
 * where we use the hardware accelerators when present and OpenSSL native code
 * otherwise. That presumes the fact that OpenSSL native code is faster than the
 * code in the soft token. It's a logical assumption - Crypto Framework has some
 * inherent overhead so going there for the software implementation of a
 * mechanism should be logically slower in contrast to the OpenSSL native code,
 * presuming that both implementations are of similar speed. For example, the
 * soft token for AES is roughly three times slower than OpenSSL for 64 byte
 * blocks and still 20% slower for 8KB blocks. So, if we want to ship products
 * that use the PKCS#11 engine by default, we must somehow avoid that regression
 * on machines without hardware acceleration. That's why switching to the
 * pkcs11_kernel library seems like a very good idea.
 *
 * The problem is that OpenSSL built with SunStudio is roughly 2x slower for
 * asymmetric operations (RSA/DSA/DH) than the soft token built with the same
 * compiler. That means that if we switched to pkcs11_kernel from the libpkcs11
 * library, we would have had a performance regression on machines without
 * hardware acceleration for asymmetric operations for all applications that use
 * the PKCS#11 engine. There is one such application - Apache web server since
 * it's shipped configured to use the PKCS#11 engine by default. Having said
 * that, we can't switch to the pkcs11_kernel library now and have to come with
 * a solution that, on non-accelerated machines, uses the OpenSSL native code
 * for all symmetric ciphers and digests while it uses the soft token for
 * asymmetric operations.
 *
 * This is the idea: dlopen() pkcs11_kernel directly and find out what
 * mechanisms are there. We don't care about duplications (more slots can
 * support the same mechanism), we just want to know what mechanisms can be
 * possibly supported in hardware on that particular machine. As said before,
 * pkcs11_kernel will show you hardware providers only.
 *
 * Then, we rely on the fact that since we use libpkcs11 library we will find
 * the metaslot. When we go through the metaslot's mechanisms for symmetric
 * ciphers and digests, we check that any found mechanism is in the table
 * created using the pkcs11_kernel library. So, as a result we have two arrays
 * of mechanisms that were advertised as supported in hardware which was the
 * goal of that whole exercise. Thus, we can use libpkcs11 but avoid soft token
 * code for symmetric ciphers and digests. See pk11_choose_slots() for more
 * information.
 *
 * This is Solaris specific code, if SOLARIS_HW_SLOT_SELECTION is not defined
 * the code won't be used.
 */
#if defined(__sparcv9) || defined(__x86_64) || defined(__amd64)
static const char pkcs11_kernel[] = "/usr/lib/security/64/pkcs11_kernel.so.1";
#else
static const char pkcs11_kernel[] = "/usr/lib/security/pkcs11_kernel.so.1";
#endif

/*
 * Check hardware capabilities of the machines. The output are two lists,
 * hw_cnids and hw_dnids, that contain hardware mechanisms found in all hardware
 * providers together. They are not sorted and may contain duplicate mechanisms.
 */
static int check_hw_mechanisms(void)
	{
	int i;
	CK_RV rv;
	void *handle;
	CK_C_GetFunctionList p;
	CK_TOKEN_INFO token_info;
	CK_ULONG ulSlotCount = 0;
	int n_cipher = 0, n_digest = 0;
	CK_FUNCTION_LIST_PTR pflist = NULL;
	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
	int *tmp_hw_cnids = NULL, *tmp_hw_dnids = NULL;
	int hw_ctable_size, hw_dtable_size;

	DEBUG_SLOT_SEL("%s: SOLARIS_HW_SLOT_SELECTION code running\n",
	    PK11_DBG);
	/*
	 * Use RTLD_GROUP to limit the pkcs11_kernel provider to its own
	 * symbols, which prevents it from mistakenly accessing C_* functions
	 * from the top-level PKCS#11 library.
	 */
	if ((handle = dlopen(pkcs11_kernel, RTLD_LAZY | RTLD_GROUP)) == NULL)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
		goto err;
		}

	if ((p = (CK_C_GetFunctionList)dlsym(handle,
	    PK11_GET_FUNCTION_LIST)) == NULL)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
		goto err;
		}

	/* get the full function list from the loaded library */
	if (p(&pflist) != CKR_OK)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_DSO_FAILURE);
		goto err;
		}

	rv = pflist->C_Initialize(NULL_PTR);
	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
		{
		PK11err_add_data(PK11_F_CHECK_HW_MECHANISMS,
		    PK11_R_INITIALIZE, rv);
		goto err;
		}

	if (pflist->C_GetSlotList(0, NULL_PTR, &ulSlotCount) != CKR_OK)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
		goto err;
		}

	/* no slots, set the hw mechanism tables as empty */
	if (ulSlotCount == 0)
		{
		DEBUG_SLOT_SEL("%s: no hardware mechanisms found\n", PK11_DBG);
		hw_cnids = OPENSSL_malloc(sizeof (int));
		hw_dnids = OPENSSL_malloc(sizeof (int));
		if (hw_cnids == NULL || hw_dnids == NULL)
			{
			PK11err(PK11_F_CHECK_HW_MECHANISMS,
			    PK11_R_MALLOC_FAILURE);
			return (0);
			}
		/* this means empty tables */
		hw_cnids[0] = NID_undef;
		hw_dnids[0] = NID_undef;
		return (1);
		}

	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
	if (pSlotList == NULL)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
		goto err;
		}

	/* Get the slot list for processing */
	if (pflist->C_GetSlotList(0, pSlotList, &ulSlotCount) != CKR_OK)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_GETSLOTLIST);
		goto err;
		}

	/*
	 * We don't care about duplicate mechanisms in multiple slots and also
	 * reserve one slot for the terminal NID_undef which we use to stop the
	 * search.
	 */
	hw_ctable_size = ulSlotCount * PK11_CIPHER_MAX + 1;
	hw_dtable_size = ulSlotCount * PK11_DIGEST_MAX + 1;
	tmp_hw_cnids = OPENSSL_malloc(hw_ctable_size * sizeof (int));
	tmp_hw_dnids = OPENSSL_malloc(hw_dtable_size * sizeof (int));
	if (tmp_hw_cnids == NULL || tmp_hw_dnids == NULL)
		{
		PK11err(PK11_F_CHECK_HW_MECHANISMS, PK11_R_MALLOC_FAILURE);
		goto err;
		}

	/*
	 * Do not use memset since we should not rely on the fact that NID_undef
	 * is zero now.
	 */
	for (i = 0; i < hw_ctable_size; ++i)
		tmp_hw_cnids[i] = NID_undef;
	for (i = 0; i < hw_dtable_size; ++i)
		tmp_hw_dnids[i] = NID_undef;

	DEBUG_SLOT_SEL("%s: provider: %s\n", PK11_DBG, pkcs11_kernel);
	DEBUG_SLOT_SEL("%s: found %d hardware slots\n", PK11_DBG, ulSlotCount);
	DEBUG_SLOT_SEL("%s: now looking for mechs supported in hw\n",
	    PK11_DBG);

	for (i = 0; i < ulSlotCount; i++)
		{
		if (pflist->C_GetTokenInfo(pSlotList[i], &token_info) != CKR_OK)
			continue;

		DEBUG_SLOT_SEL("%s: token label: %.32s\n", PK11_DBG,
		    token_info.label);

		/*
		 * We are filling the hw mech tables here. Global tables are
		 * still NULL so all mechanisms are put into tmp tables.
		 */
		pk11_find_symmetric_ciphers(pflist, pSlotList[i],
		    &n_cipher, tmp_hw_cnids);
		pk11_find_digests(pflist, pSlotList[i],
		    &n_digest, tmp_hw_dnids);
		}

	/*
	 * Since we are part of a library (libcrypto.so), calling this function
	 * may have side-effects. Also, C_Finalize() is triggered by
	 * dlclose(3C).
	 */
#if 0
	pflist->C_Finalize(NULL);
#endif
	OPENSSL_free(pSlotList);
	(void) dlclose(handle);
	hw_cnids = tmp_hw_cnids;
	hw_dnids = tmp_hw_dnids;

	DEBUG_SLOT_SEL("%s: hw mechs check complete\n", PK11_DBG);
	return (1);

err:
	if (pSlotList != NULL)
		OPENSSL_free(pSlotList);
	if (tmp_hw_cnids != NULL)
		OPENSSL_free(tmp_hw_cnids);
	if (tmp_hw_dnids != NULL)
		OPENSSL_free(tmp_hw_dnids);

	return (0);
	}

/*
 * Check presence of a NID in the table of NIDs unless the mechanism is
 * supported directly in a CPU instruction set. The table may be NULL (i.e.,
 * non-existent).
 */
static int nid_in_table(int nid, int *nid_table)
	{
	int i = 0;

	/*
	 * Special case first. NULL means that we are initializing a new table.
	 */
	if (nid_table == NULL)
		return (1);

	/*
	 * If we have an AES instruction set on SPARC we route everything
	 * through the Crypto Framework (ie., through pkcs11_softtoken in this
	 * case). This is for T4 which has HW instructions for AES, DES, MD5,
	 * SHA1, SHA256, SHA512, MONTMUL, and MPMUL.
	 *
	 * On Intel, if we have AES-NI instruction set we route AES to the
	 * Crypto Framework. Intel CPUs do not have other instruction sets for
	 * HW crypto acceleration so we check the HW NID table for any other
	 * mechanism.
	 */
#if defined(__x86)
	if (hw_aes_instruction_set_present() == 1)
		{
		switch (nid)
			{
			case NID_aes_128_ecb:
			case NID_aes_192_ecb:
			case NID_aes_256_ecb:
			case NID_aes_128_cbc:
			case NID_aes_192_cbc:
			case NID_aes_256_cbc:
				return (1);
			}
		/*
		 * These are variables, cannot be used as case expressions.
		 */
		if (nid == NID_aes_128_ctr ||
		    nid == NID_aes_192_ctr ||
		    nid == NID_aes_256_ctr)
			{
				return (1);
			}
		}
#elif defined(__sparc)
	if (hw_aes_instruction_set_present() == 1)
		return (1);
#endif

	/* The table is never full, there is always at least one NID_undef. */
	while (nid_table[i] != NID_undef)
		{
		if (nid_table[i++] == nid)
			{
			DEBUG_SLOT_SEL(" (NID %d in hw table, idx %d)", nid, i);
			return (1);
			}
		}

	return (0);
	}

/* Do we have an AES instruction set? */
static int
hw_aes_instruction_set_present(void)
	{
	static int present = -1;

	if (present == -1)
		{
		uint_t ui = 0;

		(void) getisax(&ui, 1);

#if defined(__amd64) || defined(__i386)
		present = (ui & AV_386_AES) > 0;
#elif defined(__sparc)
		present = (ui & (AV_SPARC_AES|AV_SPARC_FJAES)) > 0;
#endif
		}

	return (present);
	}

#endif	/* SOLARIS_HW_SLOT_SELECTION */

#endif	/* OPENSSL_NO_HW_PK11 */
#endif	/* OPENSSL_NO_HW */