opensc-sys 0.1.1

FFI bindings to OpenSC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
/*
 * framework-pkcs15.c: PKCS#15 framework and related objects
 *
 * Copyright (C) 2002  Timo Teräs <timo.teras@iki.fi>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "libopensc/log.h"
#include "libopensc/internal.h"
#include "libopensc/asn1.h"
#include "libopensc/cardctl.h"
#include "ui/notify.h"
#include "common/compat_strnlen.h"
#ifdef ENABLE_OPENSSL
#include <openssl/sha.h>
#else
#define SHA_DIGEST_LENGTH	20
#endif

#include "sc-pkcs11.h"
#ifdef USE_PKCS15_INIT
#include "pkcs15init/pkcs15-init.h"
#endif

struct pkcs15_slot_data {
	struct sc_pkcs15_object *auth_obj;
};
#define slot_data(p)		((struct pkcs15_slot_data *) (p))
#define slot_data_auth(p)	(((p) && slot_data(p)) ? slot_data(p)->auth_obj : NULL)
#define slot_data_auth_info(p)	(((p) && slot_data_auth(p))? \
		(struct sc_pkcs15_auth_info *) slot_data_auth(p)->data : NULL)

#define check_attribute_buffer(attr,size)	\
	if (attr->pValue == NULL_PTR) {         \
		attr->ulValueLen = size;        \
		return CKR_OK;                  \
	}                                       \
	if (attr->ulValueLen < size) {		\
		attr->ulValueLen = size;	\
		return CKR_BUFFER_TOO_SMALL;    \
	}                                       \
	attr->ulValueLen = size;

#define MAX_OBJECTS	128
struct pkcs15_fw_data {
	struct sc_pkcs15_card *		p15_card;
	struct pkcs15_any_object *	objects[MAX_OBJECTS];
	unsigned int			num_objects;
	unsigned int			locked;
	unsigned char user_puk[64];
	unsigned int user_puk_len;
};

struct pkcs15_any_object {
	struct sc_pkcs11_object		base;
	unsigned int			refcount;
	size_t				size;
	struct sc_pkcs15_object *	p15_object;
	struct pkcs15_pubkey_object *	related_pubkey;
	struct pkcs15_cert_object *	related_cert;
	struct pkcs15_prkey_object *	related_privkey;
};

struct pkcs15_cert_object {
	struct pkcs15_any_object	base;

	struct sc_pkcs15_cert_info *	cert_info;
	struct sc_pkcs15_cert *		cert_data;
};
#define cert_flags		base.base.flags
#define cert_p15obj		base.p15_object
#define cert_pubkey		base.related_pubkey
#define cert_issuer		base.related_cert
#define cert_prvkey		base.related_privkey

struct pkcs15_prkey_object {
	struct pkcs15_any_object	base;

	struct sc_pkcs15_prkey_info *	prv_info;
	struct sc_pkcs15_pubkey *	pub_data;
};
#define prv_flags		base.base.flags
#define prv_p15obj		base.p15_object
#define prv_pubkey		base.related_pubkey
#define prv_next		base.related_privkey

struct pkcs15_pubkey_object {
	struct pkcs15_any_object	base;

	struct sc_pkcs15_pubkey_info *	pub_info;	/* NULL for key extracted from cert */
	struct sc_pkcs15_pubkey *	pub_data;
};
#define pub_flags		base.base.flags
#define pub_p15obj		base.p15_object
#define pub_genfrom		base.related_cert

#define __p15_type(obj)		(((obj) && (obj)->p15_object)? ((obj)->p15_object->type) : (unsigned int)-1)
#define is_privkey(obj)		((__p15_type(obj) & SC_PKCS15_TYPE_CLASS_MASK) == SC_PKCS15_TYPE_PRKEY)
#define is_pubkey(obj)		((__p15_type(obj) & SC_PKCS15_TYPE_CLASS_MASK) == SC_PKCS15_TYPE_PUBKEY)
#define is_cert(obj)		(__p15_type(obj) == SC_PKCS15_TYPE_CERT_X509)

struct pkcs15_data_object {
	struct pkcs15_any_object	base;

	struct sc_pkcs15_data_info *info;
	struct sc_pkcs15_data *value;
};
#define data_flags		base.base.flags
#define data_p15obj		base.p15_object
#define is_data(obj) (__p15_type(obj) == SC_PKCS15_TYPE_DATA_OBJECT)

struct pkcs15_skey_object {
	struct pkcs15_any_object    base;

	struct sc_pkcs15_skey_info *info;
	struct sc_pkcs15_skey *valueXXXX;
};

#define is_skey(obj) ((__p15_type(obj) & SC_PKCS15_TYPE_CLASS_MASK) == SC_PKCS15_TYPE_SKEY)

#define skey_flags	base.base.flags
#define skey_p15obj	base.p15_object

extern struct sc_pkcs11_object_ops pkcs15_cert_ops;
extern struct sc_pkcs11_object_ops pkcs15_prkey_ops;
extern struct sc_pkcs11_object_ops pkcs15_pubkey_ops;
extern struct sc_pkcs11_object_ops pkcs15_dobj_ops;
extern struct sc_pkcs11_object_ops pkcs15_skey_ops;

const CK_BYTE gostr3410_paramset_A_encoded_oid[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01 };
const unsigned int gostr3410_paramset_A_oid[] = {1, 2, 643, 2, 2, 35, 1, (unsigned int)-1};
const CK_BYTE gostr3410_paramset_B_encoded_oid[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x02 };
const unsigned int gostr3410_paramset_B_oid[] = {1, 2, 643, 2, 2, 35, 2, (unsigned int)-1};
const CK_BYTE gostr3410_paramset_C_encoded_oid[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x03 };
const unsigned int gostr3410_paramset_C_oid[] = {1, 2, 643, 2, 2, 35, 3, (unsigned int)-1};

static const struct {
	const CK_BYTE *encoded_oid;
	const unsigned int encoded_oid_size;
	const unsigned int *oid;
	const unsigned int oid_size;
	unsigned char oid_id;
} gostr3410_param_oid [] = {
	{ &gostr3410_paramset_A_encoded_oid[0],
		sizeof(gostr3410_paramset_A_encoded_oid),
		&gostr3410_paramset_A_oid[0],
		sizeof(gostr3410_paramset_A_oid),
		SC_PKCS15_PARAMSET_GOSTR3410_A },
	{ &gostr3410_paramset_B_encoded_oid[0],
		sizeof(gostr3410_paramset_B_encoded_oid),
		&gostr3410_paramset_B_oid[0],
		sizeof(gostr3410_paramset_B_oid),
		SC_PKCS15_PARAMSET_GOSTR3410_B },
	{ &gostr3410_paramset_C_encoded_oid[0],
		sizeof(gostr3410_paramset_C_encoded_oid),
		&gostr3410_paramset_C_oid[0],
		sizeof(gostr3410_paramset_C_oid),
		SC_PKCS15_PARAMSET_GOSTR3410_C }
};

const CK_BYTE gostr3411_94_cryptopro_paramset_encoded_oid[] = { 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1e, 0x01 };
const unsigned int gostr3411_94_cryptopro_paramset_oid[] = {1, 2, 643, 2, 2, 30, 1, (unsigned int)-1};

#ifdef USE_PKCS15_INIT
static const struct {
	const CK_BYTE *encoded_oid;
	const unsigned int encoded_oid_size;
	const unsigned int *oid;
	const unsigned int oid_size;
} gostr3410_hash_param_oid [] = {
	{ &gostr3411_94_cryptopro_paramset_encoded_oid[0],
		sizeof(gostr3411_94_cryptopro_paramset_encoded_oid),
		&gostr3411_94_cryptopro_paramset_oid[0],
		sizeof(gostr3411_94_cryptopro_paramset_oid)}
};
#endif

static int	__pkcs15_release_object(struct pkcs15_any_object *);
static CK_RV	register_mechanisms(struct sc_pkcs11_card *p11card);
static CK_RV	get_public_exponent(struct sc_pkcs15_pubkey *,
					CK_ATTRIBUTE_PTR);
static CK_RV	get_modulus(struct sc_pkcs15_pubkey *,
					CK_ATTRIBUTE_PTR);
static CK_RV	get_modulus_bits(struct sc_pkcs15_pubkey *,
					CK_ATTRIBUTE_PTR);
static CK_RV	get_usage_bit(unsigned int usage, CK_ATTRIBUTE_PTR attr);
static CK_RV	get_gostr3410_params(const u8 *, size_t, CK_ATTRIBUTE_PTR);
static CK_RV	get_ec_pubkey_point(struct sc_pkcs15_pubkey *, CK_ATTRIBUTE_PTR);
static CK_RV	get_ec_pubkey_params(struct sc_pkcs15_pubkey *, CK_ATTRIBUTE_PTR);
static int	lock_card(struct pkcs15_fw_data *);
static int	unlock_card(struct pkcs15_fw_data *);
static int	reselect_app_df(sc_pkcs15_card_t *p15card);

#ifdef USE_PKCS15_INIT
static CK_RV	set_gost3410_params(struct sc_pkcs15init_prkeyargs *,
			struct sc_pkcs15init_pubkeyargs *,
			CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG);
static CK_RV	pkcs15_create_slot(struct sc_pkcs11_card *p11card, struct pkcs15_fw_data *fw_data,
			struct sc_pkcs15_object *auth, struct sc_app_info *app,
			struct sc_pkcs11_slot **out);
static int pkcs11_get_pin_callback(struct sc_profile *profile, int id,
		const struct sc_pkcs15_auth_info *info, const char *label,
		unsigned char *pinbuf, size_t *pinsize);

static struct sc_pkcs15init_callbacks pkcs15init_callbacks = {
	pkcs11_get_pin_callback,       /* get_pin() */
	NULL
};
static char *pkcs15init_sopin = NULL;
static size_t pkcs15init_sopin_len = 0;

static int pkcs11_get_pin_callback(struct sc_profile *profile, int id,
		const struct sc_pkcs15_auth_info *info, const char *label,
		unsigned char *pinbuf, size_t *pinsize)
{
	char	*secret = NULL;
	size_t	len = 0;

	if (info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
		return SC_ERROR_NOT_SUPPORTED;

	sc_log(context, "pkcs11_get_pin_callback() auth-method %X", info->auth_method);
	if (info->auth_method == SC_AC_CHV)   {
		unsigned int flags = info->attrs.pin.flags;

		sc_log(context, "pkcs11_get_pin_callback() PIN flags %X", flags);
		if ((flags & SC_PKCS15_PIN_FLAG_SO_PIN) && !(flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))    {
			if (pkcs15init_sopin_len)
				secret = pkcs15init_sopin;
		}
	}
	if (secret)
		len = strlen(secret);

	sc_log(context, "pkcs11_get_pin_callback() secret '%s'", secret ? secret : "<null>");

	if (!secret)
		return SC_ERROR_OBJECT_NOT_FOUND;
	if (len > *pinsize)
		return SC_ERROR_BUFFER_TOO_SMALL;
	memcpy(pinbuf, secret, len + 1);
	*pinsize = len;
	return 0;
}
#endif

/* Returns WF data corresponding to the given application or,
 * if application info is not supplied, returns first available WF data. */
static struct pkcs15_fw_data *
get_fw_data(struct sc_pkcs11_card *p11card, struct sc_app_info *app_info, int *out_idx)
{
	struct pkcs15_fw_data *out = NULL;
	int idx;

	if (!p11card)
		return NULL;
	for (idx=0; p11card && idx < SC_PKCS11_FRAMEWORK_DATA_MAX_NUM; idx++)   {
		struct pkcs15_fw_data *fw_data = (struct pkcs15_fw_data *) p11card->fws_data[idx];
		struct sc_file *file_app = NULL;

		if (!fw_data || !fw_data->p15_card)
			continue;

		file_app = fw_data->p15_card->file_app;
		if (app_info && file_app)   {
			if (file_app->path.len != app_info->path.len)
				continue;
			if (file_app->path.aid.len != app_info->path.aid.len)
				continue;
			if (memcmp(file_app->path.aid.value, app_info->path.aid.value, app_info->path.aid.len))
				continue;
			if (memcmp(file_app->path.value, app_info->path.value, app_info->path.len))
				continue;
		}

		out = fw_data;
		if (out_idx)
			*out_idx = idx;
		break;
	}

	return out;
}

/* PKCS#15 Framework */
static CK_RV
pkcs15_bind(struct sc_pkcs11_card *p11card, struct sc_app_info *app_info)
{
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_aid *aid = app_info ? &app_info->aid : NULL;
	int rc, idx;
	CK_RV ck_rv;

	sc_log(context, "Bind PKCS#15 '%s' application", app_info ? app_info->label : "<anonymous>");
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	for (idx=0; idx<SC_PKCS11_FRAMEWORK_DATA_MAX_NUM; idx++)
		if (!p11card->fws_data[idx])
			break;
	if (idx == SC_PKCS11_FRAMEWORK_DATA_MAX_NUM)
		return CKR_USER_TOO_MANY_TYPES;

	if (!(fw_data = calloc(1, sizeof(*fw_data))))
		return CKR_HOST_MEMORY;
	p11card->fws_data[idx] = fw_data;

	rc = sc_pkcs15_bind(p11card->card, aid, &fw_data->p15_card);
	if (rc != SC_SUCCESS) {
		sc_log(context, "sc_pkcs15_bind failed: %d", rc);
		return sc_to_cryptoki_error(rc, NULL);
	}

	/* Mechanisms are registered globally per card. Checking
	 * p11card->nmechanisms avoids registering the same mechanisms twice for a
	 * card with multiple slots. */
	if (!p11card->nmechanisms) {
		ck_rv = register_mechanisms(p11card);
		if (ck_rv != CKR_OK) {
			sc_log(context, "cannot register mechanisms; CKR 0x%lX",
			       ck_rv);
			return ck_rv;
		}
	}

	if (idx == 0) {
		/* send a notification only for the first application that's bound */
		sc_notify_id(p11card->card->ctx, &p11card->reader->atr, fw_data->p15_card,
				NOTIFY_CARD_INSERTED);
	}

	return CKR_OK;
}


static CK_RV
pkcs15_unbind(struct sc_pkcs11_card *p11card)
{
	unsigned int i, idx;
	int rv = SC_SUCCESS;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	for (idx=0; p11card && idx<SC_PKCS11_FRAMEWORK_DATA_MAX_NUM; idx++)   {
		struct pkcs15_fw_data *fw_data = (struct pkcs15_fw_data *) p11card->fws_data[idx];

		if (!fw_data)
			break;
		for (i = 0; i < fw_data->num_objects; i++) {
			struct pkcs15_any_object *obj = fw_data->objects[i];

			/* use object specific release method if existing */
			if (obj->base.ops && obj->base.ops->release)
				obj->base.ops->release(obj);
			else
				__pkcs15_release_object(obj);
		}

		unlock_card(fw_data);

		if (fw_data->p15_card && fw_data->p15_card->card) {
			if (idx == 0) {
				int rc = sc_detect_card_presence(fw_data->p15_card->card->reader);
				if (rc <= 0 || rc & SC_READER_CARD_CHANGED) {
					/* send a notification only if the card was removed/changed
					 * and only for the first application that's unbound */
					sc_notify_id(fw_data->p15_card->card->ctx,
							&fw_data->p15_card->card->reader->atr,
							fw_data->p15_card,
							NOTIFY_CARD_REMOVED);
				}
			}
			rv = sc_pkcs15_unbind(fw_data->p15_card);
		}
		fw_data->p15_card = NULL;

		free(fw_data);
		p11card->fws_data[idx] = NULL;
	}

	return sc_to_cryptoki_error(rv, NULL);
}


static void
pkcs15_init_token_info(struct sc_pkcs15_card *p15card, CK_TOKEN_INFO_PTR pToken)
{
	scconf_block *conf_block = NULL;
	char *model = NULL;

	conf_block = sc_get_conf_block(p15card->card->ctx, "framework", "pkcs15", 1);
	if (conf_block && p15card->file_app)   {
		scconf_block **blocks = NULL;
		char str_path[SC_MAX_AID_STRING_SIZE];

		memset(str_path, 0, sizeof(str_path));
		sc_bin_to_hex(p15card->file_app->path.value, p15card->file_app->path.len, str_path, sizeof(str_path), 0);
		blocks = scconf_find_blocks(p15card->card->ctx->conf, conf_block, "application", str_path);
		if (blocks)   {
			if (blocks[0])
				model = (char *)scconf_get_str(blocks[0], "model", NULL);
			free(blocks);
		}
	}

	if (model)
		strcpy_bp(pToken->model, model, sizeof(pToken->model));
	else if (p15card->flags & SC_PKCS15_CARD_FLAG_EMULATED)
		strcpy_bp(pToken->model, "PKCS#15 emulated", sizeof(pToken->model));
	else
		strcpy_bp(pToken->model, "PKCS#15", sizeof(pToken->model));

	if (p15card->tokeninfo) {
		strcpy_bp(pToken->manufacturerID, p15card->tokeninfo->manufacturer_id, 32);

		/* Take the last 16 chars of the serial number (if the are more than 16).
		 * _Assuming_ that the serial number is a Big Endian counter, this
		 * will assure that the serial within each type of card will be
		 * unique in pkcs11 (at least for the first 8^16 cards :-) */
		if (p15card->tokeninfo->serial_number != NULL) {
			size_t sn_start = strlen(p15card->tokeninfo->serial_number);

			if (sn_start <= 16)
				sn_start = 0;
			else
				sn_start -= 16;

			strcpy_bp(pToken->serialNumber, p15card->tokeninfo->serial_number + sn_start, 16);
		}
	}

	pToken->ulMaxSessionCount = CK_EFFECTIVELY_INFINITE;
	pToken->ulSessionCount = 0; /* FIXME */
	pToken->ulMaxRwSessionCount = CK_EFFECTIVELY_INFINITE;
	pToken->ulRwSessionCount = 0; /* FIXME */
	pToken->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
	pToken->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
	pToken->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
	pToken->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
	pToken->hardwareVersion.major = p15card->card->version.hw_major;
	pToken->hardwareVersion.minor = p15card->card->version.hw_minor;
	pToken->firmwareVersion.major = p15card->card->version.fw_major;
	pToken->firmwareVersion.minor = p15card->card->version.fw_minor;
}

#ifdef USE_PKCS15_INIT
static char *
set_cka_label(CK_ATTRIBUTE_PTR attr, char *label)
{
	char *l = (char *)attr->pValue;
	unsigned long len = attr->ulValueLen;

	if (len >= SC_PKCS15_MAX_LABEL_SIZE)
		len = SC_PKCS15_MAX_LABEL_SIZE-1;
	memcpy(label, l, len);
	label[len] = '\0';
	return label;
}
#endif

static int
__pkcs15_create_object(struct pkcs15_fw_data *fw_data,
		       struct pkcs15_any_object **result,
		       struct sc_pkcs15_object *p15_object,
		       struct sc_pkcs11_object_ops *ops,
		       size_t size)
{
	struct pkcs15_any_object *obj;

	if (fw_data->num_objects >= MAX_OBJECTS)
		return SC_ERROR_TOO_MANY_OBJECTS;

	if (!(obj = calloc(1, size)))
		return SC_ERROR_OUT_OF_MEMORY;

	fw_data->objects[fw_data->num_objects++] = obj;

	obj->base.ops = ops;
	obj->p15_object = p15_object;
	obj->refcount = 1;
	obj->size = size;

	*result = obj;
	return 0;
}

static int
__pkcs15_release_object(struct pkcs15_any_object *obj)
{
	if (--(obj->refcount) != 0)
		return obj->refcount;

	sc_mem_clear(obj, obj->size);
	free(obj);

	return 0;
}

#ifdef USE_PKCS15_INIT
static int
__pkcs15_delete_object(struct pkcs15_fw_data *fw_data, struct pkcs15_any_object *obj)
{
	unsigned int i;

	if (fw_data->num_objects == 0)
		return SC_ERROR_INTERNAL;

	for (i = 0; i < fw_data->num_objects; ++i)   {
		if (fw_data->objects[i] == obj) {
			fw_data->objects[i] = fw_data->objects[--fw_data->num_objects];
			if (__pkcs15_release_object(obj) > 0)
				return SC_ERROR_INTERNAL;
			return SC_SUCCESS;
		}
	}
	return SC_ERROR_OBJECT_NOT_FOUND;
}
#endif

CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo)
{
	struct sc_pkcs11_slot *slot;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_card *p15card = NULL;
	struct sc_pkcs15_object *auth;
	struct sc_pkcs15_auth_info *pin_info;
	CK_RV rv;

	sc_log(context, "C_GetTokenInfo(%lx)", slotID);
	if (pInfo == NULL_PTR)
		return CKR_ARGUMENTS_BAD;

	rv = sc_pkcs11_lock();
	if (rv != CKR_OK)
		return rv;

	rv = slot_get_token(slotID, &slot);
	if (rv != CKR_OK)   {
		sc_log(context, "C_GetTokenInfo() get token: rv 0x%lX", rv);
		goto out;
	}

	if (slot->p11card == NULL) {
		rv = CKR_TOKEN_NOT_PRESENT;
		goto out;
	}

	fw_data = (struct pkcs15_fw_data *) slot->p11card->fws_data[slot->fw_data_idx];
	if (!fw_data) {
		rv = sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetTokenInfo");
		goto out;
	}
	p15card = fw_data->p15_card;

	/* User PIN flags are cleared before re-calculation */
	slot->token_info.flags &= ~(CKF_USER_PIN_COUNT_LOW|CKF_USER_PIN_FINAL_TRY|CKF_USER_PIN_LOCKED);
	auth = slot_data_auth(slot->fw_data);
	sc_log(context,
		"C_GetTokenInfo() auth. object %p, token-info flags 0x%lX", auth,
		slot->token_info.flags);
	if (auth) {
		pin_info = (struct sc_pkcs15_auth_info*) auth->data;

		sc_pkcs15_get_pin_info(p15card, auth);

		if (pin_info->tries_left >= 0) {
			if (pin_info->tries_left == 1 || pin_info->max_tries == 1)
				slot->token_info.flags |= CKF_USER_PIN_FINAL_TRY;
			else if (pin_info->tries_left == 0)
				slot->token_info.flags |= CKF_USER_PIN_LOCKED;
			else if (pin_info->max_tries > 1 && pin_info->tries_left < pin_info->max_tries)
				slot->token_info.flags |= CKF_USER_PIN_COUNT_LOW;
		}
	}
	memcpy(pInfo, &slot->token_info, sizeof(CK_TOKEN_INFO));
out:
	sc_pkcs11_unlock();
	sc_log(context, "C_GetTokenInfo(%lx) returns %s", slotID, lookup_enum(RV_T, rv));
	return rv;
}


static int
public_key_created(struct pkcs15_fw_data *fw_data, const struct sc_pkcs15_id *id,
		struct pkcs15_any_object **obj2)
{
	size_t ii;

	for(ii=0; ii<fw_data->num_objects; ii++) {
		struct pkcs15_any_object *any_object = fw_data->objects[ii];
		struct sc_pkcs15_object *p15_object = any_object->p15_object;

		if (!p15_object)
			continue;

		if ((p15_object->type & SC_PKCS15_TYPE_CLASS_MASK) != SC_PKCS15_TYPE_PUBKEY)
			continue;

		if (sc_pkcs15_compare_id(id, &((struct sc_pkcs15_pubkey_info *)p15_object->data)->id))   {
			if (obj2)
				*obj2 = any_object;
			return SC_SUCCESS;
		}
	}

	return SC_ERROR_OBJECT_NOT_FOUND;
}

static void
pkcs15_cert_extract_label(struct pkcs15_cert_object *cert)
{
	if (!cert || !cert->cert_p15obj || !cert->cert_data)
		return;

	sc_log(context, "pkcs15_cert_extract_label() called. Current label: %s", cert->cert_p15obj->label);

	/* if we didn't get a label, set one based on the CN */
	if (*cert->cert_p15obj->label == '\0') { /* can't be NULL -- static array */
		static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
		u8 *cn_name = NULL;
		size_t cn_len = 0;
		int rv = sc_pkcs15_get_name_from_dn(context,
			cert->cert_data->subject, cert->cert_data->subject_len,
			&cn_oid, &cn_name, &cn_len);
		if (rv == SC_SUCCESS) {
			sc_log(context, "pkcs15_cert_extract_label(): Name from DN is %.*s",
					(unsigned int) cn_len, cn_name);
			cn_len = MIN(cn_len, SC_PKCS15_MAX_LABEL_SIZE-1);
			memcpy(cert->cert_p15obj->label, cn_name, cn_len);
			cert->cert_p15obj->label[cn_len] = '\0';
		}
		free(cn_name);
	}
}

static int
__pkcs15_create_cert_object(struct pkcs15_fw_data *fw_data, struct sc_pkcs15_object *cert,
		struct pkcs15_any_object **cert_object)
{
	struct sc_pkcs15_cert_info *p15_info = NULL;
	struct sc_pkcs15_cert *p15_cert = NULL;
	struct pkcs15_cert_object *object = NULL;
	struct pkcs15_pubkey_object *obj2 = NULL;
	int rv;

	p15_info = (struct sc_pkcs15_cert_info *) cert->data;

	if (cert->flags & SC_PKCS15_CO_FLAG_PRIVATE)  {	/* is the cert private? */
		p15_cert = NULL;			/* will read cert when needed */
	}
	else    {
		rv = sc_pkcs15_read_certificate(fw_data->p15_card, p15_info, &p15_cert);
		if (rv < 0)
			return rv;
	}

	/* Certificate object */
	rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &object,
			cert, &pkcs15_cert_ops, sizeof(struct pkcs15_cert_object));
	if (rv < 0) {
		if (p15_cert != NULL)
			sc_pkcs15_free_certificate(p15_cert);
		return rv;
	}

	object->cert_info = p15_info;
	object->cert_data = p15_cert;

	/* Corresponding public key */
	rv = public_key_created(fw_data, &p15_info->id, (struct pkcs15_any_object **) &obj2);
	if (rv != SC_SUCCESS)
		rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &obj2,
				NULL, &pkcs15_pubkey_ops, sizeof(struct pkcs15_pubkey_object));
	if (rv < 0)
		return rv;

	if (p15_cert) {
		 /* make a copy of public key from the cert */
		if (!obj2->pub_data)
			rv = sc_pkcs15_pubkey_from_cert(context, &p15_cert->data, &obj2->pub_data);
		if (rv < 0)
			return rv;
	}

	obj2->pub_genfrom = object;
	object->cert_pubkey = obj2;

	/* Find missing labels for certificate */
	pkcs15_cert_extract_label(object);

	if (cert_object != NULL)
		*cert_object = (struct pkcs15_any_object *) object;

	return 0;
}


static int
__pkcs15_create_pubkey_object(struct pkcs15_fw_data *fw_data,
	struct sc_pkcs15_object *pubkey, struct pkcs15_any_object **pubkey_object)
{
	struct pkcs15_pubkey_object *object = NULL;
	struct sc_pkcs15_pubkey *p15_key = NULL;
	int rv;

	/* Read public key from card */
	/* Attempt to read pubkey from card or file.
	 * During initialization process, the key may have been created
	 * and saved as a file before the certificate has been created.
	 */
	if (pubkey->flags & SC_PKCS15_CO_FLAG_PRIVATE)   {	/* is the key private? */
		sc_log(context, "No pubkey");
		p15_key = NULL;					/* will read key when needed */
	}
	else {
		/* if emulation already created pubkey use it */
		if (pubkey->emulated && (fw_data->p15_card->flags & SC_PKCS15_CARD_FLAG_EMULATED)) {
			sc_log(context, "Use emulated pubkey");
			p15_key = (struct sc_pkcs15_pubkey *) pubkey->emulated;
		}
		else {
			sc_log(context, "Get pubkey from PKCS#15 object");
			rv = sc_pkcs15_read_pubkey(fw_data->p15_card, pubkey, &p15_key);
			if (rv < 0)
				 p15_key = NULL;
		}
	}

	/* Public key object */
	rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &object,
			pubkey, &pkcs15_pubkey_ops, sizeof(struct pkcs15_pubkey_object));
	if (rv >= 0) {
		object->pub_info = (struct sc_pkcs15_pubkey_info *) pubkey->data;
		object->pub_data = p15_key;
		if (p15_key && object->pub_info->modulus_length == 0 && p15_key->algorithm == SC_ALGORITHM_RSA)
			object->pub_info->modulus_length = 8 * p15_key->u.rsa.modulus.len;
	} else if (!(pubkey->emulated && (fw_data->p15_card->flags & SC_PKCS15_CARD_FLAG_EMULATED))) {
		sc_pkcs15_free_pubkey(p15_key);
	}
	if (object && object->pub_data) {
		if ((object->pub_data->alg_id)&&(object->pub_data->algorithm == SC_ALGORITHM_GOSTR3410))
			object->pub_data->alg_id->params = &((object->pub_data->u).gostr3410.params);
	}
	if (pubkey_object != NULL)
		*pubkey_object = (struct pkcs15_any_object *) object;

	return rv;
}


static int
__pkcs15_create_prkey_object(struct pkcs15_fw_data *fw_data,
	struct sc_pkcs15_object *prkey, struct pkcs15_any_object **prkey_object)
{
	struct pkcs15_prkey_object *object = NULL;
	int rv;

	rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &object,
			prkey, &pkcs15_prkey_ops, sizeof(struct pkcs15_prkey_object));
	if (rv >= 0)
		object->prv_info = (struct sc_pkcs15_prkey_info *) prkey->data;

	if (prkey_object != NULL)
		*prkey_object = (struct pkcs15_any_object *) object;

	return rv;
}


static int
__pkcs15_create_data_object(struct pkcs15_fw_data *fw_data,
		struct sc_pkcs15_object *object, struct pkcs15_any_object **data_object)
{
	struct pkcs15_data_object *dobj = NULL;
	int rv;

	rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &dobj,
			object, &pkcs15_dobj_ops, sizeof(struct pkcs15_data_object));
	if (rv >= 0)   {
		dobj->info = (struct sc_pkcs15_data_info *) object->data;
		dobj->value = NULL;
	}

	if (data_object != NULL)
		*data_object = (struct pkcs15_any_object *) dobj;

	return rv;
}


static int
__pkcs15_create_secret_key_object(struct pkcs15_fw_data *fw_data,
		struct sc_pkcs15_object *object, struct pkcs15_any_object **skey_object)
{
	struct pkcs15_skey_object *skey = NULL;
	int rv;

	rv = __pkcs15_create_object(fw_data, (struct pkcs15_any_object **) &skey,
			object, &pkcs15_skey_ops, sizeof(struct pkcs15_skey_object));
	if (rv >= 0)
		skey->info = (struct sc_pkcs15_skey_info *) object->data;

	if (skey_object != NULL)
		*skey_object = (struct pkcs15_any_object *) skey;

	return rv;
}


static int
pkcs15_create_pkcs11_objects(struct pkcs15_fw_data *fw_data, int p15_type, const char *name,
		int (*create)(struct pkcs15_fw_data *, struct sc_pkcs15_object *,
			struct pkcs15_any_object **any_object))
{
	struct sc_pkcs15_object *p15_object[MAX_OBJECTS];
	int i, count, rv;

	rv = count = sc_pkcs15_get_objects(fw_data->p15_card, p15_type, p15_object, MAX_OBJECTS);
	if (rv >= 0)
		sc_log(context, "Found %d %s%s", count, name, (count == 1)? "" : "s");

	for (i = 0; rv >= 0 && i < count; i++)
		rv = create(fw_data, p15_object[i], NULL);

	return count;
}


static void
__pkcs15_prkey_bind_related(struct pkcs15_fw_data *fw_data, struct pkcs15_prkey_object *pk)
{
	struct sc_pkcs15_id *id = &pk->prv_info->id;
	unsigned int i;

	sc_log(context, "Object is a private key and has id %s", sc_pkcs15_print_id(id));

	for (i = 0; i < fw_data->num_objects; i++) {
		struct pkcs15_any_object *obj = fw_data->objects[i];

		if (obj->base.flags & SC_PKCS11_OBJECT_HIDDEN)
			continue;
		if (is_privkey(obj) && obj != (struct pkcs15_any_object *) pk) {
			/* merge private keys with the same ID and
			 * different usage bits */
			struct pkcs15_prkey_object *other, **pp;

			other = (struct pkcs15_prkey_object *) obj;
			if (sc_pkcs15_compare_id(&other->prv_info->id, id)) {
				obj->base.flags |= SC_PKCS11_OBJECT_HIDDEN;
				for (pp = &pk->prv_next; *pp; pp = &(*pp)->prv_next)
					;
				*pp = (struct pkcs15_prkey_object *) obj;
			}
		}
		else if (is_pubkey(obj) && !pk->prv_pubkey) {
			struct pkcs15_pubkey_object *pubkey;

			pubkey = (struct pkcs15_pubkey_object *) obj;
			if (sc_pkcs15_compare_id(&pubkey->pub_info->id, id)) {
				sc_log(context, "Associating object %d as public key", i);
				pk->prv_pubkey = pubkey;
				if (pubkey->pub_data) {
					sc_pkcs15_dup_pubkey(context, pubkey->pub_data, &pk->pub_data);
					if (pk->prv_info->modulus_length == 0)
						pk->prv_info->modulus_length = pubkey->pub_info->modulus_length;
				}
			}
		}
	}
}


static void
__pkcs15_cert_bind_related(struct pkcs15_fw_data *fw_data, struct pkcs15_cert_object *cert)
{
	struct sc_pkcs15_cert *c1 = cert->cert_data;
	struct sc_pkcs15_id *id = &cert->cert_info->id;
	unsigned int i;

	sc_log(context, "Object is a certificate and has id %s", sc_pkcs15_print_id(id));

	/* Loop over all objects to see if we find the certificate of
	 * the issuer and the associated private key */
	for (i = 0; i < fw_data->num_objects; i++) {
		struct pkcs15_any_object *obj = fw_data->objects[i];

		if (is_cert(obj) && obj != (struct pkcs15_any_object *) cert) {
			struct pkcs15_cert_object *cert2;
			struct sc_pkcs15_cert *c2;

			cert2 = (struct pkcs15_cert_object *) obj;
			c2 = cert2->cert_data;

			if (!c1 || !c2 || !c1->issuer_len || !c2->subject_len)
				continue;
			if (c1->issuer_len == c2->subject_len
			 && !memcmp(c1->issuer, c2->subject, c1->issuer_len)) {
				sc_log(context, "Associating object %d (id %s) as issuer",
						i, sc_pkcs15_print_id(&cert2->cert_info->id));
				cert->cert_issuer = (struct pkcs15_cert_object *) obj;
				return;
			}
		} else
		if (is_privkey(obj) && !cert->cert_prvkey) {
			struct pkcs15_prkey_object *pk;

			pk = (struct pkcs15_prkey_object *) obj;
			if (sc_pkcs15_compare_id(&pk->prv_info->id, id)) {
				sc_log(context, "Associating object %d as private key", i);
				cert->cert_prvkey = pk;
			}
		}
	}
}

static void
pkcs15_bind_related_objects(struct pkcs15_fw_data *fw_data)
{
	unsigned int i;

	/* Loop over all private keys and attached related certificate
	 * and/or public key
	 */
	for (i = 0; i < fw_data->num_objects; i++) {
		struct pkcs15_any_object *obj = fw_data->objects[i];

		if (obj->base.flags & SC_PKCS11_OBJECT_HIDDEN)
			continue;

		sc_log(context, "Looking for objects related to object %d", i);
		if (is_privkey(obj))
			__pkcs15_prkey_bind_related(fw_data, (struct pkcs15_prkey_object *) obj);
		else if (is_cert(obj))
			__pkcs15_cert_bind_related(fw_data, (struct pkcs15_cert_object *) obj);
	}
}


/* We deferred reading of the cert until needed, as it may be
 * a private object, so we must wait till login to read  */
static int
check_cert_data_read(struct pkcs15_fw_data *fw_data, struct pkcs15_cert_object *cert)
{
	struct pkcs15_pubkey_object *obj2;
	int rv;

	if (!cert)
		return SC_ERROR_OBJECT_NOT_FOUND;

	if (cert->cert_data)
		return 0;
	rv = sc_pkcs15_read_certificate(fw_data->p15_card, cert->cert_info, &cert->cert_data);
	if (rv < 0)
		return rv;

	obj2 = cert->cert_pubkey;
	/* make a copy of public key from the cert data */
	if (!obj2->pub_data)
		rv = sc_pkcs15_pubkey_from_cert(context, &cert->cert_data->data, &obj2->pub_data);

	/* Find missing labels for certificate */
	pkcs15_cert_extract_label(cert);

	/* now that we have the cert and pub key, lets see if we can bind anything else */
	pkcs15_bind_related_objects(fw_data);

	return rv;
}


static void
pkcs15_add_object(struct sc_pkcs11_slot *slot, struct pkcs15_any_object *obj,
		  CK_OBJECT_HANDLE_PTR pHandle)
{
	unsigned int i;
	struct pkcs15_fw_data *card_fw_data;
	CK_OBJECT_HANDLE handle =
		(CK_OBJECT_HANDLE)(uintptr_t)obj; /* cast pointer to long, will truncate on Win64 */

	if (obj == NULL || slot == NULL)
		return;
	if (obj->base.flags & (SC_PKCS11_OBJECT_HIDDEN | SC_PKCS11_OBJECT_RECURS))
		return;

	if (list_contains(&slot->objects, obj))
		return;

	if (pHandle != NULL)
		*pHandle = handle;

	list_append(&slot->objects, obj);
	sc_log(context, "Slot:%lX Setting object handle of 0x%lx to 0x%lx",
		   slot->id, obj->base.handle, handle);
	obj->base.handle = handle;
	obj->base.flags |= SC_PKCS11_OBJECT_SEEN;
	obj->refcount++;

	/* Add related objects
	 * XXX prevent infinite recursion when a card specifies two certificates
	 * referring to each other.
	 */
	obj->base.flags |= SC_PKCS11_OBJECT_RECURS;

	switch (__p15_type(obj)) {
	case SC_PKCS15_TYPE_PRKEY_RSA:
	case SC_PKCS15_TYPE_PRKEY_GOSTR3410:
	case SC_PKCS15_TYPE_PRKEY_EC:
		if (slot->p11card != NULL) {
			pkcs15_add_object(slot, (struct pkcs15_any_object *) obj->related_pubkey, NULL);
			if (!slot->p11card)
				return;
			card_fw_data = (struct pkcs15_fw_data *) slot->p11card->fws_data[slot->fw_data_idx];
			for (i = 0; i < card_fw_data->num_objects; i++) {
				struct pkcs15_any_object *obj2 = card_fw_data->objects[i];
				struct pkcs15_cert_object *cert;

				if (!is_cert(obj2))
					continue;

				cert = (struct pkcs15_cert_object*) obj2;

				if ((struct pkcs15_any_object*)(cert->cert_prvkey) != obj)
					continue;

				pkcs15_add_object(slot, obj2, NULL);
			}
		}
		break;
	case SC_PKCS15_TYPE_CERT_X509:
		pkcs15_add_object(slot, (struct pkcs15_any_object *) obj->related_pubkey, NULL);
		pkcs15_add_object(slot, (struct pkcs15_any_object *) obj->related_cert, NULL);
		break;
	}

	obj->base.flags &= ~SC_PKCS11_OBJECT_RECURS;
}


static void
pkcs15_init_slot(struct sc_pkcs15_card *p15card, struct sc_pkcs11_slot *slot,
		struct sc_pkcs15_object *auth, struct sc_app_info *app_info)
{
	struct pkcs15_slot_data *fw_data;
	struct sc_pkcs15_auth_info *pin_info = NULL;
	int write_protected;
	scconf_block *atrblock;

	sc_log(context, "Called");
	pkcs15_init_token_info(p15card, &slot->token_info);
	slot->token_info.flags |= CKF_TOKEN_INITIALIZED;
	if (auth != NULL)
		slot->token_info.flags |= CKF_USER_PIN_INITIALIZED;

	if ((p15card->card->reader->capabilities & SC_READER_CAP_PIN_PAD) || (p15card->card->caps & SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH))
		slot->token_info.flags |= CKF_PROTECTED_AUTHENTICATION_PATH;

	if (p15card->card->caps & SC_CARD_CAP_RNG && p15card->card->ops->get_challenge != NULL)
		slot->token_info.flags |= CKF_RNG;

	if (p15card->tokeninfo && p15card->tokeninfo->flags & SC_PKCS15_TOKEN_READONLY) {
		write_protected = 1;
	} else {
		write_protected = 0;
	}
	atrblock = _sc_match_atr_block(p15card->card->ctx, NULL, &p15card->card->atr);
	if (atrblock) {
		write_protected = scconf_get_bool(atrblock, "read_only", write_protected);
	}
	if (write_protected) {
		slot->token_info.flags |= CKF_WRITE_PROTECTED;
	}

	slot->fw_data = fw_data = calloc(1, sizeof(*fw_data));
	if (!fw_data) {
		return;
	}
	fw_data->auth_obj = auth;

	if (auth != NULL) {
		pin_info = (struct sc_pkcs15_auth_info*) auth->data;

		if (pin_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)   {
			pin_info = NULL;
		}
		else   {
			size_t pin_len = 0;
			if (auth->label[0] && strncmp(auth->label, "PIN", 4) != 0)
				pin_len = strlen(auth->label);

			if (pin_len) {
				size_t tokeninfo_len = 0;
				if (p15card->tokeninfo)
					tokeninfo_len = strlen(p15card->tokeninfo->label);
				/* Print the possibly truncated token label with at least 4
				 * characters followed by the PIN label in paranthesis */
				if (tokeninfo_len == 0
						|| pin_len + strlen("L... ()") > 32) {
					/* There is no token label or it doesn't fit,
					 * print only PIN label */
					strcpy_bp(slot->token_info.label, auth->label, 32);
				} else {
					size_t max_tokeninfo_len = MIN(tokeninfo_len,
							32 - pin_len - strlen(" ()"));
					strcpy_bp(slot->token_info.label,
							p15card->tokeninfo->label,
							max_tokeninfo_len);
					slot->token_info.label[max_tokeninfo_len]           = ' ';
					slot->token_info.label[max_tokeninfo_len+1]         = '(';
					slot->token_info.label[max_tokeninfo_len+2+pin_len] = ')';
					strcpy_bp(slot->token_info.label+max_tokeninfo_len+2,
							auth->label, pin_len);
				}
			} else {
				/* PIN label is empty or just says non-useful "PIN",
				 * print only token label */
				strcpy_bp(slot->token_info.label,
						p15card->tokeninfo ? p15card->tokeninfo->label : "",
						32);
			}
			slot->token_info.flags |= CKF_LOGIN_REQUIRED;
		}
	}

	if (pin_info) {
		slot->token_info.ulMaxPinLen = pin_info->attrs.pin.max_length;
		slot->token_info.ulMinPinLen = pin_info->attrs.pin.min_length;
	}
	else {
		/* choose reasonable defaults */
		slot->token_info.ulMaxPinLen = 8;
		slot->token_info.ulMinPinLen = 4;
		strcpy_bp(slot->token_info.label,
				p15card->tokeninfo ? p15card->tokeninfo->label : "",
				32);
	}

	slot->app_info = app_info;
	sc_log(context, "Initialized slot 0x%lx with token %*s", slot->id,
			(int)sizeof(slot->token_info.label), slot->token_info.label);
}


static CK_RV
pkcs15_create_slot(struct sc_pkcs11_card *p11card, struct pkcs15_fw_data *fw_data,
		struct sc_pkcs15_object *auth, struct sc_app_info *app_info,
		struct sc_pkcs11_slot **out)
{
	struct sc_pkcs11_slot *slot = NULL;
	CK_RV rv;

	rv = slot_allocate(&slot, p11card);
	if (rv != CKR_OK)
		return rv;

	/* There's a token in this slot */
	slot->slot_info.flags |= CKF_TOKEN_PRESENT;

	/* Fill in the slot/token info from pkcs15 data */
	if (fw_data)
		pkcs15_init_slot(fw_data->p15_card, slot, auth, app_info);
	else {
		/* Token is not initialized, announce pinpad capability nevertheless */
		if (slot->reader->capabilities & SC_READER_CAP_PIN_PAD)
			slot->token_info.flags |= CKF_PROTECTED_AUTHENTICATION_PATH;
	}

	*out = slot;
	return CKR_OK;
}


static int
_pkcs15_create_typed_objects(struct pkcs15_fw_data *fw_data)
{
	int rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PRKEY_RSA, "RSA private key",
			__pkcs15_create_prkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PUBKEY_RSA, "RSA public key",
			__pkcs15_create_pubkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PRKEY_EC, "EC private key",
			__pkcs15_create_prkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PUBKEY_EC, "EC public key",
			__pkcs15_create_pubkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PRKEY_GOSTR3410, "GOSTR3410 private key",
			__pkcs15_create_prkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_PUBKEY_GOSTR3410, "GOSTR3410 public key",
			__pkcs15_create_pubkey_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_CERT_X509, "certificate",
			__pkcs15_create_cert_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_DATA_OBJECT, "data object",
			__pkcs15_create_data_object);
	if (rv < 0)
		return rv;

	rv = pkcs15_create_pkcs11_objects(fw_data, SC_PKCS15_TYPE_SKEY_GENERIC, "Generic secret key",
			__pkcs15_create_secret_key_object);
	if (rv < 0)
		return rv;

	/* Match up related keys and certificates */
	pkcs15_bind_related_objects(fw_data);
	sc_log(context, "found %i FW objects", fw_data->num_objects);

	return rv;
}


int
_is_slot_auth_object(struct sc_pkcs15_auth_info *pin_info)
{

	/* Ignore all but PIN authentication objects */
	if (pin_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
		return 0;

	/* Ignore any non-authentication PINs */
	if ((pin_info->attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN) != 0)
		return 0;

	/* Ignore unblocking pins */
	if (!sc_pkcs11_conf.create_puk_slot)
		if (pin_info->attrs.pin.flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
			return 0;

	return 1;
}

int slot_get_logged_in_state(struct sc_pkcs11_slot *slot)
{
	int logged_in = SC_PIN_STATE_UNKNOWN;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_card *p15card = NULL;
	struct sc_pkcs15_object *pin_obj = NULL;
	struct sc_pkcs15_auth_info *pin_info;

	if (slot->p11card == NULL) {
		goto out;
	}

	fw_data = (struct pkcs15_fw_data *) slot->p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		goto out;
	p15card = fw_data->p15_card;

	if (slot->login_user == CKU_SO) {
		sc_pkcs15_find_so_pin(p15card, &pin_obj);
	} else {
		pin_obj = slot_data_auth(slot->fw_data);
	}

	if (!pin_obj)
		goto out;

	pin_info = (struct sc_pkcs15_auth_info *)pin_obj->data;
	if (!pin_info)
		goto out;
	sc_pkcs15_get_pin_info(p15card, pin_obj);
	logged_in = pin_info->logged_in;
out:
	return logged_in;
}


struct sc_pkcs15_object *
_get_auth_object_by_name(struct sc_pkcs15_card *p15card, char *name)
{
	struct sc_pkcs15_object *out = NULL;
	int rv = SC_ERROR_OBJECT_NOT_FOUND;

	/* please keep me in sync with md_get_pin_by_role() in minidriver */
	if (!strcmp(name, "UserPIN"))   {
		/* Try to get 'global' PIN; if no, get the 'local' one */
		rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_GLOBAL,
				SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
		if (rv)
			rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_LOCAL,
					SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
	}
	else if (!strcmp(name, "SignPIN"))   {
		int idx = 0;

		/* Get the 'global' user PIN */
		rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_GLOBAL,
				SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
		if (!rv)   {
			/* Global (user) PIN exists, get the local one -- sign PIN */
			rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_LOCAL,
					SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
		}
		else   {
			/* No global PIN, try to get first local one -- user PIN */
			rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_LOCAL,
					SC_PKCS15_PIN_TYPE_FLAGS_MASK, &idx, &out);
			if (!rv)   {
				/* User PIN is local, try to get the second local -- sign PIN */
				idx++;
				rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PIN_LOCAL,
						SC_PKCS15_PIN_TYPE_FLAGS_MASK, &idx, &out);
			}
		}
	}
	else if (!strcmp(name, "UserPUK"))   {
		/* Get the 'global' PUK; if no, get the 'local' one */
		rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PUK_GLOBAL,
				SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
		if (rv)
			rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_PUK_LOCAL,
					SC_PKCS15_PIN_TYPE_FLAGS_MASK, NULL, &out);
	}
	else if (!strcmp(name, "SignPUK"))   {
		/* TODO: Sign PUK to be defined */
	}
	else if (!strcmp(name, "SoPIN"))   {
		rv = sc_pkcs15_find_pin_by_flags(p15card, SC_PKCS15_PIN_TYPE_FLAGS_SOPIN,
				SC_PKCS15_PIN_TYPE_FLAGS_SOPIN, NULL, &out);
	}

	return rv ? NULL : out;
}


static void
_add_pin_related_objects(struct sc_pkcs11_slot *slot, struct sc_pkcs15_object *pin_obj,
		struct pkcs15_fw_data *fw_data, struct pkcs15_fw_data *move_to_fw)
{
	struct sc_pkcs15_auth_info *pin_info = (struct sc_pkcs15_auth_info *)pin_obj->data;
	unsigned i;

	sc_log(context, "Add objects related to PIN('%.*s',ID:%s)", (int) sizeof pin_obj->label, pin_obj->label, sc_pkcs15_print_id(&pin_info->auth_id));
	for (i=0; i < fw_data->num_objects; i++) {
		struct pkcs15_any_object *obj = fw_data->objects[i];

		/* "Fake" objects we've generated */
		if (__p15_type(obj) == (unsigned int)-1)
			continue;
		/* Some objects have an auth_id even though they are
		 * not private. Just ignore those... */
		if (!(obj->p15_object->flags & SC_PKCS15_CO_FLAG_PRIVATE))
			continue;
		sc_log(context, "ObjID(%p,%.*s,%x):%s", obj, (int) sizeof obj->p15_object->label, obj->p15_object->label,
				obj->p15_object->type, sc_pkcs15_print_id(&obj->p15_object->auth_id));
		if (!sc_pkcs15_compare_id(&pin_info->auth_id, &obj->p15_object->auth_id))   {
			sc_log(context, "Ignoring object %d", i);
			continue;
		}

		if (is_privkey(obj)) {
			sc_log(context, "Slot:%p, obj:%p  Adding private key %d to PIN '%.*s'", slot, obj, i, (int) sizeof pin_obj->label, pin_obj->label);
			pkcs15_add_object(slot, obj, NULL);
		}
		else if (is_data(obj)) {
			sc_log(context, "Slot:%p Adding data object %d to PIN '%.*s'", slot, i, (int) sizeof pin_obj->label, pin_obj->label);
			pkcs15_add_object(slot, obj, NULL);
		}
		else if (is_cert(obj)) {
			sc_log(context, "Slot:%p Adding cert object %d to PIN '%.*s'", slot, i, (int) sizeof pin_obj->label, pin_obj->label);
			pkcs15_add_object(slot, obj, NULL);
		}
		else if (is_skey(obj)) {
			sc_log(context, "Slot:%p Adding secret key object %d to PIN '%.*s'", slot, i, (int) sizeof pin_obj->label, pin_obj->label);
			pkcs15_add_object(slot, obj, NULL);
		}
		else   {
			sc_log(context, "Slot:%p Object %d skipped", slot, i);
			continue;
		}

		if (move_to_fw && move_to_fw != fw_data && move_to_fw->num_objects < MAX_OBJECTS)   {
			int tail = fw_data->num_objects - i - 1;

			move_to_fw->objects[move_to_fw->num_objects++] = obj;
			if (tail)
				memcpy(&fw_data->objects[i], &fw_data->objects[i + 1], sizeof(fw_data->objects[0]) * tail);
			i--;
			fw_data->num_objects--;
		}
	}
}


static void
_add_public_objects(struct sc_pkcs11_slot *slot, struct pkcs15_fw_data *fw_data)
{
	unsigned i;

	if (slot == NULL || fw_data == NULL)
		return;

	sc_log(context, "%i public objects to process", fw_data->num_objects);
	for (i=0; i < fw_data->num_objects; i++) {
		struct pkcs15_any_object *obj = fw_data->objects[i];

		/* "Fake" objects we've generated */
		if (__p15_type(obj) == (unsigned int)-1)
			continue;
		/* Ignore seen object */
		if (obj->base.flags & SC_PKCS11_OBJECT_SEEN)
			continue;
		/* Ignore 'private' object */
		if (obj->p15_object->flags & SC_PKCS15_CO_FLAG_PRIVATE)
			continue;
		/* PKCS#15 4.1.3 is a little vague, but implies if not PRIVATE it is readable
		 * even if there is an auth_id to allow writing for example.
		 * See bug issue #291
		 * treat pubkey and cert as readable.a
		 */
		if (obj->p15_object->auth_id.len && !(is_pubkey(obj) || is_cert(obj)))
			continue;

		sc_log(context, "Add public object(%p,%.*s,%x)", obj, (int) sizeof obj->p15_object->label, obj->p15_object->label, obj->p15_object->type);
		pkcs15_add_object(slot, obj, NULL);
	}
}


static CK_RV
pkcs15_create_tokens(struct sc_pkcs11_card *p11card, struct sc_app_info *app_info)
{
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_object *auth_user_pin = NULL, *auth_sign_pin = NULL;
	struct sc_pkcs11_slot *slot = NULL, *sign_slot = NULL;
	unsigned int cs_flags = sc_pkcs11_conf.create_slots_flags;
	CK_RV rv;
	int rc, i, idx;

	if (p11card) {
		sc_log(context, "create PKCS#15 tokens; fws:%p,%p,%p", p11card->fws_data[0], p11card->fws_data[1], p11card->fws_data[2]);
	}
	sc_log(context, "create slots flags 0x%X", cs_flags);

	/* Find out framework data corresponding to the given application */
	fw_data = get_fw_data(p11card, app_info, &idx);
	if (!fw_data)   {
		if (p11card) {
			sc_log(context, "Create slot for the non-binded card");
			pkcs15_create_slot(p11card, NULL, NULL, app_info, &slot);
		}
		return CKR_OK;
	}
	sc_log(context, "Use FW data with index %i; fw_data->p15_card %p", idx, fw_data->p15_card);

	/* Try to identify UserPIN and SignPIN by their symbolic name */
	auth_user_pin = _get_auth_object_by_name(fw_data->p15_card, "UserPIN");
	if (cs_flags & SC_PKCS11_SLOT_FOR_PIN_SIGN)
		auth_sign_pin = _get_auth_object_by_name(fw_data->p15_card, "SignPIN");
	sc_log(context, "Flags:0x%X; Auth User/Sign PINs %p/%p", cs_flags, auth_user_pin, auth_sign_pin);

	/* Add PKCS#15 objects of the known types to the framework data */
	rc = _pkcs15_create_typed_objects(fw_data);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, NULL);
	sc_log(context, "Found %d FW objects objects", fw_data->num_objects);

	/* Create slots for all non-unblock, non-so PINs if:
	 *  - 'UserPIN' cannot be identified (VT: for some cards with incomplete PIN flags);
	 *  - configuration impose to create slot for all PINs.
	 */
	if (!auth_user_pin || cs_flags & SC_PKCS11_SLOT_CREATE_ALL)   {
		struct sc_pkcs15_object *auths[MAX_OBJECTS];
		int auth_count;

		memset(auths, 0, sizeof(auths));
		/* Get authentication PKCS#15 objects present in the associated on-card application */
		rc = sc_pkcs15_get_objects(fw_data->p15_card, SC_PKCS15_TYPE_AUTH_PIN, auths, SC_PKCS15_MAX_PINS);
		if (rc < 0)
			return sc_to_cryptoki_error(rc, NULL);
		auth_count = rc;
		sc_log(context, "Found %d authentication objects", auth_count);

		for (i = 0; i < auth_count; i++) {
			struct sc_pkcs15_auth_info *pin_info = (struct sc_pkcs15_auth_info*)auths[i]->data;
			struct sc_pkcs11_slot *islot = NULL;

			/* Check if a slot could be created with this PIN */
			if (!_is_slot_auth_object(pin_info))
				continue;
			sc_log(context, "Found authentication object '%.*s'", (int) sizeof auths[i]->label, auths[i]->label);

			rv = pkcs15_create_slot(p11card, fw_data, auths[i], app_info, &islot);
			if (rv != CKR_OK)
				return CKR_OK; /* no more slots available for this card */
			islot->fw_data_idx = idx;
			_add_pin_related_objects(islot, auths[i], fw_data, NULL);

			/* Get slot to which the public objects will be associated */
			if (!slot && !auth_user_pin)
				slot = islot;
			else if (!slot && auth_user_pin && auth_user_pin == auths[i])
				slot = islot;
		}
	}
	else   {
		sc_log(context, "User/Sign PINs %p/%p", auth_user_pin, auth_sign_pin);
		if (auth_user_pin && (cs_flags & SC_PKCS11_SLOT_FOR_PIN_USER)) {
			/* For the UserPIN of the first slot create slot */
			sc_log(context, "Create slot for User PIN '%.*s'", (int) sizeof auth_user_pin->label, auth_user_pin->label);
			rv = pkcs15_create_slot(p11card, fw_data, auth_user_pin, app_info, &slot);
			if (rv != CKR_OK)
				return CKR_OK; /* no more slots available for this card */
			slot->fw_data_idx = idx;
			_add_pin_related_objects(slot, auth_user_pin, fw_data, NULL);
		}

		if (auth_sign_pin && (cs_flags & SC_PKCS11_SLOT_FOR_PIN_SIGN))   {
			/* Only Sign PIN slot needs to be exposed */
			sc_log(context, "Create slot for Sign PIN '%.*s'", (int) sizeof auth_sign_pin->label, auth_sign_pin->label);
			rv = pkcs15_create_slot(p11card, fw_data, auth_sign_pin, app_info, &sign_slot);
			if (rv != CKR_OK)
				return CKR_OK; /* no more slots available for this card */
			sign_slot->fw_data_idx = idx;
			_add_pin_related_objects(sign_slot, auth_sign_pin, fw_data, NULL);
		}

		if (!slot && sign_slot)
			slot = sign_slot;
	}

	if (!slot && (cs_flags == SC_PKCS11_SLOT_CREATE_ALL))   {
		sc_log(context, "Now create slot without AUTH object");
		pkcs15_create_slot(p11card, fw_data, NULL, app_info, &slot);
		sc_log(context, "Created slot without AUTH object: %p", slot);
	}

	if (slot)   {
		sc_log(context, "Add public objects to slot %p", slot);
		_add_public_objects(slot, fw_data);
	}

	sc_log(context, "All tokens created");
	return CKR_OK;
}


static CK_RV
pkcs15_release_token(struct sc_pkcs11_card *p11card, void *fw_token)
{
	sc_log(context, "pkcs15_release_token() not implemented");
	free(fw_token);
	return CKR_FUNCTION_REJECTED;
}


static CK_RV
pkcs15_login(struct sc_pkcs11_slot *slot, CK_USER_TYPE userType,
		CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
{
	struct sc_pkcs11_card *p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_card *p15card = NULL;
	struct sc_pkcs15_object *auth_object = NULL;
	struct sc_pkcs15_auth_info *pin_info = NULL;
	int rc;

	if (slot->p11card == NULL) {
		return CKR_TOKEN_NOT_RECOGNIZED;
	}
	p11card = slot->p11card;

	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_Login");
	p15card = fw_data->p15_card;

	sc_log(context, "pkcs15-login: userType 0x%lX, PIN length %li", userType, ulPinLen);
	switch (userType) {
	case CKU_USER:
		auth_object = slot_data_auth(slot->fw_data);
		if (auth_object == NULL)
			return CKR_USER_PIN_NOT_INITIALIZED;
		break;
	case CKU_SO:
		/* A card with no SO PIN is treated as if no SO login
		 * is required */
		rc = sc_pkcs15_find_so_pin(p15card, &auth_object);
		sc_log(context, "pkcs15-login: find SO PIN: rc %i", rc);

		/* If there's no SO PIN on the card, silently
		 * accept any PIN, and lock the card if required */
		if (rc == SC_ERROR_OBJECT_NOT_FOUND)   {
			rc = 0;
			if (sc_pkcs11_conf.lock_login)
				rc = lock_card(fw_data);

			if (sc_pkcs11_conf.pin_unblock_style == SC_PKCS11_PIN_UNBLOCK_SO_LOGGED_INITPIN)   {
				if (ulPinLen && ulPinLen < sizeof(fw_data->user_puk))   {
					memcpy(fw_data->user_puk, pPin, ulPinLen);
					fw_data->user_puk_len = (unsigned int) ulPinLen;
				}
			}

			sc_log(context, "No SOPIN found; returns %d", rc);
			return sc_to_cryptoki_error(rc, "C_Login");
		}
		else if (rc < 0)   {
			return sc_to_cryptoki_error(rc, "C_Login");
		}

		break;
	case CKU_CONTEXT_SPECIFIC:
		/*
		 * A session should already be open for user or SO
		 * All we need to do is authenticate to the card
		 * using the correct auth_object.
		 * TODO: handle the CK_SO case
		 */
		sc_log(context, "context specific login %d", slot->login_user);
		if (slot->login_user == CKU_USER) {
			auth_object = slot_data_auth(slot->fw_data);
			if (auth_object == NULL)
				return CKR_USER_PIN_NOT_INITIALIZED;
			break;
		}
		/* TODO looks like this was never executed,
		 * And even if it was, why the lock as a session
		 * should already be open and the card locked.
		 */
		/* For a while, used only to unblock User PIN. */
		rc = 0;
		if (sc_pkcs11_conf.lock_login)
			rc = lock_card(fw_data);
		sc_log(context, "context specific login returns %d", rc);
		return sc_to_cryptoki_error(rc, "C_Login");
	default:
		return CKR_USER_TYPE_INVALID;
	}
	pin_info = (struct sc_pkcs15_auth_info *) auth_object->data;
	if (pin_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
		return CKR_FUNCTION_REJECTED;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	if (p11card->card->reader->capabilities & SC_READER_CAP_PIN_PAD
			|| (p15card->card->caps & SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH)) {
		/* pPin should be NULL in case of a pin pad reader, but
		 * some apps (e.g. older Netscapes) don't know about it.
		 * So we don't require that pPin == NULL, but set it to
		 * NULL ourselves. This way, you can supply an empty (if
		 * possible) or fake PIN if an application asks a PIN).
		 */
		/* But we want to be able to specify a PIN on the command
		 * line (e.g. for the test scripts). So we don't do anything
		 * here - this gives the user the choice of entering
		 * an empty pin (which makes us use the pin pad) or
		 * a valid pin (which is processed normally). --okir */
		if (ulPinLen == 0)
			pPin = NULL;
	}

	/* By default, we make the reader resource manager keep other
	 * processes from accessing the card while we're logged in.
	 * Otherwise an attacker could perform some crypto operation
	 * after we've authenticated with the card */

	/* Context specific login is not real login but only a
	 * reassertion of the PIN to the card.
	 * And we don't want to do any extra operations to the card
	 * that could invalidate the assertion of the pin
	 * before the crypto operation that requires the assertion
	 */
	if (userType != CKU_CONTEXT_SPECIFIC) {
		if (sc_pkcs11_conf.lock_login && (rc = lock_card(fw_data)) < 0)   {
			return sc_to_cryptoki_error(rc, "C_Login");
		}
	}

	if (userType  == CKU_CONTEXT_SPECIFIC) {
		int auth_meth_saved = pin_info->auth_method;

		sc_log(context, "Setting SC_AC_CONTEXT_SPECIFIC");
		pin_info->auth_method = SC_AC_CONTEXT_SPECIFIC;
		rc = sc_pkcs15_verify_pin(p15card, auth_object, pPin, ulPinLen);
		pin_info->auth_method = auth_meth_saved;
	} else
		rc = sc_pkcs15_verify_pin(p15card, auth_object, pPin, ulPinLen);

	sc_log(context, "PKCS15 verify PIN returned %d", rc);

	if (rc != SC_SUCCESS)
		return sc_to_cryptoki_error(rc, "C_Login");

	if (userType == CKU_USER)   {
		sc_pkcs15_object_t *p15_obj = p15card->obj_list;
		sc_pkcs15_search_key_t sk;

		sc_log(context, "Check if pkcs15 object list can be completed.");

		/* Ensure non empty list */
		if (p15_obj == NULL)
			return CKR_OK;

		/* Select last object in list */
		while(p15_obj->next)
			p15_obj = p15_obj->next;

		/* Trigger enumeration of EF.XXX files */
		memset(&sk, 0, sizeof(sk));
		sk.class_mask = SC_PKCS15_SEARCH_CLASS_PRKEY | SC_PKCS15_SEARCH_CLASS_PUBKEY |
				SC_PKCS15_SEARCH_CLASS_CERT  | SC_PKCS15_SEARCH_CLASS_DATA;
		sc_pkcs15_search_objects(p15card, &sk, NULL, 0);

		/* Iterate over newly discovered objects */
		while(p15_obj->next) {
			struct pkcs15_any_object *fw_obj;

			p15_obj = p15_obj->next;

			if (!sc_pkcs15_compare_id(&pin_info->auth_id, &p15_obj->auth_id))
				continue;

			switch (p15_obj->type & SC_PKCS15_TYPE_CLASS_MASK) {
			case SC_PKCS15_TYPE_PRKEY:
				__pkcs15_create_prkey_object(fw_data, p15_obj, &fw_obj); break;
			case SC_PKCS15_TYPE_PUBKEY:
				__pkcs15_create_pubkey_object(fw_data, p15_obj, &fw_obj); break;
			case SC_PKCS15_TYPE_CERT:
				__pkcs15_create_cert_object(fw_data, p15_obj, &fw_obj); break;
			case SC_PKCS15_TYPE_DATA_OBJECT:
				__pkcs15_create_data_object(fw_data, p15_obj, &fw_obj); break;
			default: continue;
			}

			sc_log(context, "new object found: type=0x%03X", p15_obj->type);
			pkcs15_add_object(slot, fw_obj, NULL);
		}
	}

	return CKR_OK;
}


static CK_RV
pkcs15_logout(struct sc_pkcs11_slot *slot)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	CK_RV ret = CKR_OK;
	int rc;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_Logout");

	memset(fw_data->user_puk, 0, sizeof(fw_data->user_puk));
	fw_data->user_puk_len = 0;

	sc_pkcs15_pincache_clear(fw_data->p15_card);

	rc = sc_logout(fw_data->p15_card->card);

	/* Ignore missing card specific logout functions. #302 */
	if (rc == SC_ERROR_NOT_SUPPORTED)
		rc = SC_SUCCESS;

	if (rc != SC_SUCCESS)
		ret = sc_to_cryptoki_error(rc, "C_Logout");

	if (sc_pkcs11_conf.lock_login) {
		rc = unlock_card(fw_data);
		if (rc != SC_SUCCESS)
			ret = sc_to_cryptoki_error(rc, "C_Logout");
	}

	/* TODO DEE free any session objects ? */

	return ret;
}


static CK_RV
pkcs15_change_pin(struct sc_pkcs11_slot *slot,
		CK_CHAR_PTR pOldPin, CK_ULONG ulOldLen,
		CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct sc_pkcs15_card *p15card = NULL;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_auth_info *auth_info = NULL;
	struct sc_pkcs15_object *pin_obj = NULL;
	int login_user = slot->login_user;
	int rc;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_SetPin");

	p15card = fw_data->p15_card;

	if (login_user == CKU_SO) {
		rc = sc_pkcs15_find_so_pin(p15card, &pin_obj);
		sc_log(context, "pkcs15-login: find SO PIN: rc %i", rc);
	} else {
		pin_obj = slot_data_auth(slot->fw_data);
	}

	if (!pin_obj)
		return CKR_USER_PIN_NOT_INITIALIZED;

	auth_info = (struct sc_pkcs15_auth_info *)pin_obj->data;
	if (!auth_info)
		return CKR_USER_PIN_NOT_INITIALIZED;

	sc_log(context, "Change '%.*s' (ref:%i,type:%i)", (int) sizeof pin_obj->label, pin_obj->label, auth_info->attrs.pin.reference, login_user);
	if ((p11card->card->reader->capabilities & SC_READER_CAP_PIN_PAD)
			|| (p15card->card->caps & SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH)) {
		/* pPin should be NULL in case of a pin pad reader, but
		 * some apps (e.g. older Netscapes) don't know about it.
		 * So we don't require that pPin == NULL, but set it to
		 * NULL ourselves. This way, you can supply an empty (if
		 * possible) or fake PIN if an application asks a PIN).
		 */
		pOldPin = pNewPin = NULL;
		ulOldLen = ulNewLen = 0;
	}
	else if (ulNewLen < auth_info->attrs.pin.min_length || ulNewLen > auth_info->attrs.pin.max_length)  {
		return CKR_PIN_LEN_RANGE;
	}

	if (login_user < 0) {
		if (sc_pkcs11_conf.pin_unblock_style != SC_PKCS11_PIN_UNBLOCK_UNLOGGED_SETPIN) {
			sc_log(context, "PIN unlock is not allowed in unlogged session");
			return CKR_FUNCTION_NOT_SUPPORTED;
		}
		rc = sc_pkcs15_unblock_pin(fw_data->p15_card, pin_obj, pOldPin, ulOldLen, pNewPin, ulNewLen);
	}
	else if (login_user == CKU_CONTEXT_SPECIFIC)   {
		if (sc_pkcs11_conf.pin_unblock_style != SC_PKCS11_PIN_UNBLOCK_SCONTEXT_SETPIN) {
			sc_log(context, "PIN unlock is not allowed with CKU_CONTEXT_SPECIFIC login");
			return CKR_FUNCTION_NOT_SUPPORTED;
		}
		rc = sc_pkcs15_unblock_pin(fw_data->p15_card, pin_obj, pOldPin, ulOldLen, pNewPin, ulNewLen);
	}
	else if ((login_user == CKU_USER) || (login_user == CKU_SO)) {
		rc = sc_pkcs15_change_pin(fw_data->p15_card, pin_obj, pOldPin, ulOldLen, pNewPin, ulNewLen);
	}
	else {
		sc_log(context, "cannot change PIN: non supported login type: %i", login_user);
		return CKR_FUNCTION_NOT_SUPPORTED;
	}

	sc_log(context, "PIN change returns %d", rc);
	return sc_to_cryptoki_error(rc, "C_SetPIN");
}



#ifdef USE_PKCS15_INIT
static CK_RV
pkcs15_initialize(struct sc_pkcs11_slot *slot, void *ptr,
		CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen,
		CK_UTF8CHAR_PTR pLabel)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct sc_cardctl_pkcs11_init_token args;
	scconf_block *conf_block = NULL;
	int rc, enable_InitToken = 0;
	CK_RV rv;

	sc_log(context, "Get 'enable-InitToken' card configuration option");
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	conf_block = sc_get_conf_block(p11card->card->ctx, "framework", "pkcs15", 1);
	enable_InitToken = scconf_get_bool(conf_block, "pkcs11_enable_InitToken", 0);

	memset(&args, 0, sizeof(args));
	args.so_pin = pPin;
	args.so_pin_len = ulPinLen;
	args.label = (const char *) pLabel;

	sc_log(context, "Try card specific token initialize procedure");
	rc = sc_card_ctl(p11card->card, SC_CARDCTL_PKCS11_INIT_TOKEN, &args);
	if (rc == SC_ERROR_NOT_SUPPORTED && enable_InitToken)   {
		struct sc_profile *profile = NULL;
		struct pkcs15_fw_data *fw_data = NULL;
		struct sc_pkcs15_card *p15card = NULL;

		sc_log(context, "Using generic token initialize procedure");
		fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
		if (!fw_data)
			return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_Login");
		p15card = fw_data->p15_card;

		rc = sc_lock(p11card->card);
		if (rc < 0)
			return sc_to_cryptoki_error(rc, "C_InitToken");

		rc = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, NULL, &profile);
		if (rc < 0) {
			sc_log(context, "pkcs15init bind error %i", rc);
			sc_unlock(p11card->card);
			return sc_to_cryptoki_error(rc, "C_InitToken");
		}

		rc = sc_pkcs15init_finalize_profile(p11card->card, profile, NULL);
		if (rc) {
			sc_log(context, "finalize profile error %i", rc);
			return sc_to_cryptoki_error(rc, "C_InitToken");
		}

		sc_log(context, "set pkcs15init callbacks");
		pkcs15init_sopin = (char *)pPin;
		pkcs15init_sopin_len = ulPinLen;
		sc_pkcs15init_set_callbacks(&pkcs15init_callbacks);

		if (p15card)   {
			sc_log(context, "pkcs15init erase card");
			sc_pkcs15init_erase_card(p15card, profile, NULL);

			sc_log(context, "pkcs15init unbind");
			sc_pkcs15init_unbind(profile);

			rc = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, NULL, &profile);
			if (rc < 0) {
				sc_log(context, "pkcs15init bind error %i", rc);
				sc_pkcs15init_set_callbacks(NULL);
				sc_unlock(p11card->card);
				return sc_to_cryptoki_error(rc, "C_InitToken");
			}

			rc = sc_pkcs15init_finalize_profile(p11card->card, profile, NULL);
			if (rc) {
				sc_pkcs15init_set_callbacks(NULL);
				sc_log(context, "Cannot finalize profile: %i", rc);
				return sc_to_cryptoki_error(rc, "C_InitToken");
			}
		}
		else   {
			sc_log(context, "No erase for the non-initialized card");
		}

		if (!rc)  {
			struct sc_pkcs15init_initargs init_args;

			memset(&init_args, 0, sizeof(init_args));
			init_args.so_pin = pPin;
			init_args.so_pin_len = ulPinLen;
			init_args.label = (char *)pLabel;

			sc_log(context, "pkcs15init: create application on '%s' card", p11card->card->name);
			rc = sc_pkcs15init_add_app(p11card->card, profile, &init_args);
			sc_log(context, "pkcs15init: create application returns %i", rc);
		}

		pkcs15init_sopin = NULL;
		pkcs15init_sopin_len = 0;

		sc_log(context, "pkcs15init: unset callbacks");
		sc_pkcs15init_set_callbacks(NULL);

		sc_log(context, "pkcs15init: unbind");
		sc_pkcs15init_unbind(profile);

		sc_unlock(p11card->card);
	}

	if (rc < 0)   {
		sc_log(context, "init token error %i", rc);
		return sc_to_cryptoki_error(rc, "C_InitToken");
	}

	rv = card_removed(p11card->reader);
	if (rv != CKR_OK)   {
		sc_log(context, "remove card error 0x%lX", rv);
		return rv;
	}

	rv = card_detect_all();
	if (rv != CKR_OK)   {
		sc_log(context, "detect all card error 0x%lX", rv);
		return rv;
	}

	return CKR_OK;
}


static CK_RV
pkcs15_init_pin(struct sc_pkcs11_slot *slot, CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_pinargs args;
	struct sc_profile	*profile = NULL;
	struct sc_pkcs15_object	*auth_obj = NULL;
	struct sc_pkcs15_auth_info *auth_info = NULL;
	struct sc_cardctl_pkcs11_init_pin p11args;
	int rc;

	memset(&p11args, 0, sizeof(p11args));
	p11args.pin = pPin;
	p11args.pin_len = ulPinLen;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	rc = sc_card_ctl(p11card->card, SC_CARDCTL_PKCS11_INIT_PIN, &p11args);
	if (rc != SC_ERROR_NOT_SUPPORTED) {
		if (rc == SC_SUCCESS)
			return CKR_OK;
		return sc_to_cryptoki_error(rc, "C_InitPin");
	}

	sc_log(context, "Init PIN: pin %p:%lu; unblock style %i", pPin,
		ulPinLen, sc_pkcs11_conf.pin_unblock_style);

	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_InitPin");

	auth_info = slot_data_auth_info(slot->fw_data);
	if (auth_info && sc_pkcs11_conf.pin_unblock_style == SC_PKCS11_PIN_UNBLOCK_SO_LOGGED_INITPIN)   {
		/* C_InitPIN is used to unblock User PIN or set it in the SO session .*/
		auth_obj = slot_data_auth(slot->fw_data);
		if (fw_data->user_puk_len)
			rc = sc_pkcs15_unblock_pin(fw_data->p15_card, auth_obj,
					fw_data->user_puk, fw_data->user_puk_len, pPin, ulPinLen);
		else
			/* FIXME (VT): Actually sc_pkcs15_unblock_pin() do not accepts zero length PUK.
			 * Something like sc_pkcs15_set_pin() should be introduced.
			 * For a while, use the 'libopensc' API to set PIN. */
			rc = sc_reset_retry_counter(fw_data->p15_card->card, SC_AC_CHV, auth_info->attrs.pin.reference,
					NULL, 0, pPin, ulPinLen);

		return sc_to_cryptoki_error(rc, "C_InitPIN");
	}

	rc = sc_lock(p11card->card);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_InitPIN");

	rc = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, NULL, &profile);
	if (rc < 0) {
		sc_unlock(p11card->card);
		return sc_to_cryptoki_error(rc, "C_InitPIN");
	}

	rc = sc_pkcs15init_finalize_profile(p11card->card, profile, NULL);
	if (rc != CKR_OK) {
		sc_log(context, "Cannot finalize profile: %i", rc);
		return sc_to_cryptoki_error(rc, "C_InitPIN");
	}

	memset(&args, 0, sizeof(args));
	args.label = "User PIN";
	args.pin = pPin;
	args.pin_len = ulPinLen;
	rc = sc_pkcs15init_store_pin(fw_data->p15_card, profile, &args);

	sc_pkcs15init_unbind(profile);
	sc_unlock(p11card->card);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_InitPIN");

	rc = sc_pkcs15_find_pin_by_auth_id(fw_data->p15_card, &args.auth_id, &auth_obj);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_InitPIN");

	/* Re-initialize the slot */
	free(slot->fw_data);
	pkcs15_init_slot(fw_data->p15_card, slot, auth_obj, slot->app_info);

	return CKR_OK;
}


static unsigned long
pkcs15_check_bool_cka(CK_ATTRIBUTE_PTR attr, unsigned long flag)
{
	if (attr->ulValueLen != sizeof(CK_BBOOL) || !attr->pValue)
		return 0;

	if (*((CK_BBOOL *)attr->pValue))
		return flag;

	return 0;
}


static CK_RV
pkcs15_create_private_key(struct sc_pkcs11_slot *slot, struct sc_profile *profile,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
		CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_prkeyargs args;
	struct pkcs15_any_object *key_any_obj = NULL;
	struct sc_pkcs15_object	*key_obj = NULL;
	struct sc_pkcs15_auth_info *pin = NULL;
	CK_KEY_TYPE key_type;
	struct sc_pkcs15_prkey_rsa *rsa = NULL;
	struct sc_pkcs15_prkey_gostr3410 *gost = NULL;
	int rc;
	CK_RV rv;
	char label[SC_PKCS15_MAX_LABEL_SIZE];

	memset(&args, 0, sizeof(args));
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	/* See if the "slot" is pin protected. If so, get the PIN id */
	if ((pin = slot_data_auth_info(slot->fw_data)) != NULL)
		args.auth_id = pin->auth_id;

	/* Get the key type */
	rv = attr_find(pTemplate, ulCount, CKA_KEY_TYPE, &key_type, NULL);
	if (rv != CKR_OK)
		return rv;
	switch (key_type) {
		case CKK_RSA:
			args.key.algorithm = SC_ALGORITHM_RSA;
			rsa = &args.key.u.rsa;
			break;
		case CKK_GOSTR3410:
			set_gost3410_params(&args, NULL, pTemplate, ulCount, NULL, 0);
			args.key.algorithm = SC_ALGORITHM_GOSTR3410;
			gost = &args.key.u.gostr3410;
			break;
		case CKK_EC:
			args.key.algorithm = SC_ALGORITHM_EC;
			/* TODO: -DEE Do not have PKCS15 card with EC to test this */
			/* fall through */
		default:
			return CKR_ATTRIBUTE_VALUE_INVALID;
	}

	while (ulCount--) {
		CK_ATTRIBUTE_PTR attr = pTemplate++;
		sc_pkcs15_bignum_t *bn = NULL;

		switch (attr->type) {
		/* Skip attrs we already know or don't care for */
		case CKA_CLASS:
		case CKA_KEY_TYPE:
		case CKA_MODULUS_BITS:
		case CKA_PRIVATE:
			break;
		case CKA_LABEL:
			args.label = set_cka_label(attr, label);
			break;
		case CKA_ID:
			args.id.len = sizeof(args.id.value);
			rv = attr_extract(attr, args.id.value, &args.id.len);
			if (rv != CKR_OK)
				goto out;
			break;
		case CKA_MODULUS:
			bn = &rsa->modulus; break;
		case CKA_PUBLIC_EXPONENT:
			bn = &rsa->exponent; break;
		case CKA_PRIVATE_EXPONENT:
			bn = &rsa->d; break;
		case CKA_PRIME_1:
			bn = &rsa->p; break;
		case CKA_PRIME_2:
			bn = &rsa->q; break;
		case CKA_VALUE:
			if (key_type == CKK_GOSTR3410)
				bn = &gost->d;
			break;
		case CKA_SIGN:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_SIGN);
			break;
		case CKA_SIGN_RECOVER:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_SIGNRECOVER);
			break;
		case CKA_DECRYPT:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_DECRYPT);
			break;
		case CKA_UNWRAP:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_UNWRAP);
			break;
		case CKA_OPENSC_NON_REPUDIATION:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION);
			break;
		case CKA_ALWAYS_AUTHENTICATE:
			args.user_consent = (int) (pkcs15_check_bool_cka(attr, 1));
			break;
		default:
			/* ignore unknown attrs, or flag error? */
			continue;
		}

		if (bn) {
			if (attr->ulValueLen > 1024)   {
				return CKR_ATTRIBUTE_VALUE_INVALID;
			}
			bn->len = attr->ulValueLen;
			bn->data = (u8 *) attr->pValue;
		}
	}

	if (key_type == CKK_RSA)   {
		if (!rsa->modulus.len || !rsa->exponent.len || !rsa->d.len || !rsa->p.len || !rsa->q.len) {
			sc_log(context, "Template to store the RSA key is incomplete");
			rv = CKR_TEMPLATE_INCOMPLETE;
			goto out;
		}
	}
	else if (key_type == CKK_GOSTR3410)   {
		if (!gost->d.len)   {
			sc_log(context, "Template to store the GOST key is incomplete");
			return CKR_ATTRIBUTE_VALUE_INVALID;
		}
		/* CKA_VALUE arrives in little endian form. pkcs15init framework expects it in a big endian one. */
		rc = sc_mem_reverse(gost->d.data, gost->d.len);
		if (rc != SC_SUCCESS)  {
			rv = sc_to_cryptoki_error(rc, "C_CreateObject");
			goto out;
		}
	}

	rc = sc_pkcs15init_store_private_key(fw_data->p15_card, profile, &args, &key_obj);
	if (rc < 0) {
		rv = sc_to_cryptoki_error(rc, "C_CreateObject");
		goto out;
	}

	/* Create a new pkcs11 object for it */
	__pkcs15_create_prkey_object(fw_data, key_obj, &key_any_obj);
	pkcs15_add_object(slot, key_any_obj, phObject);

	rv = CKR_OK;

out:	return rv;
}


/*
 * Secret key objects can be stored on card, if the card supports them
 *
 * Session objects have CKA_TOKEN=false
 *
 * CKA_TOKEN = FALSE can mean two things:
 *		1. If the card supports on card session objects, the object is stored on card for duration of the PKCS#11 session.
 *		   Depending on card implementation, it can be automatically deleted during the card's reset.
 *		   This kind of objects are not written to the PKCS#15 directory file.
 *		2. If the card doesn't support on card session objects, a CKA_TOKEN = FALSE object is stored only in OpenSC's memory.
 *
 * This is used by the C_DeriveKey with ECDH to hold the
 * key, and the calling application can then retrieve the attributes as needed.
 * .
 */
static CK_RV
pkcs15_create_secret_key(struct sc_pkcs11_slot *slot, struct sc_profile *profile,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
		CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_skeyargs args;
	struct pkcs15_any_object *key_any_obj = NULL;
	struct sc_pkcs15_object	*key_obj = NULL;
	struct sc_pkcs15_auth_info *pin = NULL;
	struct sc_pkcs15_skey_info *skey_info;
	CK_KEY_TYPE key_type;
	CK_BBOOL _token = FALSE;
	CK_RV rv;
	int rc;
	char label[SC_PKCS15_MAX_LABEL_SIZE];
	CK_BBOOL temp_object = FALSE;

	memset(&args, 0, sizeof(args));
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	/* Get the key type */
	rv = attr_find(pTemplate, ulCount, CKA_KEY_TYPE, &key_type, NULL);
	if (rv != CKR_OK)
		return rv;

	/* CKA_TOKEN defaults to false */
	rv = attr_find(pTemplate, ulCount, CKA_TOKEN, &_token, NULL);
	if (rv != CKR_OK)
		return rv;

	/* See if the "slot" is pin protected. If so, get the PIN id */
	if ((pin = slot_data_auth_info(slot->fw_data)) != NULL)
		args.auth_id = pin->auth_id;

	switch (key_type) {
		case CKK_GENERIC_SECRET:
			args.algorithm = SC_ALGORITHM_UNDEFINED;
			break;
		case CKK_AES:
			args.algorithm = SC_ALGORITHM_AES;
			break;
		case CKK_DES3:
			args.algorithm = SC_ALGORITHM_3DES;
			break;
		case CKK_DES:
			args.algorithm = SC_ALGORITHM_DES;
			break;
		default:
			return CKR_ATTRIBUTE_VALUE_INVALID;
	}

	while (ulCount--) {
		CK_ATTRIBUTE_PTR attr = pTemplate++;

		switch (attr->type) {
		/* Skip attrs we already know or don't care for */
		case CKA_CLASS:
		case CKA_KEY_TYPE:
		case CKA_MODULUS_BITS:
		case CKA_PRIVATE:
			break;
		case CKA_LABEL:
			args.label = set_cka_label(attr, label);
			break;
		case CKA_ID:
			args.id.len = sizeof(args.id.value);
			rv = attr_extract(attr, args.id.value, &args.id.len);
			if (rv != CKR_OK)
				goto out;
			break;
		case CKA_VALUE_LEN:
			attr_extract(attr, &args.value_len, NULL);
			break;
		case CKA_VALUE:
			if (attr->pValue) {
				free(args.key.data);
				args.key.data = calloc(1,attr->ulValueLen);
				if (!args.key.data)
					return CKR_HOST_MEMORY;
				memcpy(args.key.data, attr->pValue, attr->ulValueLen);
				args.key.data_len = attr->ulValueLen;
			}
			break;
		case CKA_DECRYPT:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_DECRYPT);
			break;
		case CKA_ENCRYPT:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_ENCRYPT);
			break;
		case CKA_WRAP:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_WRAP);
			break;
		case CKA_UNWRAP:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_UNWRAP);
			break;
		case CKA_EXTRACTABLE:
			if (pkcs15_check_bool_cka(attr, 1))
				args.access_flags |= SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE;
			break;
		case CKA_OPENSC_ALWAYS_AUTH_ANY_OBJECT:
			args.user_consent = (int) (pkcs15_check_bool_cka(attr, 1));
			break;
		default:
			/* ignore unknown attrs, or flag error? */
			continue;
		}
	}

	/* If creating a PKCS#11 session object, i.e. one that is only in memory */
	if (_token == FALSE && (fw_data->p15_card->card->caps & SC_CARD_CAP_ONCARD_SESSION_OBJECTS) == 0) {

		/* TODO Have 3 choices as to how to create the object.
		 * (1)create a sc_pkcs15init_store_secret_key routine like the others
		 * (2)use the sc_pkcs15emu_ routines
		 * (3)do it inline here (Will do this for now)
		 */

		key_obj = calloc(1, sizeof(sc_pkcs15_object_t));
		if (key_obj == NULL) {
			rv = CKR_HOST_MEMORY;
			goto out;
		}
		temp_object = TRUE;
		key_obj->type = SC_PKCS15_TYPE_SKEY;

		if (args.id.len)
			memcpy(key_obj->label, args.id.value, args.id.len);

		key_obj->flags = 2; /* TODO not sure what these mean */

		skey_info = calloc(1, sizeof(sc_pkcs15_skey_info_t));
		if (skey_info == NULL) {
			rv = CKR_HOST_MEMORY;
			goto out;
		}
		key_obj->data = skey_info;
		skey_info->usage = (unsigned int) args.usage;
		skey_info->native = 0; /* card can not use this */
		skey_info->access_flags = 0; /* looks like not needed */
		skey_info->key_type = key_type; /* PKCS#11 CKK_* */
		skey_info->data.value = args.key.data;
		skey_info->data.len = args.key.data_len;
		skey_info->value_len = args.value_len * 8; /* key length comes in number of bytes, use length in bits in PKCS#15. */
		args.key.data = NULL;
		key_obj->session_object = 1;
	}
	else {
		if(_token == FALSE)
			args.session_object = 1;	/* store the object on card for duration of the session. */

		args.value_len = args.value_len * 8; /* CKA_VALUE_LEN is number of bytes, PKCS#15 needs key length in bits */
		rc = sc_pkcs15init_store_secret_key(fw_data->p15_card, profile, &args, &key_obj);
		if (rc < 0) {
			rv = sc_to_cryptoki_error(rc, "C_CreateObject");
			goto out;
		}
	}

	/* Create a new pkcs11 object for it */
	__pkcs15_create_secret_key_object(fw_data, key_obj, &key_any_obj);
	pkcs15_add_object(slot, key_any_obj, phObject);

	rv = CKR_OK;

out:
	free(args.key.data); /* if allocated */
	if (temp_object)
		free(key_obj); /* do not free if the object was created by pkcs15init. It will be freed in C_Finalize */
	return rv;
}


static CK_RV
pkcs15_create_public_key(struct sc_pkcs11_slot *slot, struct sc_profile *profile,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_pubkeyargs args;
	struct pkcs15_any_object *key_any_obj = NULL;
	struct sc_pkcs15_object	*key_obj = NULL;
	struct sc_pkcs15_auth_info *pin = NULL;
	CK_KEY_TYPE key_type;
	struct sc_pkcs15_pubkey_rsa *rsa = NULL;
	int rc;
	CK_RV rv;
	char label[SC_PKCS15_MAX_LABEL_SIZE];

	memset(&args, 0, sizeof(args));
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	/* See if the "slot" is pin protected. If so, get the PIN id */
	if ((pin = slot_data_auth_info(slot->fw_data)) != NULL)
		args.auth_id = pin->auth_id;

	/* Get the key type */
	rv = attr_find(pTemplate, ulCount, CKA_KEY_TYPE, &key_type, NULL);
	if (rv != CKR_OK)
		return rv;
	switch (key_type) {
		case CKK_RSA:
			args.key.algorithm = SC_ALGORITHM_RSA;
			rsa = &args.key.u.rsa;
			break;
		case CKK_EC:
			/* TODO: -DEE Do not have real pkcs15 card with EC */
			/* fall through */
		default:
			return CKR_ATTRIBUTE_VALUE_INVALID;
	}

	while (ulCount--) {
		CK_ATTRIBUTE_PTR attr = pTemplate++;
		sc_pkcs15_bignum_t *bn = NULL;

		switch (attr->type) {
		/* Skip attrs we already know or don't care for */
		case CKA_CLASS:
		case CKA_KEY_TYPE:
		case CKA_MODULUS_BITS:
		case CKA_PRIVATE:
			break;
		case CKA_LABEL:
			args.label = set_cka_label(attr, label);
			break;
		case CKA_ID:
			args.id.len = sizeof(args.id.value);
			rv = attr_extract(attr, args.id.value, &args.id.len);
			if (rv != CKR_OK)
				return rv;
			break;
		case CKA_MODULUS:
			bn = &rsa->modulus; break;
		case CKA_PUBLIC_EXPONENT:
			bn = &rsa->exponent; break;
		case CKA_VERIFY:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_VERIFY);
			break;
		case CKA_VERIFY_RECOVER:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER);
			break;
		case CKA_ENCRYPT:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_ENCRYPT);
			break;
		case CKA_WRAP:
			args.usage |= pkcs15_check_bool_cka(attr, SC_PKCS15_PRKEY_USAGE_WRAP);
			break;
		default:
			/* ignore unknown attrs, or flag error? */
			continue;
		}

		if (bn) {
			if (attr->ulValueLen > 1024)
				return CKR_ATTRIBUTE_VALUE_INVALID;
			bn->len = attr->ulValueLen;
			bn->data = (u8 *) attr->pValue;
		}
	}

	if (!rsa->modulus.len || !rsa->exponent.len)
		return CKR_TEMPLATE_INCOMPLETE;

	rc = sc_pkcs15init_store_public_key(fw_data->p15_card, profile, &args, &key_obj);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_CreateObject");

	/* Create a new pkcs11 object for it */
	__pkcs15_create_pubkey_object(fw_data, key_obj, &key_any_obj);
	pkcs15_add_object(slot, key_any_obj, phObject);

	return CKR_OK;
}


static CK_RV
pkcs15_create_certificate(struct sc_pkcs11_slot *slot,
		struct sc_profile *profile,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
		CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_certargs args;
	struct pkcs15_any_object *cert_any_obj = NULL;
	struct sc_pkcs15_object	*cert_obj = NULL;
	CK_CERTIFICATE_TYPE	cert_type;
	CK_BBOOL		bValue;
	int			rc;
	CK_RV rv;
	char label[SC_PKCS15_MAX_LABEL_SIZE];

	memset(&args, 0, sizeof(args));
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	/* Get the key type */
	rv = attr_find(pTemplate, ulCount, CKA_CERTIFICATE_TYPE,
				&cert_type, NULL);
	if (rv != CKR_OK)
		return rv;
	if (cert_type != CKC_X_509)
		return CKR_ATTRIBUTE_VALUE_INVALID;

	while (ulCount--) {
		CK_ATTRIBUTE_PTR attr = pTemplate++;

		switch (attr->type) {
		/* Skip attrs we already know or don't care for */
		case CKA_CLASS:
			break;
		case CKA_PRIVATE:
			attr_extract(attr, &bValue, NULL);
			if (bValue) {
				rv = CKR_TEMPLATE_INCONSISTENT;
				goto out;
			}
			break;
		case CKA_LABEL:
			args.label = set_cka_label(attr, label);
			break;
		case CKA_ID:
			args.id.len = sizeof(args.id.value);
			rv = attr_extract(attr, args.id.value, &args.id.len);
			if (rv != CKR_OK)
				goto out;
			break;
		case CKA_VALUE:
			args.der_encoded.len = attr->ulValueLen;
			args.der_encoded.value = (u8 *) attr->pValue;
			break;
		default:
			/* ignore unknown attrs, or flag error? */
			continue;
		}
	}

	if (args.der_encoded.len == 0) {
		rv = CKR_TEMPLATE_INCOMPLETE;
		goto out;
	}

	rc = sc_pkcs15init_store_certificate(fw_data->p15_card, profile, &args, &cert_obj);
	if (rc < 0) {
		rv = sc_to_cryptoki_error(rc, "C_CreateObject");
		goto out;
	}
	/* Create a new pkcs11 object for it */
	__pkcs15_create_cert_object(fw_data, cert_obj, &cert_any_obj);
	pkcs15_add_object(slot, cert_any_obj, phObject);

	rv = CKR_OK;

out:	return rv;
}


static CK_RV
pkcs15_create_data(struct sc_pkcs11_slot *slot, struct sc_profile *profile,
		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
		CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_dataargs args;
	struct pkcs15_any_object *data_any_obj = NULL;
	struct sc_pkcs15_object	*data_obj = NULL;
	struct sc_pkcs15_auth_info *pin = NULL;
	CK_BBOOL bValue;
	int rc;
	CK_RV rv;
	char label[SC_PKCS15_MAX_LABEL_SIZE];

	memset(&args, 0, sizeof(args));
	sc_init_oid(&args.app_oid);

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	while (ulCount--) {
		CK_ATTRIBUTE_PTR attr = pTemplate++;

		switch (attr->type) {
		/* Skip attrs we already know or don't care for */
		case CKA_CLASS:
			break;
		case CKA_PRIVATE:
			attr_extract(attr, &bValue, NULL);
			if (bValue) {
				pin = slot_data_auth_info(slot->fw_data);
				if (pin == NULL) {
					rv = CKR_TEMPLATE_INCOMPLETE;
					goto out;
				}
				args.auth_id = pin->auth_id;
			}
			break;
		case CKA_LABEL:
			args.label = set_cka_label(attr, label);
			break;
		case CKA_ID:
			args.id.len = sizeof(args.id.value);
			rv = attr_extract(attr, args.id.value, &args.id.len);
			if (rv != CKR_OK)
				goto out;
			break;
		case CKA_APPLICATION:
			args.app_label = (char *) attr->pValue;
			break;
		case CKA_OBJECT_ID:
			if (sc_asn1_decode_object_id(attr->pValue, attr->ulValueLen, &args.app_oid)) {
				rv = CKR_ATTRIBUTE_VALUE_INVALID;
				goto out;
			}
			break;
		case CKA_VALUE:
			args.der_encoded.len = attr->ulValueLen;
			args.der_encoded.value = (u8 *) attr->pValue;
			break;
		default:
			/* ignore unknown attrs, or flag error? */
			continue;
		}
	}

	rc = sc_pkcs15init_store_data_object(fw_data->p15_card, profile, &args, &data_obj);
	if (rc < 0) {
		rv = sc_to_cryptoki_error(rc, "C_CreateObject");
		goto out;
	}
	/* Create a new pkcs11 object for it */
	__pkcs15_create_data_object(fw_data, data_obj, &data_any_obj);
	pkcs15_add_object(slot, data_any_obj, phObject);

	rv = CKR_OK;

out:	return rv;
}


static CK_RV
pkcs15_create_object(struct sc_pkcs11_slot *slot, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
		CK_OBJECT_HANDLE_PTR phObject)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_profile *profile = NULL;
	CK_OBJECT_CLASS	_class;
	CK_BBOOL _token = FALSE;
	CK_RV rv;
	int rc;
	CK_BBOOL p15init_create_object;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_CreateObject");

	rv = attr_find(pTemplate, ulCount, CKA_CLASS, &_class, NULL);
	if (rv != CKR_OK)
		return rv;

	rv = attr_find(pTemplate, ulCount, CKA_TOKEN, &_token, NULL);
	if (rv == CKR_TEMPLATE_INCOMPLETE) {
		/* TODO OpenSC has not checked CKA_TOKEN == TRUE, so only
		 * so only enforce for secret_key
		 */
		if (_class != CKO_SECRET_KEY)
			_token = TRUE; /* default if not in template */
	}
	else if (rv != CKR_OK) {
		return rv;
	}

	/* TODO The previous code does not check for CKA_TOKEN=TRUE
	 * PKCS#11 CreatObject examples always have it, but
	 * PKCS#11 says the default is false.
	 * for backward compatibility, will default to TRUE
	 */
	 /* Dont need profile id creating session only objects,
		except when the card supports temporary on card session objects */
	p15init_create_object = _token == TRUE || (p11card->card->caps & SC_CARD_CAP_ONCARD_SESSION_OBJECTS) == SC_CARD_CAP_ONCARD_SESSION_OBJECTS;

	if (p15init_create_object) {
		struct sc_aid *aid = NULL;

		rc = sc_lock(p11card->card);
		if (rc < 0)
			return sc_to_cryptoki_error(rc, "C_CreateObject");

		/* Bind the profile */
		rc = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, slot->app_info, &profile);
		if (rc < 0) {
			sc_unlock(p11card->card);
			return sc_to_cryptoki_error(rc, "C_CreateObject");
		}

		if (slot->app_info)
			aid = &slot->app_info->aid;

		rc = sc_pkcs15init_finalize_profile(p11card->card, profile, aid);
		if (rc != CKR_OK) {
			sc_log(context, "Cannot finalize profile: %i", rc);
			sc_unlock(p11card->card);
			return sc_to_cryptoki_error(rc, "C_CreateObject");
		}

		sc_pkcs15init_set_p15card(profile, fw_data->p15_card);
	}
	switch (_class) {
	case CKO_PRIVATE_KEY:
		rv = pkcs15_create_private_key(slot, profile, pTemplate, ulCount, phObject);
		break;
	case CKO_PUBLIC_KEY:
		rv = pkcs15_create_public_key(slot, profile, pTemplate, ulCount, phObject);
		break;
	case CKO_CERTIFICATE:
		rv = pkcs15_create_certificate(slot, profile, pTemplate, ulCount, phObject);
		break;
	case CKO_DATA:
		rv = pkcs15_create_data(slot, profile, pTemplate, ulCount, phObject);
		break;
	case CKO_SECRET_KEY:
		rv = pkcs15_create_secret_key(slot, profile, pTemplate, ulCount, phObject);
		break;
	default:
		rv = CKR_FUNCTION_NOT_SUPPORTED;
	}

	if (p15init_create_object) {
		// TODO: after sc_pkcs15init_unbind, user may have to enter PIN on a pin pad reader even though authentication state
		// is supposed to remain open. Check why this happens.
		sc_pkcs15init_unbind(profile);
		sc_unlock(p11card->card);
	}

	return rv;
}


static CK_RV
get_X509_usage_privk(CK_ATTRIBUTE_PTR pTempl, CK_ULONG ulCount, unsigned long *x509_usage)
{
	CK_ULONG i;
	for (i = 0; i < ulCount; i++) {
		CK_ATTRIBUTE_TYPE typ = pTempl[i].type;
		CK_BBOOL *val = (CK_BBOOL *) pTempl[i].pValue;
		if (val == NULL)
			continue;
		if (typ == CKA_SIGN && *val)
			*x509_usage |= SC_PKCS15INIT_X509_DIGITAL_SIGNATURE;
		if (typ == CKA_UNWRAP && *val)
			*x509_usage |= SC_PKCS15INIT_X509_KEY_ENCIPHERMENT;
		if (typ == CKA_DECRYPT && *val)
			*x509_usage |= SC_PKCS15INIT_X509_DATA_ENCIPHERMENT;
		if (typ == CKA_DERIVE && *val)
			*x509_usage |= SC_PKCS15INIT_X509_KEY_AGREEMENT;
		if (typ == CKA_OPENSC_NON_REPUDIATION && *val)
			*x509_usage |= SC_PKCS15INIT_X509_NON_REPUDIATION;
		if (typ == CKA_VERIFY || typ == CKA_WRAP || typ == CKA_ENCRYPT) {
			sc_log(context,
				"get_X509_usage_privk(): invalid typ = 0x%0lx",
				typ);
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
	}
	return CKR_OK;
}


static CK_RV
get_X509_usage_pubk(CK_ATTRIBUTE_PTR pTempl, CK_ULONG ulCount, unsigned long *x509_usage)
{
	CK_ULONG i;
	for (i = 0; i < ulCount; i++) {
		CK_ATTRIBUTE_TYPE typ = pTempl[i].type;
		CK_BBOOL *val = (CK_BBOOL *) pTempl[i].pValue;
		if (val == NULL)
			continue;
		if (typ == CKA_VERIFY && *val)
			*x509_usage |= SC_PKCS15INIT_X509_DIGITAL_SIGNATURE;
		if (typ == CKA_WRAP && *val)
			*x509_usage |= SC_PKCS15INIT_X509_KEY_ENCIPHERMENT;
		if (typ == CKA_ENCRYPT && *val)
			*x509_usage |= SC_PKCS15INIT_X509_DATA_ENCIPHERMENT;
		if (typ == CKA_DERIVE && *val)
			*x509_usage |= SC_PKCS15INIT_X509_KEY_AGREEMENT;
		if (typ == CKA_SIGN || typ == CKA_UNWRAP || typ == CKA_DECRYPT) {
			sc_log(context,
				"get_X509_usage_pubk(): invalid typ = 0x%0lx",
				typ);
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
	}
	return CKR_OK;
}


static CK_RV
set_gost3410_params(struct sc_pkcs15init_prkeyargs *prkey_args,
		struct sc_pkcs15init_pubkeyargs *pubkey_args,
		CK_ATTRIBUTE_PTR pPubTpl, CK_ULONG ulPubCnt,
		CK_ATTRIBUTE_PTR pPrivTpl, CK_ULONG ulPrivCnt)
{
	const CK_BYTE * gost_params_encoded_oid_from_template;
	const CK_BYTE * gost_hash_params_encoded_oid_from_template;
	size_t len, param_index, hash_index;
	CK_RV rv;

	/* If template has CKA_GOSTR3410_PARAMS attribute, set param_index to
	 * corresponding item's index in gostr3410_param_oid[] */
	if (pPrivTpl && ulPrivCnt)
		rv = attr_find_ptr2(pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt, CKA_GOSTR3410_PARAMS, (void **)&gost_params_encoded_oid_from_template, &len);
	else
		rv = attr_find_ptr(pPubTpl, ulPubCnt, CKA_GOSTR3410_PARAMS, (void **)&gost_params_encoded_oid_from_template, &len);

	if (rv == CKR_OK) {
		size_t nn = sizeof(gostr3410_param_oid)/sizeof(gostr3410_param_oid[0]);

		for (param_index = 0; param_index < nn; ++param_index) {
			if (len != gostr3410_param_oid[param_index].encoded_oid_size)
				continue;
			if (!memcmp(gost_params_encoded_oid_from_template, gostr3410_param_oid[param_index].encoded_oid, len))
				break;
		}

		if (param_index == nn)
			return CKR_ATTRIBUTE_VALUE_INVALID;
	}
	else if (rv == CKR_TEMPLATE_INCOMPLETE)
		/* Default used parameters' index */
		param_index = 0;
	else
		return rv;

	/* If template has CKA_GOSTR3411_PARAMS attribute, set hash_index to
	 * corresponding item's index in gostr3410_hash_param_oid[] */
	if (pPrivTpl && ulPrivCnt)
		rv = attr_find_ptr2(pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt, CKA_GOSTR3411_PARAMS, (void **)&gost_hash_params_encoded_oid_from_template, &len);
	else
		rv = attr_find_ptr(pPubTpl, ulPubCnt, CKA_GOSTR3411_PARAMS, (void **)&gost_hash_params_encoded_oid_from_template, &len);

	if (rv == CKR_OK) {
		size_t nn = sizeof(gostr3410_hash_param_oid)/sizeof(gostr3410_hash_param_oid[0]);

		for (hash_index = 0; hash_index < nn; ++hash_index) {
			if (len != gostr3410_hash_param_oid[hash_index].encoded_oid_size)
				continue;
			if (!memcmp(gost_hash_params_encoded_oid_from_template, gostr3410_hash_param_oid[hash_index].encoded_oid, len))
				break;
		}

		if (hash_index == nn)
			return CKR_ATTRIBUTE_VALUE_INVALID;
	}
	else if (rv == CKR_TEMPLATE_INCOMPLETE)
		/* Default used hash parameters' index */
		hash_index = 0;
	else
		return rv;

	/* Set params and hash oids in priv and pub keys' gostr3410 params
	 * and set params oid_id in priv key */
	if (prkey_args) {
		(prkey_args->params).gost.gostr3410 = gostr3410_param_oid[param_index].oid_id;
		memcpy(&(prkey_args->key).u.gostr3410.params.key,
			gostr3410_param_oid[param_index].oid,
			gostr3410_param_oid[param_index].oid_size);
		memcpy(&(prkey_args->key).u.gostr3410.params.hash,
			gostr3410_hash_param_oid[hash_index].oid,
			gostr3410_hash_param_oid[hash_index].oid_size);
	}
	if (pubkey_args) {
		(pubkey_args->params).gost.gostr3410 = gostr3410_param_oid[param_index].oid_id;
		memcpy(&(pubkey_args->key).u.gostr3410.params.key,
			gostr3410_param_oid[param_index].oid,
			gostr3410_param_oid[param_index].oid_size);
		memcpy(&(pubkey_args->key).u.gostr3410.params.hash,
			gostr3410_hash_param_oid[hash_index].oid,
			gostr3410_hash_param_oid[hash_index].oid_size);
	}

	return CKR_OK;
}

/* FIXME: check for the public exponent in public key template and use this value */
static CK_RV
pkcs15_gen_keypair(struct sc_pkcs11_slot *slot, CK_MECHANISM_PTR pMechanism,
			CK_ATTRIBUTE_PTR pPubTpl, CK_ULONG ulPubCnt,
			CK_ATTRIBUTE_PTR pPrivTpl, CK_ULONG ulPrivCnt,
			CK_OBJECT_HANDLE_PTR phPubKey, CK_OBJECT_HANDLE_PTR phPrivKey)                /* gets priv. key handle */
{
	struct sc_profile *profile = NULL;
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct sc_pkcs15_auth_info *pin = NULL;
	struct sc_aid *aid = NULL;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15init_keygen_args keygen_args;
	struct sc_pkcs15init_pubkeyargs pub_args;
	struct sc_pkcs15_object	 *priv_key_obj = NULL, *pub_key_obj = NULL;
	struct pkcs15_any_object *priv_any_obj = NULL, *pub_any_obj = NULL;
	struct pkcs15_prkey_object *priv_prk_obj = NULL;
	struct sc_pkcs15_id id;
	size_t		len;
	CK_KEY_TYPE	keytype;
	CK_ULONG	keybits = 0;
	char		pub_label[SC_PKCS15_MAX_LABEL_SIZE];
	char		priv_label[SC_PKCS15_MAX_LABEL_SIZE];
	int		rc;
	CK_RV rv = CKR_OK;
	CK_BBOOL always_auth = CK_FALSE;

	sc_log(context, "Keypair generation, mech = 0x%0lx",
		   pMechanism->mechanism);

	if (pMechanism->mechanism != CKM_RSA_PKCS_KEY_PAIR_GEN
			&& pMechanism->mechanism != CKM_GOSTR3410_KEY_PAIR_GEN
			&& pMechanism->mechanism != CKM_EC_KEY_PAIR_GEN)
		return CKR_MECHANISM_INVALID;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GenerateKeyPair");

	rc = sc_lock(p11card->card);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_GenerateKeyPair");

	rc = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, slot->app_info, &profile);
	if (rc < 0) {
		sc_unlock(p11card->card);
		return sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
	}

	if(slot->app_info)
		aid = &slot->app_info->aid;

	rc = sc_pkcs15init_finalize_profile(p11card->card, profile, aid);
	if (rc != CKR_OK) {
		sc_log(context, "Cannot finalize profile: %i", rc);
		return sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
	}

	memset(&keygen_args, 0, sizeof(keygen_args));
	memset(&pub_args, 0, sizeof(pub_args));

	/* 1. Convert the pkcs11 attributes to pkcs15init args */

	if ((pin = slot_data_auth_info(slot->fw_data)) != NULL)
		keygen_args.prkey_args.auth_id = pub_args.auth_id = pin->auth_id;

	rv = attr_find2(pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt, CKA_KEY_TYPE,
		&keytype, NULL);
	if (rv != CKR_OK && pMechanism->mechanism == CKM_RSA_PKCS_KEY_PAIR_GEN)
		keytype = CKK_RSA;
	else if (rv != CKR_OK && pMechanism->mechanism == CKM_EC_KEY_PAIR_GEN)
		keytype = CKK_EC;
	else if (rv != CKR_OK && pMechanism->mechanism == CKM_GOSTR3410_KEY_PAIR_GEN)
		keytype = CKK_GOSTR3410;
	else if (rv != CKR_OK)
		goto kpgen_done;

	if (keytype == CKK_GOSTR3410)   {
		keygen_args.prkey_args.key.algorithm = SC_ALGORITHM_GOSTR3410;
		pub_args.key.algorithm               = SC_ALGORITHM_GOSTR3410;
		rv = set_gost3410_params(&keygen_args.prkey_args, &pub_args,
				pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt);
		if (rv != CKR_OK)
			goto kpgen_done;
		keybits = SC_PKCS15_GOSTR3410_KEYSIZE;
	}
	else if (keytype == CKK_RSA)   {
		/* default value (CKA_KEY_TYPE isn't set) or CKK_RSA is set */
		keygen_args.prkey_args.key.algorithm = SC_ALGORITHM_RSA;
		pub_args.key.algorithm               = SC_ALGORITHM_RSA;

		rv = attr_find2(pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt,	CKA_MODULUS_BITS, &keybits, NULL);
		if (rv != CKR_OK)
			keybits = 1024; /* Default key size */
		/* TODO: check allowed values of keybits */
	}
	else if (keytype == CKK_EC)   {
		struct sc_lv_data *der = &keygen_args.prkey_args.key.u.ec.params.der;

		der->len = sizeof(struct sc_object_id);
		rv = attr_find_and_allocate_ptr(pPubTpl, ulPubCnt, CKA_EC_PARAMS, (void **)&der->value, &der->len);
		if (rv != CKR_OK)   {
			sc_unlock(p11card->card);
			return sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
		}

		keygen_args.prkey_args.key.algorithm = SC_ALGORITHM_EC;
		pub_args.key.algorithm               = SC_ALGORITHM_EC;
	}
	else   {
		/* CKA_KEY_TYPE is set, but keytype isn't correct */
		rv = CKR_ATTRIBUTE_VALUE_INVALID;
		goto kpgen_done;
	}

	id.len = SC_PKCS15_MAX_ID_SIZE;
	rv = attr_find2(pPubTpl, ulPubCnt, pPrivTpl, ulPrivCnt,	CKA_ID, &id.value, &id.len);
	if (rv == CKR_OK)
		keygen_args.prkey_args.id = pub_args.id = id;

	len = sizeof(priv_label) - 1;
	rv = attr_find(pPrivTpl, ulPrivCnt, CKA_LABEL, priv_label, &len);
	if (rv == CKR_OK) {
		priv_label[len] = '\0';
		keygen_args.prkey_args.label = priv_label;
	}
	len = sizeof(pub_label) - 1;
	rv = attr_find(pPubTpl, ulPubCnt, CKA_LABEL, pub_label, &len);
	if (rv == CKR_OK) {
		pub_label[len] = '\0';
		keygen_args.pubkey_label = pub_label;
		pub_args.label = pub_label;
	}

	rv = get_X509_usage_privk(pPrivTpl, ulPrivCnt, &keygen_args.prkey_args.x509_usage);
	if (rv == CKR_OK)
		rv = get_X509_usage_pubk(pPubTpl, ulPubCnt, &keygen_args.prkey_args.x509_usage);
	if (rv != CKR_OK)
		goto kpgen_done;
	pub_args.x509_usage = keygen_args.prkey_args.x509_usage;

	len = sizeof(always_auth);
	rv = attr_find(pPrivTpl, ulPrivCnt, CKA_ALWAYS_AUTHENTICATE, &always_auth, &len);
	if (rv == CKR_OK && always_auth == CK_TRUE) {
		keygen_args.prkey_args.user_consent = 1;
	}

	/* 3.a Try on-card key pair generation */

	sc_pkcs15init_set_p15card(profile, fw_data->p15_card);

	sc_log(context, "Try on-card key pair generation");
	rc = sc_pkcs15init_generate_key(fw_data->p15_card, profile, &keygen_args, (unsigned int) keybits, &priv_key_obj);
	if (rc >= 0) {
		id = ((struct sc_pkcs15_prkey_info *) priv_key_obj->data)->id;
		rc = sc_pkcs15_find_pubkey_by_id(fw_data->p15_card, &id, &pub_key_obj);
		if (rc != 0) {
			sc_log(context, "sc_pkcs15_find_pubkey_by_id returned %d", rc);
			rv = sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
			goto kpgen_done;
		}
	}
	else {
		sc_log(context, "sc_pkcs15init_generate_key returned %d", rc);
		rv = sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
		goto kpgen_done;
	}

	/* 4. Create new pkcs11 public and private key object */

	rc = __pkcs15_create_prkey_object(fw_data, priv_key_obj, &priv_any_obj);
	if (rc == 0)
		rc = __pkcs15_create_pubkey_object(fw_data, pub_key_obj, &pub_any_obj);
	if (rc != 0) {
		sc_log(context, "__pkcs15_create_pr/pubkey_object returned %d", rc);
		rv = sc_to_cryptoki_error(rc, "C_GenerateKeyPair");
		goto kpgen_done;
	}
	pkcs15_add_object(slot, priv_any_obj, phPrivKey);
	pkcs15_add_object(slot, pub_any_obj, phPubKey);

	priv_prk_obj = (struct pkcs15_prkey_object *) priv_any_obj;

	priv_prk_obj->prv_pubkey = (struct pkcs15_pubkey_object *)pub_any_obj;

	/* Duplicate public key so that parameters can be retrieved even if public key object is deleted */
	rv = sc_pkcs15_dup_pubkey(context, ((struct pkcs15_pubkey_object *)pub_any_obj)->pub_data, &priv_prk_obj->pub_data);

kpgen_done:
	sc_pkcs15init_unbind(profile);
	sc_unlock(p11card->card);

	return rv;
}
#endif


static CK_RV
pkcs15_skey_destroy(struct sc_pkcs11_session *session, void *object)
{
#ifndef USE_PKCS15_INIT
	return CKR_FUNCTION_NOT_SUPPORTED;
#else
	struct pkcs15_any_object *any_obj = (struct pkcs15_any_object*) object;
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	int rv;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GenerateKeyPair");
	/* TODO assuming this is a session only object. */
	rv = sc_lock(p11card->card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_DestroyObject");

	/* Oppose to pkcs15_add_object */
	--any_obj->refcount; /* correct refcount */
	list_delete(&session->slot->objects, any_obj);
	/* Delete object in pkcs15 */
	rv = __pkcs15_delete_object(fw_data, any_obj);

	sc_unlock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_DestroyObject");

	return CKR_OK;
#endif
}

static CK_RV
pkcs15_any_destroy(struct sc_pkcs11_session *session, void *object)
{
#ifndef USE_PKCS15_INIT
	return CKR_FUNCTION_NOT_SUPPORTED;
#else
	struct pkcs15_data_object *obj = (struct pkcs15_data_object*) object;
	struct pkcs15_any_object *any_obj = (struct pkcs15_any_object*) object;
	struct sc_pkcs11_slot *slot = session->slot;
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_aid *aid = NULL;
	struct sc_profile *profile = NULL;
	int rv;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_DestroyObject");

	rv = sc_lock(p11card->card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_DestroyObject");

	/* Bind the profile */
	rv = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, slot->app_info, &profile);
	if (rv < 0) {
		sc_unlock(p11card->card);
		return sc_to_cryptoki_error(rv, "C_DestroyObject");
	}

	if(slot->app_info)
		aid = &slot->app_info->aid;
	rv = sc_pkcs15init_finalize_profile(p11card->card, profile, aid);
	if (rv) {
		sc_log(context, "Cannot finalize profile: %i", rv);
		return sc_to_cryptoki_error(rv, "C_DestroyObject");
	}

	if (any_obj->related_pubkey)   {
		struct pkcs15_any_object *ao_pubkey = (struct pkcs15_any_object *)any_obj->related_pubkey;
		struct pkcs15_pubkey_object *pubkey = any_obj->related_pubkey;

		/* Check if key is not removed in between */
		if (list_locate(&session->slot->objects, ao_pubkey) > 0) {
			sc_log(context, "Found related pubkey %p", any_obj->related_pubkey);

			/* Delete reference to related certificate of the public key PKCS#11 object */
			pubkey->pub_genfrom = NULL;
			if (ao_pubkey->p15_object == NULL)   {
				sc_log(context, "Found related p15 object %p", ao_pubkey->p15_object);
				/* Unlink related public key FW object if it has no corresponding PKCS#15 object
				 * and was created from certificate. */
				--ao_pubkey->refcount;
				list_delete(&session->slot->objects, ao_pubkey);
				/* Delete public key object in pkcs15 */
				if (pubkey->pub_data)   {
					sc_log(context, "Found pub_data %p", pubkey->pub_data);
					sc_pkcs15_free_pubkey(pubkey->pub_data);
					pubkey->pub_data = NULL;
				}
				__pkcs15_delete_object(fw_data, ao_pubkey);
			}
		}
	}

	/* Delete object in smartcard (if corresponding PKCS#15 object exists) */
	if (obj->base.p15_object)
		rv = sc_pkcs15init_delete_object(fw_data->p15_card, profile, obj->base.p15_object);
	if (rv >= 0) {
		/* Oppose to pkcs15_add_object */
		--any_obj->refcount; /* correct refcount */
		list_delete(&session->slot->objects, any_obj);
		/* Delete object in pkcs15 */
		rv = __pkcs15_delete_object(fw_data, any_obj);
	}

	sc_pkcs15init_unbind(profile);
	sc_unlock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_DestroyObject");

	return CKR_OK;
#endif
}


static CK_RV
pkcs15_get_random(struct sc_pkcs11_slot *slot, CK_BYTE_PTR p, CK_ULONG len)
{
	struct sc_pkcs11_card *p11card = slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	int rc;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GenerateRandom");

	rc = sc_get_challenge(fw_data->p15_card->card, p, (size_t)len);
	return sc_to_cryptoki_error(rc, "C_GenerateRandom");
}


struct sc_pkcs11_framework_ops framework_pkcs15 = {
	pkcs15_bind,
	pkcs15_unbind,
	pkcs15_create_tokens,
	pkcs15_release_token,
	pkcs15_login,
	pkcs15_logout,
	pkcs15_change_pin,
#ifdef USE_PKCS15_INIT
	pkcs15_initialize,
	pkcs15_init_pin,
	pkcs15_create_object,
	pkcs15_gen_keypair,
#else
	NULL,
	NULL,
	NULL,
	NULL,
#endif
	pkcs15_get_random
};


static CK_RV
pkcs15_set_attrib(struct sc_pkcs11_session *session, struct sc_pkcs15_object *p15_object,
		CK_ATTRIBUTE_PTR attr)
{
#ifndef USE_PKCS15_INIT
	return CKR_FUNCTION_NOT_SUPPORTED;
#else
	struct sc_profile *profile = NULL;
	struct sc_pkcs11_slot *slot = session->slot;
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_aid *aid = NULL;
	struct sc_pkcs15_id id;
	int rv = 0;
	CK_RV ck_rv = CKR_OK;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_SetAttributeValue");

	rv = sc_lock(p11card->card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_SetAttributeValue");

	rv = sc_pkcs15init_bind(p11card->card, "pkcs15", NULL, slot->app_info, &profile);
	if (rv < 0) {
		sc_log(context, "C_SetAttributeValue: pkcs15init bind failed: %i", rv);
		sc_unlock(p11card->card);
		return sc_to_cryptoki_error(rv, "C_SetAttributeValue");
	}

	if(slot->app_info)
		aid = &slot->app_info->aid;

	rv = sc_pkcs15init_finalize_profile(p11card->card, profile, aid);
	if (rv != CKR_OK) {
		sc_log(context, "C_SetAttributeValue: cannot finalize profile: %i", rv);
		sc_unlock(p11card->card);
		return sc_to_cryptoki_error(rv, "C_SetAttributeValue");
	}

	switch(attr->type) {
	case CKA_LABEL:
		rv = sc_pkcs15init_change_attrib(fw_data->p15_card, profile, p15_object,
				P15_ATTR_TYPE_LABEL, attr->pValue, (unsigned int) attr->ulValueLen);
		break;
	case CKA_ID:
		if (attr->ulValueLen > SC_PKCS15_MAX_ID_SIZE) {
			rv = SC_ERROR_INVALID_ARGUMENTS;
			break;
		}
		memcpy(id.value, attr->pValue, attr->ulValueLen);
		id.len = attr->ulValueLen;
		rv = sc_pkcs15init_change_attrib(fw_data->p15_card, profile, p15_object,
				P15_ATTR_TYPE_ID, &id, sizeof(id));
		break;
	case CKA_SUBJECT:
		rv = SC_SUCCESS;
		break;
	case CKA_VALUE:
		if ((p15_object->type & SC_PKCS15_TYPE_CLASS_MASK) != SC_PKCS15_TYPE_DATA_OBJECT) {
			ck_rv = CKR_ATTRIBUTE_READ_ONLY;
			goto set_attr_done;
		}
		rv = sc_pkcs15init_change_attrib(fw_data->p15_card, profile, p15_object, 
				P15_ATTR_TYPE_VALUE, attr->pValue, (unsigned int) attr->ulValueLen);
		break;
	default:
		ck_rv = CKR_ATTRIBUTE_READ_ONLY;
		goto set_attr_done;
	}

	ck_rv = sc_to_cryptoki_error(rv, "C_SetAttributeValue");

set_attr_done:
	sc_pkcs15init_unbind(profile);
	sc_unlock(p11card->card);

	return ck_rv;
#endif
}

/*
 * PKCS#15 Certificate Object
 */
static void
pkcs15_cert_release(void *obj)
{
	struct pkcs15_cert_object *cert = (struct pkcs15_cert_object *) obj;
	struct sc_pkcs15_cert      *cert_data = cert->cert_data;

	if (__pkcs15_release_object((struct pkcs15_any_object *) obj) == 0)
		if (cert_data) /* may never have been read */
			sc_pkcs15_free_certificate(cert_data);
}


static CK_RV
pkcs15_cert_set_attribute(struct sc_pkcs11_session *session, void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_cert_object *cert = (struct pkcs15_cert_object*) object;
	return pkcs15_set_attrib(session, cert->base.p15_object, attr);
}


static CK_RV
pkcs15_cert_get_attribute(struct sc_pkcs11_session *session, void *object, CK_ATTRIBUTE_PTR attr)
{
	struct sc_pkcs11_card *p11card = NULL;
	struct pkcs15_cert_object *cert = (struct pkcs15_cert_object*) object;
	struct pkcs15_fw_data *fw_data = NULL;
	size_t len;

	sc_log(context, "pkcs15_cert_get_attribute() called");
	p11card = session->slot->p11card;
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");

	switch (attr->type) {
	case CKA_CLASS:
		check_attribute_buffer(attr, sizeof(CK_OBJECT_CLASS));
		*(CK_OBJECT_CLASS*)attr->pValue = CKO_CERTIFICATE;
		break;
	case CKA_TOKEN:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = TRUE;
		break;
	case CKA_PRIVATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (cert->base.p15_object->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0;
		break;
	case CKA_MODIFIABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = FALSE;
		break;
	case CKA_LABEL:
		if (check_cert_data_read(fw_data, cert) != 0) {
			attr->ulValueLen = 0;
			return CKR_OK;
		}
		len = strnlen(cert->cert_p15obj->label, sizeof cert->cert_p15obj->label);
		check_attribute_buffer(attr, len);
		memcpy(attr->pValue, cert->cert_p15obj->label, len);
		break;
	case CKA_CERTIFICATE_TYPE:
		check_attribute_buffer(attr, sizeof(CK_CERTIFICATE_TYPE));
		*(CK_CERTIFICATE_TYPE*)attr->pValue = CKC_X_509;
		break;
	case CKA_ID:
#ifdef ZERO_CKAID_FOR_CA_CERTS
		if (cert->cert_info->authority) {
			check_attribute_buffer(attr, 1);
			*(unsigned char*)attr->pValue = 0;
			break;
		}
#endif
		check_attribute_buffer(attr, cert->cert_info->id.len);
		memcpy(attr->pValue, cert->cert_info->id.value, cert->cert_info->id.len);
		break;
	case CKA_TRUSTED:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = cert->cert_info->authority ? TRUE : FALSE;
		break;
	case CKA_VALUE:
		if (check_cert_data_read(fw_data, cert) != 0) {
			attr->ulValueLen = 0;
			return CKR_OK;
		}
		check_attribute_buffer(attr, cert->cert_data->data.len);
		memcpy(attr->pValue, cert->cert_data->data.value, cert->cert_data->data.len);
		break;
	case CKA_SERIAL_NUMBER:
		if (check_cert_data_read(fw_data, cert) != 0) {
			attr->ulValueLen = 0;
			return CKR_OK;
		}
		check_attribute_buffer(attr, cert->cert_data->serial_len);
		memcpy(attr->pValue, cert->cert_data->serial, cert->cert_data->serial_len);
		break;
	case CKA_SUBJECT:
		if (check_cert_data_read(fw_data, cert) != 0) {
			attr->ulValueLen = 0;
			return CKR_OK;
		}
		check_attribute_buffer(attr, cert->cert_data->subject_len);
		memcpy(attr->pValue, cert->cert_data->subject, cert->cert_data->subject_len);
		return CKR_OK;
	case CKA_ISSUER:
		if (check_cert_data_read(fw_data, cert) != 0) {
			attr->ulValueLen = 0;
			return CKR_OK;
		}
		check_attribute_buffer(attr, cert->cert_data->issuer_len);
		memcpy(attr->pValue, cert->cert_data->issuer, cert->cert_data->issuer_len);
		return CKR_OK;
	default:
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	return CKR_OK;
}


#define ASN1_SET_TAG (SC_ASN1_SET | SC_ASN1_TAG_CONSTRUCTED)
#define ASN1_SEQ_TAG (SC_ASN1_SEQUENCE | SC_ASN1_TAG_CONSTRUCTED)
static CK_RV
pkcs15_cert_cmp_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_cert_object *cert = (struct pkcs15_cert_object*) object;
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	const unsigned char *data = NULL, *_data = NULL;
	size_t	len, _len;

	sc_log(context, "pkcs15_cert_cmp_attribute() called");
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)   {
		sc_log(context, "pkcs15_cert_cmp_attribute() returns SC_ERROR_INTERNAL");
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");
	}

	switch (attr->type) {
	/* Check the issuer/subject. Some pkcs11 callers (i.e. netscape) will pass
	 * in the ASN.1 encoded SEQUENCE OF SET,
	 * while OpenSC just keeps the SET in the issuer/subject field. */
	case CKA_ISSUER:
		if (check_cert_data_read(fw_data, cert) != 0)
			break;
		if (cert->cert_data->issuer_len == 0)
			break;

		data = _data = (u8 *) attr->pValue;
		len = _len = attr->ulValueLen;
		if (cert->cert_data->issuer[0] == ASN1_SET_TAG && data[0] == ASN1_SEQ_TAG && len >= 2)
			data = sc_asn1_skip_tag(context, &_data, &_len, SC_ASN1_CONS | SC_ASN1_TAG_SEQUENCE, &len);

		if (len == cert->cert_data->issuer_len && !memcmp(cert->cert_data->issuer, data, len))   {
			sc_log(context, "pkcs15_cert_cmp_attribute() returns CKA_ISSUER matched");
			return 1;
		}
		break;
	case CKA_SUBJECT:
		if (check_cert_data_read(fw_data, cert) != 0)
			break;
		if (cert->cert_data->subject_len == 0)
			break;

		data = _data = (u8 *) attr->pValue;
		len = _len = attr->ulValueLen;
		if (cert->cert_data->subject[0] == ASN1_SET_TAG && data[0] == ASN1_SEQ_TAG && len >= 2)
			data = sc_asn1_skip_tag(context, &_data, &_len, SC_ASN1_CONS | SC_ASN1_TAG_SEQUENCE, &len);

		if (len == cert->cert_data->subject_len && !memcmp(cert->cert_data->subject, data, len))   {
			sc_log(context, "pkcs15_cert_cmp_attribute() returns CKA_SUBJECT matched");
			return 1;
		}
		break;
	default:
		return sc_pkcs11_any_cmp_attribute(session, object, attr);
	}
	sc_log(context, "pkcs15_cert_cmp_attribute() returns not matched");
	return 0;
}

struct sc_pkcs11_object_ops pkcs15_cert_ops = {
	pkcs15_cert_release,
	pkcs15_cert_set_attribute,
	pkcs15_cert_get_attribute,
	pkcs15_cert_cmp_attribute,
	pkcs15_any_destroy,
	NULL,	/* get_size */
	NULL,	/* sign */
	NULL,	/* unwrap_key */
	NULL,	/* decrypt */
	NULL,	/* derive */
	NULL,	/* can_do */
	NULL,	/* init_params */
	NULL	/* wrap_key */
};

/*
 * PKCS#15 Private Key Object
 */
static void pkcs15_prkey_release(void *object)
{
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object*) object;
	struct sc_pkcs15_pubkey *key_data = prkey->pub_data;

	if (__pkcs15_release_object((struct pkcs15_any_object *) object) == 0)
		if (key_data)
			sc_pkcs15_free_pubkey(key_data);
}

static CK_RV pkcs15_prkey_set_attribute(struct sc_pkcs11_session *session,
                               void *object,
                               CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object*) object;
	return pkcs15_set_attrib(session, prkey->base.p15_object, attr);
}


static CK_RV
pkcs15_prkey_get_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object*) object;
	struct sc_pkcs11_card *p11card = NULL;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_pkcs15_pubkey *key = NULL;
	unsigned int usage;
	size_t len;

	sc_log(context, "pkcs15_prkey_get_attribute() called");
	p11card = session->slot->p11card;
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");

	/* PKCS#11 requires us to supply CKA_MODULUS for private keys,
	 * although that is not generally available from a smart card
	 * (the key is supposed to be safely locked away after all).
	 *
	 * To work around this, we hope that we either have an associated
	 * public key, or we try to find a certificate with the
	 * corresponding public key.
	 *
	 * Note: We do the same thing for CKA_PUBLIC_EXPONENT as some
	 *       applications assume they can get that from the private
	 *       key, something PKCS#11 doesn't guarantee.
	 */
	if ((attr->type == CKA_MODULUS) || (attr->type == CKA_PUBLIC_EXPONENT) ||
		((attr->type == CKA_MODULUS_BITS) && (prkey->prv_p15obj->type == SC_PKCS15_TYPE_PRKEY_EC)) ||
		(attr->type == CKA_ECDSA_PARAMS)) {
		/* First see if we have an associated public key */
		if (prkey->pub_data) {
			key = prkey->pub_data;
		} else {
			/* Try to find public key or certificate with the public key */
			unsigned int i;

			for (i = 0; i < fw_data->num_objects; i++) {
				struct pkcs15_any_object *obj = fw_data->objects[i];
				struct pkcs15_cert_object *cert;

				if (is_cert(obj))   {
					cert = (struct pkcs15_cert_object*) obj;

					if (cert->cert_prvkey != prkey)
						continue;

					if (check_cert_data_read(fw_data, cert) == 0)   {
						key = cert->cert_pubkey->pub_data;
						sc_log(context, "found friend certificate's public key %p", key);
					}
				}
				else if (is_pubkey(obj)) {
					struct pkcs15_pubkey_object *pubkey = (struct pkcs15_pubkey_object *) obj;

					if (!pubkey->pub_data)
						continue;

					if (sc_pkcs15_compare_id(&pubkey->pub_info->id, &prkey->prv_info->id))   {
						prkey->prv_pubkey = pubkey;
						key = pubkey->pub_data;
						sc_log(context, "found friend public key %p", key);
					}
				}
			}
		}
	}

	switch (attr->type) {
	case CKA_CLASS:
		check_attribute_buffer(attr, sizeof(CK_OBJECT_CLASS));
		*(CK_OBJECT_CLASS*)attr->pValue = CKO_PRIVATE_KEY;
		break;
	case CKA_TOKEN:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = TRUE;
		break;
	case CKA_ALWAYS_SENSITIVE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (prkey->prv_info->access_flags & SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE) != 0;
		break;
	case CKA_NEVER_EXTRACTABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (prkey->prv_info->access_flags & SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE) != 0;
		break;
	case CKA_SENSITIVE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (prkey->prv_info->access_flags & SC_PKCS15_PRKEY_ACCESS_SENSITIVE) != 0;
		break;
	case CKA_LOCAL:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (prkey->prv_info->access_flags & SC_PKCS15_PRKEY_ACCESS_LOCAL) != 0;
		break;
    case CKA_ALWAYS_AUTHENTICATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = prkey->prv_p15obj->user_consent >= 1 ? CK_TRUE : CK_FALSE;
		break;
	case CKA_PRIVATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (prkey->prv_p15obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0;
		break;
	case CKA_MODIFIABLE:
	case CKA_EXTRACTABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = FALSE;
		break;
	case CKA_LABEL:
		len = strnlen(prkey->prv_p15obj->label, sizeof prkey->prv_p15obj->label);
		check_attribute_buffer(attr, len);
		memcpy(attr->pValue, prkey->prv_p15obj->label, len);
		break;
	case CKA_KEY_TYPE:
		check_attribute_buffer(attr, sizeof(CK_KEY_TYPE));
		switch (prkey->prv_p15obj->type) {
			case SC_PKCS15_TYPE_PRKEY_RSA:
				*(CK_KEY_TYPE*)attr->pValue = CKK_RSA;
				break;
			case SC_PKCS15_TYPE_PRKEY_GOSTR3410:
				*(CK_KEY_TYPE*)attr->pValue = CKK_GOSTR3410;
				break;
			case SC_PKCS15_TYPE_PRKEY_EC:
				*(CK_KEY_TYPE*)attr->pValue = CKK_EC;
				break;
			default:
				return CKR_GENERAL_ERROR; /* Internal error*/
		}
		break;
	case CKA_ID:
		check_attribute_buffer(attr, prkey->prv_info->id.len);
		memcpy(attr->pValue, prkey->prv_info->id.value, prkey->prv_info->id.len);
		break;
	case CKA_KEY_GEN_MECHANISM:
		check_attribute_buffer(attr, sizeof(CK_MECHANISM_TYPE));
		*(CK_MECHANISM_TYPE*)attr->pValue = CK_UNAVAILABLE_INFORMATION;
		break;
	case CKA_DECRYPT:
	case CKA_SIGN:
	case CKA_SIGN_RECOVER:
	case CKA_UNWRAP:
	case CKA_DERIVE:
	case CKA_OPENSC_NON_REPUDIATION:
		/* TODO seems to be obsolete */
		/* Combine the usage bits of all split keys */
		for (usage = 0; prkey; prkey = prkey->prv_next)
			usage |= prkey->prv_info->usage;
		return get_usage_bit(usage, attr);
	case CKA_MODULUS:
		return get_modulus(key, attr);
	case CKA_MODULUS_BITS:
		check_attribute_buffer(attr, sizeof(CK_ULONG));
		switch (prkey->prv_p15obj->type) {
			case SC_PKCS15_TYPE_PRKEY_EC:
				if (key) {
					if (key->u.ec.params.field_length > 0)
						*(CK_ULONG *) attr->pValue = key->u.ec.params.field_length;
					else
						*(CK_ULONG *) attr->pValue = (key->u.ec.ecpointQ.len - 1) / 2 *8;
				}
				return CKR_OK;
			default:
				*(CK_ULONG *) attr->pValue = prkey->prv_info->modulus_length;
				return CKR_OK;
		}
	case CKA_PUBLIC_EXPONENT:
		return get_public_exponent(key, attr);
	case CKA_PRIVATE_EXPONENT:
	case CKA_PRIME_1:
	case CKA_PRIME_2:
	case CKA_EXPONENT_1:
	case CKA_EXPONENT_2:
	case CKA_COEFFICIENT:
		return CKR_ATTRIBUTE_SENSITIVE;
	case CKA_SUBJECT:
	case CKA_START_DATE:
	case CKA_END_DATE:
		attr->ulValueLen = 0;
		return CKR_OK;
	case CKA_GOSTR3410_PARAMS:
		if (prkey->prv_info && prkey->prv_info->params.len)
			return get_gostr3410_params(prkey->prv_info->params.data,
					prkey->prv_info->params.len, attr);
		else
			return CKR_ATTRIBUTE_TYPE_INVALID;
	case CKA_EC_PARAMS:
		return get_ec_pubkey_params(key, attr); /* get from pubkey for now */
	default:
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	return CKR_OK;
}



static CK_RV
pkcs15_prkey_check_pss_param(CK_MECHANISM_PTR pMechanism, CK_ULONG hlen)
{
	CK_RSA_PKCS_PSS_PARAMS *pss_param;
	int i;
	const unsigned int hash_lens[5] = { 160, 256, 385, 512, 224 };
	const unsigned int hashes[5] = { CKM_SHA_1, CKM_SHA256,
		CKM_SHA384, CKM_SHA512, CKM_SHA224 };

	pss_param = (CK_RSA_PKCS_PSS_PARAMS *)pMechanism->pParameter;

	// Hash parameter must match length of data supplied for CKM_RSA_PKCS_PSS
	for (i = 0; i < 5; i++) {
		if (pss_param->hashAlg == hashes[i]
			&& hlen != hash_lens[i]/8)
			return CKR_MECHANISM_PARAM_INVALID;
	}
	/* other aspects of pss params were already verified during SignInit */

	return CKR_OK;
}

static int mgf2flags(CK_RSA_PKCS_MGF_TYPE mgf)
{
	switch (mgf) {
	case CKG_MGF1_SHA224:
		return SC_ALGORITHM_MGF1_SHA224;
		break;
	case CKG_MGF1_SHA256:
		return SC_ALGORITHM_MGF1_SHA256;
	case CKG_MGF1_SHA384:
		return SC_ALGORITHM_MGF1_SHA384;
	case CKG_MGF1_SHA512:
		return SC_ALGORITHM_MGF1_SHA512;
	case CKG_MGF1_SHA1:
		return SC_ALGORITHM_MGF1_SHA1;
	default:
		return -1;
	}
}


static CK_RV
pkcs15_prkey_sign(struct sc_pkcs11_session *session, void *obj,
			CK_MECHANISM_PTR pMechanism, CK_BYTE_PTR pData,
			CK_ULONG ulDataLen, CK_BYTE_PTR pSignature,
			CK_ULONG_PTR pulDataLen)
{
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object *) obj;
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	CK_RV rv;
	int flags = 0, prkey_has_path = 0, rc;
	unsigned sign_flags = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER
			| SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;

	sc_log(context, "Initiating signing operation, mechanism 0x%lx.",
		   pMechanism->mechanism);
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_Sign");

	/* See which of the alternative keys supports signing */
	while (prkey && !(prkey->prv_info->usage & sign_flags))
		prkey = prkey->prv_next;

	if (prkey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	if (prkey->prv_info->path.len || prkey->prv_info->path.aid.len)
		prkey_has_path = 1;

	switch (pMechanism->mechanism) {
	case CKM_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_NONE;
		break;
	case CKM_MD5_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_MD5;
		break;
	case CKM_SHA1_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA1;
		break;
	case CKM_SHA224_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA224;
		break;
	case CKM_SHA256_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA256;
		break;
	case CKM_SHA384_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA384;
		break;
	case CKM_SHA512_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA512;
		break;
	case CKM_RIPEMD160_RSA_PKCS:
		flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_RIPEMD160;
		break;
	case CKM_RSA_X_509:
		flags = SC_ALGORITHM_RSA_RAW;
		break;
	case CKM_RSA_PKCS_PSS:
		flags = SC_ALGORITHM_RSA_PAD_PSS;
		/* The hash was done ouside of the module */
		flags |= SC_ALGORITHM_RSA_HASH_NONE;
		/* Omited parameter can use MGF1-SHA1 ? */
		if (pMechanism->pParameter == NULL) {
			flags |= SC_ALGORITHM_MGF1_SHA1;
			if (ulDataLen != SHA_DIGEST_LENGTH)
				return CKR_MECHANISM_PARAM_INVALID;
			break;
		}

		/* Check the data length matches the selected hash */
		rv = pkcs15_prkey_check_pss_param(pMechanism, (int)ulDataLen);
		if (rv != CKR_OK) {
			sc_log(context, "Invalid data lenght for the selected "
			    "PSS parameters");
			return rv;
		}

		/* The MGF parameter was already verified in SignInit() */
		flags |=  mgf2flags(((CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter)->mgf);

		/* Assuming salt is the size of hash */
		break;
	case CKM_SHA1_RSA_PKCS_PSS:
	case CKM_SHA224_RSA_PKCS_PSS:
	case CKM_SHA256_RSA_PKCS_PSS:
	case CKM_SHA384_RSA_PKCS_PSS:
	case CKM_SHA512_RSA_PKCS_PSS:
		flags = SC_ALGORITHM_RSA_PAD_PSS;
		/* Omited parameter can use MGF1-SHA1 and SHA1 hash ? */
		if (pMechanism->pParameter == NULL) {
			flags |= SC_ALGORITHM_RSA_HASH_SHA1;
			flags |= SC_ALGORITHM_MGF1_SHA1;
			break;
		}

		switch (((CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter)->hashAlg) {
		case CKM_SHA_1:
			flags |= SC_ALGORITHM_RSA_HASH_SHA1;
			break;
		case CKM_SHA224:
			flags |= SC_ALGORITHM_RSA_HASH_SHA224;
			break;
		case CKM_SHA256:
			flags |= SC_ALGORITHM_RSA_HASH_SHA256;
			break;
		case CKM_SHA384:
			flags |= SC_ALGORITHM_RSA_HASH_SHA384;
			break;
		case CKM_SHA512:
			flags |= SC_ALGORITHM_RSA_HASH_SHA512;
			break;
		default:
			return CKR_MECHANISM_PARAM_INVALID;
		}

		/* The MGF parameter was already verified in SignInit() */
		flags |= mgf2flags(((CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter)->mgf);

		/* Assuming salt is the size of hash */
		break;
	case CKM_GOSTR3410:
		flags = SC_ALGORITHM_GOSTR3410_HASH_NONE;
		break;
	case CKM_GOSTR3410_WITH_GOSTR3411:
		flags = SC_ALGORITHM_GOSTR3410_HASH_GOSTR3411;
		break;
	case CKM_ECDSA:
		flags = SC_ALGORITHM_ECDSA_HASH_NONE;
		break;
	case CKM_ECDSA_SHA1:
		flags = SC_ALGORITHM_ECDSA_HASH_SHA1;
		break;
	default:
		sc_log(context, "DEE - need EC for %lu", pMechanism->mechanism);
		return CKR_MECHANISM_INVALID;
	}

	rc = sc_lock(p11card->card);
	if (rc < 0)
		return sc_to_cryptoki_error(rc, "C_Sign");

	sc_log(context,
	       "Selected flags %X. Now computing signature for %lu bytes. %lu bytes reserved.",
	       flags, ulDataLen, *pulDataLen);
	rc = sc_pkcs15_compute_signature(fw_data->p15_card, prkey->prv_p15obj, flags,
			pData, ulDataLen, pSignature, *pulDataLen);
	if (rc < 0 && !sc_pkcs11_conf.lock_login && !prkey_has_path) {
		/* If private key PKCS#15 object do not have 'path' attribute,
		 * and if PKCS#11 login session is not locked,
		 * the compute signature could fail because of concurrent access to the card
		 * by other application that could change the current DF.
		 * In this particular case try to 'reselect' application DF.
		 */
		if (reselect_app_df(fw_data->p15_card) == SC_SUCCESS)
			rc = sc_pkcs15_compute_signature(fw_data->p15_card, prkey->prv_p15obj, flags,
					pData, ulDataLen, pSignature, *pulDataLen);
	}

	sc_unlock(p11card->card);

	sc_log(context, "Sign complete. Result %d.", rc);

	if (rc > 0) {
		*pulDataLen = rc;
		return CKR_OK;
	}

	return sc_to_cryptoki_error(rc, "C_Sign");
}


static CK_RV
pkcs15_prkey_unwrap(struct sc_pkcs11_session *session, void *obj,
			CK_MECHANISM_PTR pMechanism, CK_BYTE_PTR pWrappedKey,
			CK_ULONG ulWrappedKeyLen,
			void *targetKey)
{
	struct	sc_pkcs11_card *p11card = session->slot->p11card;
	struct	pkcs15_fw_data *fw_data = NULL;
	struct	pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object *) obj;
	struct	pkcs15_any_object *targetKeyObj = (struct pkcs15_any_object *) targetKey;
	int	rv;	

	sc_log(context, "Initiating unwrapping with private key.");

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_UnwrapKey");

	if (pMechanism == NULL || pWrappedKey == NULL || ulWrappedKeyLen == 0 || targetKeyObj == NULL) {
		sc_log(context, "One or more of mandatory arguments were NULL.");
	    return CKR_ARGUMENTS_BAD;
	}

	/* See which of the alternative keys supports unwrap */
	while (prkey && !(prkey->prv_info->usage & SC_PKCS15_PRKEY_USAGE_UNWRAP))
		prkey = prkey->prv_next;

	if (prkey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	sc_log(context, "Using mechanism %lx.", pMechanism->mechanism);

#if 0
	/* FIXME https://github.com/OpenSC/OpenSC/issues/1595 */
	/* Select the proper padding mechanism */
	switch (pMechanism->mechanism) {
	case CKM_RSA_PKCS:
		flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
		break;
	case CKM_RSA_X_509:
		flags |= SC_ALGORITHM_RSA_RAW;
		break;
	default:
		return CKR_MECHANISM_INVALID;
	}
#endif

	rv = sc_lock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	/* Call the card to do the unwrap operation */
	rv = sc_pkcs15_unwrap(fw_data->p15_card, prkey->prv_p15obj, targetKeyObj->p15_object, 0,
		pWrappedKey, ulWrappedKeyLen, NULL, 0);

	sc_unlock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	return CKR_OK;
}

static CK_RV
pkcs15_prkey_decrypt(struct sc_pkcs11_session *session, void *obj,
		CK_MECHANISM_PTR pMechanism,
		CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
		CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct pkcs15_prkey_object *prkey;
	unsigned char decrypted[512]; /* FIXME: Will not work for keys above 4096 bits */
	int	buff_too_small, rv, flags = 0, prkey_has_path = 0;

	sc_log(context, "Initiating decryption.");

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_Decrypt");

	/* See which of the alternative keys supports decrypt */
	prkey = (struct pkcs15_prkey_object *) obj;
	while (prkey  && !(prkey->prv_info->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT|SC_PKCS15_PRKEY_USAGE_UNWRAP)))
		prkey = prkey->prv_next;
	if (prkey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	if (prkey->prv_info->path.len || prkey->prv_info->path.aid.len)
		prkey_has_path = 1;

	/* Select the proper padding mechanism */
	switch (pMechanism->mechanism) {
	case CKM_RSA_PKCS:
		flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
		break;
	case CKM_RSA_X_509:
		flags |= SC_ALGORITHM_RSA_RAW;
		break;
	default:
		return CKR_MECHANISM_INVALID;
	}

	rv = sc_lock(p11card->card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_Decrypt");

	rv = sc_pkcs15_decipher(fw_data->p15_card, prkey->prv_p15obj, flags,
			pEncryptedData, ulEncryptedDataLen, decrypted, sizeof(decrypted));

	if (rv < 0 && !sc_pkcs11_conf.lock_login && !prkey_has_path)
		if (reselect_app_df(fw_data->p15_card) == SC_SUCCESS)
			rv = sc_pkcs15_decipher(fw_data->p15_card, prkey->prv_p15obj, flags,
					pEncryptedData, ulEncryptedDataLen, decrypted, sizeof(decrypted));

	sc_unlock(p11card->card);

	sc_log(context, "Decryption complete. Result %d.", rv);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_Decrypt");

	buff_too_small = (*pulDataLen < (CK_ULONG)rv);
	*pulDataLen = rv;
	if (pData == NULL_PTR)
		return CKR_OK;
	if (buff_too_small)
		return CKR_BUFFER_TOO_SMALL;
	memcpy(pData, decrypted, *pulDataLen);

	return CKR_OK;
}


static CK_RV
pkcs15_prkey_derive(struct sc_pkcs11_session *session, void *obj,
		CK_MECHANISM_PTR pMechanism,
		CK_BYTE_PTR pParameters, CK_ULONG ulParametersLen,
		CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object *) obj;
	int	need_unlock = 0, prkey_has_path = 0;
	int	rv, flags = 0;
	CK_BYTE_PTR pSeedData = NULL;
	CK_ULONG ulSeedDataLen = 0;

	sc_log(context, "Initiating derivation");

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_DeriveKey");

	/* See which of the alternative keys supports derivation */
	while (prkey && !(prkey->prv_info->usage & SC_PKCS15_PRKEY_USAGE_DERIVE))
		prkey = prkey->prv_next;

	if (prkey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	if (prkey->prv_info->path.len || prkey->prv_info->path.aid.len)
		prkey_has_path = 1;

	if (pData != NULL && *pulDataLen > 0) { /* TODO DEE only test for NULL? */
		need_unlock = 1;
		rv = sc_lock(p11card->card);
		if (rv < 0)
			return sc_to_cryptoki_error(rv, "C_DeriveKey");
	}

	/* TODO DEE This may not be the place to get the parameters,
	 * But its the last PKCS11 aware routine.
	 * RSA parameters would be null.
	 */
	switch (prkey->base.p15_object->type) {
		case SC_PKCS15_TYPE_PRKEY_EC:
		{
			CK_ECDH1_DERIVE_PARAMS * ecdh_params = (CK_ECDH1_DERIVE_PARAMS *) pParameters;
			ulSeedDataLen = ecdh_params->ulPublicDataLen;
			pSeedData = ecdh_params->pPublicData;
			flags = SC_ALGORITHM_ECDH_CDH_RAW;
		}
		break;
	}

	size_t len = *pulDataLen;
	rv = sc_pkcs15_derive(fw_data->p15_card, prkey->prv_p15obj, flags,
			pSeedData, ulSeedDataLen, pData, &len);
	if (rv < 0 && !sc_pkcs11_conf.lock_login && !prkey_has_path && need_unlock)
		if (reselect_app_df(fw_data->p15_card) == SC_SUCCESS)
			rv = sc_pkcs15_derive(fw_data->p15_card, prkey->prv_p15obj, flags,
					pSeedData, ulSeedDataLen, pData, &len);
	*pulDataLen = len;

	/* this may have been a request for size */

	if (need_unlock)
		sc_unlock(p11card->card);

	sc_log(context, "Derivation complete. Result %d.", rv);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_DeriveKey");

	return CKR_OK;
}


static CK_RV
pkcs15_prkey_can_do(struct sc_pkcs11_session *session, void *obj,
		CK_MECHANISM_TYPE mech_type, unsigned int flags)
{
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct pkcs15_prkey_object *prkey = (struct pkcs15_prkey_object *) obj;
	struct sc_pkcs15_prkey_info *pkinfo = NULL;
	struct sc_supported_algo_info *token_algos = NULL;
	int ii, jj;

	if (!prkey || !prkey->prv_info)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	pkinfo = prkey->prv_info;
	/* Return in there are no usage algorithms specified for this key. */
	if (!pkinfo->algo_refs[0])
		return CKR_FUNCTION_NOT_SUPPORTED;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	token_algos = &fw_data->p15_card->tokeninfo->supported_algos[0];

	for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && pkinfo->algo_refs[ii];ii++)   {
		/* Look for algorithm supported by token referenced in the list of key's algorithms */
		for (jj=0;jj<SC_MAX_SUPPORTED_ALGORITHMS && (token_algos + jj)->reference; jj++)
			if (pkinfo->algo_refs[ii] == (token_algos + jj)->reference)
				break;
		if ((jj == SC_MAX_SUPPORTED_ALGORITHMS) || !(token_algos + jj)->reference)
			return CKR_GENERAL_ERROR;

		if ((token_algos + jj)->mechanism != mech_type)
			continue;

		if (flags == CKF_SIGN)
			if ((token_algos + jj)->operations & SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE)
				break;

		if (flags == CKF_DECRYPT)
			if ((token_algos + jj)->operations & SC_PKCS15_ALGO_OP_DECIPHER)
				break;
	}

	if (ii == SC_MAX_SUPPORTED_ALGORITHMS || !pkinfo->algo_refs[ii])
		return CKR_MECHANISM_INVALID;

	return CKR_OK;
}


static CK_RV
pkcs15_prkey_init_params(struct sc_pkcs11_session *session,
			CK_MECHANISM_PTR pMechanism)
{
	const CK_RSA_PKCS_PSS_PARAMS *pss_params;
	unsigned int expected_hash = 0, i;
	unsigned int expected_salt_len = 0;
	const unsigned int salt_lens[5] = { 160, 256, 384, 512, 224 };
	const unsigned int hashes[5] = { CKM_SHA_1, CKM_SHA256,
		CKM_SHA384, CKM_SHA512, CKM_SHA224 };

	switch (pMechanism->mechanism) {
	case CKM_RSA_PKCS_PSS:
	case CKM_SHA1_RSA_PKCS_PSS:
	case CKM_SHA224_RSA_PKCS_PSS:
	case CKM_SHA256_RSA_PKCS_PSS:
	case CKM_SHA384_RSA_PKCS_PSS:
	case CKM_SHA512_RSA_PKCS_PSS:
		if (!pMechanism->pParameter ||
			pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS))
			return CKR_MECHANISM_PARAM_INVALID;

		pss_params = (CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter;
		if (pss_params->mgf < CKG_MGF1_SHA1 || pss_params->mgf > CKG_MGF1_SHA224)
			return CKR_MECHANISM_PARAM_INVALID;

		/* The hashAlg field can have any value for CKM_RSA_PKCS_PSS and must be
		 * used again in the PSS padding; for the other mechanisms it strictly
		 * must match the padding declared in the mechanism.
		 */
		if (pMechanism->mechanism == CKM_SHA1_RSA_PKCS_PSS) {
			expected_hash = CKM_SHA_1;
			expected_salt_len = 160;
		} else if (pMechanism->mechanism == CKM_SHA224_RSA_PKCS_PSS) {
			expected_hash = CKM_SHA224;
			expected_salt_len = 224;
		} else if (pMechanism->mechanism == CKM_SHA256_RSA_PKCS_PSS) {
			expected_hash = CKM_SHA256;
			expected_salt_len = 256;
		} else if (pMechanism->mechanism == CKM_SHA384_RSA_PKCS_PSS) {
			expected_hash = CKM_SHA384;
			expected_salt_len = 384;
		} else if (pMechanism->mechanism == CKM_SHA512_RSA_PKCS_PSS) {
			expected_hash = CKM_SHA512;
			expected_salt_len = 512;
		} else if (pMechanism->mechanism == CKM_RSA_PKCS_PSS) {
			for (i = 0; i < 5; ++i) {
				if (hashes[i] == pss_params->hashAlg) {
					expected_hash = hashes[i];
					expected_salt_len = salt_lens[i];
				}
			}
		}

		if (expected_hash != pss_params->hashAlg)
			return CKR_MECHANISM_PARAM_INVALID;

		/* We're strict, and only do PSS signatures with a salt length that
		 * matches the digest length (any shorter is rubbish, any longer
		 * is useless). */
		if (pss_params->sLen != expected_salt_len / 8)
			return CKR_MECHANISM_PARAM_INVALID;

		/* TODO support different salt lengths */
		break;
	}
	return CKR_OK;
}


struct sc_pkcs11_object_ops pkcs15_prkey_ops = {
	pkcs15_prkey_release,
	pkcs15_prkey_set_attribute,
	pkcs15_prkey_get_attribute,
	sc_pkcs11_any_cmp_attribute,
	pkcs15_any_destroy,
	NULL,	/* get_size */
	pkcs15_prkey_sign,
	pkcs15_prkey_unwrap,
	pkcs15_prkey_decrypt,
	pkcs15_prkey_derive,
	pkcs15_prkey_can_do,
	pkcs15_prkey_init_params,
	NULL	/* wrap_key */
};

/*
 * PKCS#15 RSA Public Key Object
 */
static void
pkcs15_pubkey_release(void *object)
{
	struct pkcs15_pubkey_object *pubkey = (struct pkcs15_pubkey_object*) object;
	struct sc_pkcs15_pubkey *key_data = pubkey->pub_data;

	if (__pkcs15_release_object((struct pkcs15_any_object *) object) == 0)
		if (key_data)
			sc_pkcs15_free_pubkey(key_data);
}


static CK_RV
pkcs15_pubkey_set_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_pubkey_object *pubkey = (struct pkcs15_pubkey_object*) object;
	return pkcs15_set_attrib(session, pubkey->base.p15_object, attr);
}


static CK_RV
pkcs15_pubkey_get_attribute(struct sc_pkcs11_session *session, void *object, CK_ATTRIBUTE_PTR attr)
{
	struct sc_pkcs11_card *p11card = NULL;
	struct pkcs15_pubkey_object *pubkey = (struct pkcs15_pubkey_object*) object;
	struct pkcs15_cert_object *cert = NULL;
	struct pkcs15_fw_data *fw_data = NULL;
	size_t len;

	sc_log(context, "pkcs15_pubkey_get_attribute() called");

	p11card = session->slot->p11card;
	cert = pubkey->pub_genfrom;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");
	/* We may need to get these from cert */
	switch (attr->type) {
		case CKA_MODULUS:
		case CKA_MODULUS_BITS:
		case CKA_VALUE:
		case CKA_SPKI:
		case CKA_PUBLIC_EXPONENT:
		case CKA_EC_PARAMS:
		case CKA_EC_POINT:
			if (pubkey->pub_data == NULL)
				if (SC_SUCCESS != check_cert_data_read(fw_data, cert))
					return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "check_cert_data_read");
			break;
	}

	switch (attr->type) {
	case CKA_CLASS:
		check_attribute_buffer(attr, sizeof(CK_OBJECT_CLASS));
		*(CK_OBJECT_CLASS*)attr->pValue = CKO_PUBLIC_KEY;
		break;
	case CKA_TOKEN:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = TRUE;
		break;
	case CKA_SENSITIVE:
		/* By PKCS#11 v2.20 public key cannot have SENSITIVE attr TRUE */
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = FALSE;
		break;
	case CKA_LOCAL:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		if (pubkey->pub_info)
			*(CK_BBOOL*)attr->pValue = (pubkey->pub_info->access_flags & SC_PKCS15_PRKEY_ACCESS_LOCAL) != 0;
		else /* no pub_info structure, falling back to TRUE */
			*(CK_BBOOL*)attr->pValue = TRUE;
		break;
	case CKA_PRIVATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		if (pubkey->pub_p15obj)
			*(CK_BBOOL*)attr->pValue = (pubkey->pub_p15obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0;
		else if (cert && cert->cert_p15obj)
			*(CK_BBOOL*)attr->pValue = (cert->pub_p15obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0;
		else
			return CKR_ATTRIBUTE_TYPE_INVALID;
		break;
	case CKA_MODIFIABLE:
	case CKA_EXTRACTABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = FALSE;
		break;
	case CKA_LABEL:
		if (pubkey->pub_p15obj) {
			len = strnlen(pubkey->pub_p15obj->label, sizeof pubkey->pub_p15obj->label);
			check_attribute_buffer(attr, len);
			memcpy(attr->pValue, pubkey->pub_p15obj->label, len);
		}
		else if (cert && cert->cert_p15obj) {
			len = strnlen(cert->cert_p15obj->label, sizeof cert->cert_p15obj->label);
			check_attribute_buffer(attr, len);
			memcpy(attr->pValue, cert->cert_p15obj->label, len);
		}
		else {
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
		break;
	case CKA_KEY_TYPE:
		check_attribute_buffer(attr, sizeof(CK_KEY_TYPE));
		/* TODO: -DEE why would we not have a pubkey->pub_data? */
		/* even if we do not, we should not assume RSA */
		if (pubkey->pub_data && pubkey->pub_data->algorithm == SC_ALGORITHM_GOSTR3410)
			*(CK_KEY_TYPE*)attr->pValue = CKK_GOSTR3410;
		else if (pubkey->pub_data && pubkey->pub_data->algorithm == SC_ALGORITHM_EC)
			*(CK_KEY_TYPE*)attr->pValue = CKK_EC;
		else
			*(CK_KEY_TYPE*)attr->pValue = CKK_RSA;
		break;
	case CKA_ID:
		if (pubkey->pub_info) {
			check_attribute_buffer(attr, pubkey->pub_info->id.len);
			memcpy(attr->pValue, pubkey->pub_info->id.value, pubkey->pub_info->id.len);
		}
		else if (cert && cert->cert_info) {
			check_attribute_buffer(attr, cert->cert_info->id.len);
			memcpy(attr->pValue, cert->cert_info->id.value, cert->cert_info->id.len);
		}
		else {
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
		break;
	case CKA_KEY_GEN_MECHANISM:
		check_attribute_buffer(attr, sizeof(CK_MECHANISM_TYPE));
		*(CK_MECHANISM_TYPE*)attr->pValue = CK_UNAVAILABLE_INFORMATION;
		break;
	case CKA_ENCRYPT:
	case CKA_WRAP:
	case CKA_VERIFY:
	case CKA_VERIFY_RECOVER:
	case CKA_DERIVE:
		if (pubkey->pub_info)
			return get_usage_bit(pubkey->pub_info->usage, attr);
		else
			return get_usage_bit(SC_PKCS15_PRKEY_USAGE_ENCRYPT |SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER, attr);
	case CKA_MODULUS:
		return get_modulus(pubkey->pub_data, attr);
	case CKA_MODULUS_BITS:
		return get_modulus_bits(pubkey->pub_data, attr);
	case CKA_PUBLIC_EXPONENT:
		return get_public_exponent(pubkey->pub_data, attr);
	/* 
	 * PKCS#11 does not define a CKA_VALUE for a CKO_PUBLIC_KEY.
	 * OpenSC does, but it is not consistent it what it returns
	 * Internally to do verify, with OpenSSL, we need a SPKI that
	 * can be converted into a EVP_KEY with d2i_PUBKEY
	 * CKA_SPKI is defined internally as a CKA_VENDOR_DFINED attribute.
	 */
	case CKA_VALUE:
	case CKA_SPKI:

		if (attr->type != CKA_SPKI && pubkey->pub_info && pubkey->pub_info->direct.raw.value && pubkey->pub_info->direct.raw.len)   {
			check_attribute_buffer(attr, pubkey->pub_info->direct.raw.len);
			memcpy(attr->pValue, pubkey->pub_info->direct.raw.value, pubkey->pub_info->direct.raw.len);
		}
		else if (pubkey->pub_info && pubkey->pub_info->direct.spki.value && pubkey->pub_info->direct.spki.len)   {
			check_attribute_buffer(attr, pubkey->pub_info->direct.spki.len);
			memcpy(attr->pValue, pubkey->pub_info->direct.spki.value, pubkey->pub_info->direct.spki.len);
		}
		else if (pubkey->pub_data)   {
			unsigned char *value = NULL;
			size_t len;

			if (attr->type != CKA_SPKI) {
				if (sc_pkcs15_encode_pubkey(context, pubkey->pub_data, &value, &len))
					return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");
				} else {
					if (sc_pkcs15_encode_pubkey_as_spki(context, pubkey->pub_data, &value, &len))
					return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");
				}

			if (attr->pValue == NULL_PTR) {
				attr->ulValueLen = len;
				free(value);
				return CKR_OK;
			}
			if (attr->ulValueLen < len) {
				attr->ulValueLen = len;
				free(value);
				return CKR_BUFFER_TOO_SMALL;
			}
			attr->ulValueLen = len;
			memcpy(attr->pValue, value, len);

			free(value);
		}
		else if (attr->type != CKA_SPKI && pubkey->base.p15_object && pubkey->base.p15_object->content.value && pubkey->base.p15_object->content.len)   {
			check_attribute_buffer(attr, pubkey->base.p15_object->content.len);
			memcpy(attr->pValue, pubkey->base.p15_object->content.value, pubkey->base.p15_object->content.len);
		}
		else if (cert && cert->cert_data) {
			check_attribute_buffer(attr, cert->cert_data->data.len);
			memcpy(attr->pValue, cert->cert_data->data.value, cert->cert_data->data.len);
		}
		else   {
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
		break;
	case CKA_GOSTR3410_PARAMS:
		if (pubkey->pub_info && pubkey->pub_info->params.len)
			return get_gostr3410_params(pubkey->pub_info->params.data, pubkey->pub_info->params.len, attr);
		else
			return CKR_ATTRIBUTE_TYPE_INVALID;
	case CKA_EC_PARAMS:
		return get_ec_pubkey_params(pubkey->pub_data, attr);
	case CKA_EC_POINT:
		return get_ec_pubkey_point(pubkey->pub_data, attr);

	default:
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	return CKR_OK;
}

struct sc_pkcs11_object_ops pkcs15_pubkey_ops = {
	pkcs15_pubkey_release,
	pkcs15_pubkey_set_attribute,
	pkcs15_pubkey_get_attribute,
	sc_pkcs11_any_cmp_attribute,
	pkcs15_any_destroy,
	NULL,	/* get_size */
	NULL,	/* sign */
	NULL,	/* unwrap_key */
	NULL,	/* decrypt */
	NULL,	/* derive */
	NULL,	/* can_do */
	NULL,	/* init_params */
	NULL	/* wrap_key */
};


/* PKCS#15 Data Object*/
static void
pkcs15_dobj_release(void *object)
{
	__pkcs15_release_object((struct pkcs15_any_object *) object);
}


static CK_RV
pkcs15_dobj_set_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_data_object *dobj = (struct pkcs15_data_object*) object;

	return pkcs15_set_attrib(session, dobj->base.p15_object, attr);
}


static CK_RV
pkcs15_dobj_get_value(struct sc_pkcs11_session *session,
		struct pkcs15_data_object *dobj,
		struct sc_pkcs15_data **out_data)
{
	struct sc_pkcs11_card *p11card = session->slot->p11card;
	struct pkcs15_fw_data *fw_data = NULL;
	struct sc_card *card;
	int rv;

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	card = session->slot->p11card->card;
	if (!out_data)
		return SC_ERROR_INVALID_ARGUMENTS;
	if (dobj->info->data.len == 0)
	/* CKA_VALUE is empty we may need to read it */
	{
		*out_data = NULL;
	}

	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_GetAttributeValue");

	rv = sc_lock(card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_GetAttributeValue");

	rv = sc_pkcs15_read_data_object(fw_data->p15_card, dobj->info, out_data);

	sc_unlock(card);
	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_GetAttributeValue");

	return rv;
}


static CK_RV
data_value_to_attr(CK_ATTRIBUTE_PTR attr, struct sc_pkcs15_data *data)
{
	if (!attr || !data)
		return CKR_ATTRIBUTE_VALUE_INVALID;

	check_attribute_buffer(attr, data->data_len);
	memcpy(attr->pValue, data->data, data->data_len);
	return CKR_OK;
}


static CK_RV
pkcs15_dobj_get_attribute(struct sc_pkcs11_session *session, void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_data_object *dobj = (struct pkcs15_data_object*) object;
	struct sc_pkcs15_data *data = NULL;
	CK_RV rv;
	size_t len;
	int r;
	unsigned char *buf = NULL;

	sc_log(context, "pkcs15_dobj_get_attribute() called");
	switch (attr->type) {
	case CKA_CLASS:
		check_attribute_buffer(attr, sizeof(CK_OBJECT_CLASS));
		*(CK_OBJECT_CLASS*)attr->pValue = CKO_DATA;
		break;
	case CKA_TOKEN:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = TRUE;
		break;
	case CKA_PRIVATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (dobj->base.p15_object->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0;
		break;
	case CKA_MODIFIABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (dobj->base.p15_object->flags & 0x02) != 0;
		break;
	case CKA_LABEL:
		len = strnlen(dobj->base.p15_object->label, sizeof dobj->base.p15_object->label);
		check_attribute_buffer(attr, len);
		memcpy(attr->pValue, dobj->base.p15_object->label, len);
		break;
	case CKA_APPLICATION:
		len = strlen(dobj->info->app_label);
		check_attribute_buffer(attr, len);
		memcpy(attr->pValue, dobj->info->app_label, len);
		break;
#if 0
	case CKA_ID:
		check_attribute_buffer(attr, dobj->info->id.len);
		memcpy(attr->pValue, dobj->info->id.value, dobj->info->id.len);
		break;
#endif
	case CKA_OBJECT_ID:
		if (!sc_valid_oid(&dobj->info->app_oid))   {
			attr->ulValueLen = -1;
			return CKR_ATTRIBUTE_TYPE_INVALID;
		}
		r = sc_asn1_encode_object_id(NULL, &len, &dobj->info->app_oid);
		if (r)   {
			sc_log(context, "data_get_attr(): encode OID error %i", r);
			return CKR_FUNCTION_FAILED;
		}

		check_attribute_buffer(attr, len);

		r = sc_asn1_encode_object_id(&buf, &len, &dobj->info->app_oid);
		if (r)   {
			sc_log(context, "data_get_attr(): encode OID error %i", r);
			return CKR_FUNCTION_FAILED;
		}

		memcpy(attr->pValue, buf, len);
		free(buf);
		break;
	case CKA_VALUE:
		/* if CKA_VALUE is empty, sets data to NULL */
		rv = pkcs15_dobj_get_value(session, dobj, &data);
		if (rv == CKR_OK) {
			if (data) {
				rv = data_value_to_attr(attr, data);
			}
			else {
				attr->ulValueLen = 0;
				attr->pValue = NULL_PTR;
			}
		}
		if (data) {
			free(data->data);
			free(data);
		}
		if (rv != CKR_OK)
			return rv;
		break;
	default:
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	return CKR_OK;
}

struct sc_pkcs11_object_ops pkcs15_dobj_ops = {
	pkcs15_dobj_release,
	pkcs15_dobj_set_attribute,
	pkcs15_dobj_get_attribute,
	sc_pkcs11_any_cmp_attribute,
	pkcs15_any_destroy,
	NULL,	/* get_size */
	NULL,	/* sign */
	NULL,	/* unwrap_key */
	NULL,	/* decrypt */
	NULL,	/* derive */
	NULL,	/* can_do */
	NULL,	/* init_params */
	NULL	/* wrap_key */
};


/* PKCS#15 Secret Key Objects */
/* TODO Currently only session objects */
static void
pkcs15_skey_release(void *object)
{
	__pkcs15_release_object((struct pkcs15_any_object *) object);
}


static CK_RV
pkcs15_skey_set_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_skey_object *skey = (struct pkcs15_skey_object*) object;

	/* TODO DEE Assume a session based token, and only
	 * change in memory, and only selected types
	 * The pkcs15_set_attrib assumes the object is on the card....
	 * When skey support on the card is added this needs to be changed */

	switch (attr->type) {
	case CKA_VALUE:
		if (attr->pValue) {
			skey->info->data.value = calloc(1,attr->ulValueLen);
			if (!skey->info->data.value)
				return CKR_HOST_MEMORY;
			memcpy(skey->info->data.value, attr->pValue, attr->ulValueLen);
			skey->info->data.len = attr->ulValueLen;
		}
		break;
	default:
		return pkcs15_set_attrib(session, skey->base.p15_object, attr);
	}
	return CKR_OK;
}


static CK_RV
pkcs15_skey_get_attribute(struct sc_pkcs11_session *session,
		void *object, CK_ATTRIBUTE_PTR attr)
{
	struct pkcs15_skey_object *skey = (struct pkcs15_skey_object*) object;
	size_t len;

	sc_log(context, "pkcs15_skey_get_attribute() called");
	switch (attr->type) {
	case CKA_CLASS:
		check_attribute_buffer(attr, sizeof(CK_OBJECT_CLASS));
		*(CK_OBJECT_CLASS*)attr->pValue = CKO_SECRET_KEY;
		break;
	case CKA_TOKEN:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = skey->base.p15_object->session_object == 0 ? CK_TRUE : CK_FALSE;
		break;
	case CKA_PRIVATE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->base.p15_object->flags & SC_PKCS15_CO_FLAG_PRIVATE) != 0 ? CK_TRUE : CK_FALSE;
		break;
	case CKA_MODIFIABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->base.p15_object->flags & 0x02) != 0 ? CK_TRUE : CK_FALSE;
		/*TODO Why no definition of the flag */
		break;
	case CKA_LABEL:
		len = strnlen(skey->base.p15_object->label, sizeof skey->base.p15_object->label);
		check_attribute_buffer(attr, len);
		memcpy(attr->pValue, skey->base.p15_object->label, len);
		break;
	case CKA_KEY_TYPE:
		check_attribute_buffer(attr, sizeof(CK_KEY_TYPE));
		if (skey->info)
			*(CK_OBJECT_CLASS*)attr->pValue = skey->info->key_type;
		break;
	case CKA_ENCRYPT:
	case CKA_DECRYPT:
	case CKA_SIGN:
	case CKA_SIGN_RECOVER:
	case CKA_WRAP:
	case CKA_UNWRAP:
	case CKA_VERIFY:
	case CKA_VERIFY_RECOVER:
	case CKA_DERIVE:
		if (skey->info)
			return get_usage_bit(skey->info->usage, attr);
		else
			return get_usage_bit(SC_PKCS15_PRKEY_USAGE_ENCRYPT
					|SC_PKCS15_PRKEY_USAGE_DECRYPT
					|SC_PKCS15_PRKEY_USAGE_WRAP
					|SC_PKCS15_PRKEY_USAGE_UNWRAP, attr);
		break;
	case CKA_ID:
		check_attribute_buffer(attr, skey->info->id.len);
		memcpy(attr->pValue, skey->info->id.value, skey->info->id.len);
		break;
	case CKA_EXTRACTABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (((skey->base.p15_object->flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) == SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE)
					&& (skey->base.p15_object->flags & SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE) == 0
					&& (skey->base.p15_object->flags & SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE) == 0) ? CK_TRUE : CK_FALSE;
		break;
	case CKA_ALWAYS_SENSITIVE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->info->access_flags & SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE) != 0;
		break;
	case CKA_NEVER_EXTRACTABLE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->info->access_flags & SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE) != 0;
		break;
	case CKA_SENSITIVE:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->info->access_flags & SC_PKCS15_PRKEY_ACCESS_SENSITIVE) != 0;
		break;
	case CKA_LOCAL:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = (skey->info->access_flags & SC_PKCS15_PRKEY_ACCESS_LOCAL) != 0;
		break;
	case CKA_OPENSC_ALWAYS_AUTH_ANY_OBJECT:
		check_attribute_buffer(attr, sizeof(CK_BBOOL));
		*(CK_BBOOL*)attr->pValue = skey->base.p15_object->user_consent >= 1 ? CK_TRUE : CK_FALSE;
		break;
	case CKA_VALUE_LEN:
		check_attribute_buffer(attr, sizeof(CK_ULONG));
		*(CK_ULONG*)attr->pValue = skey->info->data.len;
		break;
	case CKA_VALUE:
		check_attribute_buffer(attr, skey->info->data.len);
		memcpy(attr->pValue, skey->info->data.value, skey->info->data.len);
		break;
	default:
		return CKR_ATTRIBUTE_TYPE_INVALID;
	}

	return CKR_OK;
}

static CK_RV
pkcs15_skey_unwrap(struct sc_pkcs11_session *session, void *obj,
			CK_MECHANISM_PTR pMechanism, CK_BYTE_PTR pWrappedKey,
			CK_ULONG ulWrappedKeyLen,
			void *targetKey)
{
	struct	sc_pkcs11_card *p11card = session->slot->p11card;
	struct	pkcs15_fw_data *fw_data = NULL;
	struct	pkcs15_skey_object *skey = (struct pkcs15_skey_object *) obj;
	struct	pkcs15_skey_object *targetKeyObj = (struct pkcs15_skey_object *) targetKey;
	int	rv, flags = 0;

	sc_log(context, "Initiating unwrapping with a secret key.");

	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];
	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_UnwrapKey");

	if (pMechanism == NULL || pWrappedKey == NULL || ulWrappedKeyLen == 0 || targetKeyObj == NULL) {
		sc_log(context, "One or more of mandatory arguments were NULL.");
		return CKR_ARGUMENTS_BAD;
	}

	/* Check whether this key supports unwrap */
	if (skey && !(skey->info->usage & SC_PKCS15_PRKEY_USAGE_UNWRAP))
		skey = NULL;

	/* TODO: should we look for a compatible key automatically? prv_next not implemented yet. */
	/* skey = skey->prv_next; */

	if (skey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	sc_log(context, "Using mechanism %lx.", pMechanism->mechanism);
	/* Select the proper padding mechanism */
	switch (pMechanism->mechanism) {
	case CKM_AES_ECB:
		flags |= SC_ALGORITHM_AES_ECB;
		break;
	case CKM_AES_CBC_PAD:
		flags |= SC_ALGORITHM_AES_CBC_PAD;
		break;
	case CKM_AES_CBC:
		flags |= SC_ALGORITHM_AES_CBC; /* in this case, pMechanism->pParameter contains IV */
		break;
	default:
		return CKR_MECHANISM_INVALID;
	}

	rv = sc_lock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	/* Call the card to do the unwrap operation */
	rv = sc_pkcs15_unwrap(fw_data->p15_card, skey->prv_p15obj, targetKeyObj->prv_p15obj, flags,
		pWrappedKey, ulWrappedKeyLen, pMechanism->pParameter, pMechanism->ulParameterLen);

	sc_unlock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	return CKR_OK;
}

/*
 * Wrap a key using a secret key. obj = wrapping key, targetKey = key to be wrapped.
 * Wrapped key data is returned in pData
 */

static CK_RV
pkcs15_skey_wrap(struct sc_pkcs11_session *session, void *obj,
			CK_MECHANISM_PTR pMechanism,
			void *targetKey,
			CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)

{
	struct	sc_pkcs11_card *p11card;
	struct	pkcs15_fw_data *fw_data = NULL;
	struct	pkcs15_skey_object *skey = (struct pkcs15_skey_object *) obj;
	struct	pkcs15_skey_object *targetKeyObj = (struct pkcs15_skey_object *) targetKey;
	size_t len = pulDataLen ? *pulDataLen : 0;
	int rv, flags = 0;

	sc_log(context, "Initializing wrapping with a secret key.");

	if (session == NULL || pMechanism == NULL || obj == NULL || targetKey == NULL) {
		sc_log(context, "One or more of mandatory arguments were NULL.");
		return CKR_ARGUMENTS_BAD;
	}

	p11card = session->slot->p11card;
	if (!p11card)
		return CKR_TOKEN_NOT_RECOGNIZED;
	fw_data = (struct pkcs15_fw_data *) p11card->fws_data[session->slot->fw_data_idx];

	if (!fw_data)
		return sc_to_cryptoki_error(SC_ERROR_INTERNAL, "C_WrapKey");

	/* Verify that the key supports wrapping */
	if (skey && !(skey->info->usage & SC_PKCS15_PRKEY_USAGE_WRAP))
		skey = NULL;
	/* TODO: browse for a key that supports, like other similar funcs */

	if (skey == NULL)
		return CKR_KEY_FUNCTION_NOT_PERMITTED;

	sc_log(context, "Using mechanism %lx.", pMechanism->mechanism);

	/* Select the proper padding mechanism */
	switch (pMechanism->mechanism) {
	case CKM_AES_ECB:
		flags |= SC_ALGORITHM_AES_ECB;
		break;
	case CKM_AES_CBC_PAD:	/* with CBC, pMechanism->pParameter contains IV */
		flags |= SC_ALGORITHM_AES_CBC_PAD;
		break;
	case CKM_AES_CBC:
		flags |= SC_ALGORITHM_AES_CBC;
		break;
	default:
		return CKR_MECHANISM_INVALID;
	}

	rv = sc_lock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	/* Call the card to do the wrapping operation */
	rv = sc_pkcs15_wrap(fw_data->p15_card, skey->prv_p15obj, targetKeyObj->prv_p15obj, flags,
		pData, &len, pMechanism->pParameter, pMechanism->ulParameterLen);

	if (pulDataLen) {
		*pulDataLen = len;
	}

	sc_unlock(p11card->card);

	if (rv < 0)
		return sc_to_cryptoki_error(rv, "C_UnwrapKey");

	return CKR_OK;
}


/*
 *  Secret key objects, currently used only to retrieve derived session key
 */
struct sc_pkcs11_object_ops pkcs15_skey_ops = {
	pkcs15_skey_release,
	pkcs15_skey_set_attribute,
	pkcs15_skey_get_attribute,
	sc_pkcs11_any_cmp_attribute,
	pkcs15_skey_destroy,
	NULL,	/* get_size */
	NULL,	/* sign */
	pkcs15_skey_unwrap,
	NULL,	/* decrypt */
	NULL,	/* derive */
	NULL,	/* can_do */
	NULL,	/* init_params */
	pkcs15_skey_wrap /* wrap_key */
};

/*
 * get_attribute helpers
 */
static CK_RV
get_bignum(sc_pkcs15_bignum_t *bn, CK_ATTRIBUTE_PTR attr)
{
	check_attribute_buffer(attr, bn->len);
	memcpy(attr->pValue, bn->data, bn->len);
	return CKR_OK;
}

static CK_RV
get_bignum_bits(sc_pkcs15_bignum_t *bn, CK_ATTRIBUTE_PTR attr)
{
	CK_ULONG	bits, mask;

	if (!bn || !bn->len || !bn->data)
		return CKR_DEVICE_ERROR;

	bits = bn->len * 8;
	for (mask = 0x80; mask; mask >>= 1, bits--)
		if (bn->data[0] & mask)
			break;

	check_attribute_buffer(attr, sizeof(bits));
	*(CK_ULONG *) attr->pValue = bits;
	return CKR_OK;
}

static CK_RV
get_modulus(struct sc_pkcs15_pubkey *key, CK_ATTRIBUTE_PTR attr)
{
	if (key == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;
	switch (key->algorithm) {
	case SC_ALGORITHM_RSA:
		return get_bignum(&key->u.rsa.modulus, attr);
	}
	return CKR_ATTRIBUTE_TYPE_INVALID;
}

static CK_RV
get_modulus_bits(struct sc_pkcs15_pubkey *key, CK_ATTRIBUTE_PTR attr)
{
	if (key == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;
	switch (key->algorithm) {
	case SC_ALGORITHM_RSA:
		return get_bignum_bits(&key->u.rsa.modulus, attr);
	}
	return CKR_ATTRIBUTE_TYPE_INVALID;
}

static CK_RV
get_public_exponent(struct sc_pkcs15_pubkey *key, CK_ATTRIBUTE_PTR attr)
{
	if (key == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;
	switch (key->algorithm) {
	case SC_ALGORITHM_RSA:
		return get_bignum(&key->u.rsa.exponent, attr);
	}

	return CKR_ATTRIBUTE_TYPE_INVALID;
}

static CK_RV
get_ec_pubkey_params(struct sc_pkcs15_pubkey *key, CK_ATTRIBUTE_PTR attr)
{
	struct sc_ec_parameters *ecp;

	if (key == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;
	if (key->alg_id == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;

	switch (key->algorithm) {
	case SC_ALGORITHM_EC:
		/* TODO parms should not be in two places */
		/* ec_params may be in key->alg_id or in key->u.ec */
		if (key->u.ec.params.der.value) {
			check_attribute_buffer(attr,key->u.ec.params.der.len);
			memcpy(attr->pValue, key->u.ec.params.der.value, key->u.ec.params.der.len);
			return CKR_OK;
		}

		ecp = (struct sc_ec_parameters *) key->alg_id->params;
		if (ecp && ecp->der.value && ecp->der.len)   {
			check_attribute_buffer(attr, ecp->der.len);
			memcpy(attr->pValue, ecp->der.value, ecp->der.len);
			return CKR_OK;
		}
	}

	return CKR_ATTRIBUTE_TYPE_INVALID;
}

static CK_RV
get_ec_pubkey_point(struct sc_pkcs15_pubkey *key, CK_ATTRIBUTE_PTR attr)
{
	unsigned char *value = NULL;
	size_t value_len = 0;
	int rc;

	if (key == NULL)
		return CKR_ATTRIBUTE_TYPE_INVALID;

	switch (key->algorithm) {
	case SC_ALGORITHM_EC:
		rc = sc_pkcs15_encode_pubkey_ec(context, &key->u.ec, &value, &value_len);
		if (rc != SC_SUCCESS)
			return sc_to_cryptoki_error(rc, NULL);

		if (attr->pValue == NULL_PTR) {
			attr->ulValueLen = value_len;
			free(value);
			return CKR_OK;
		}
		if (attr->ulValueLen < value_len) {
			attr->ulValueLen = value_len;
			free(value);
			return CKR_BUFFER_TOO_SMALL;
		}
		attr->ulValueLen = value_len;

		memcpy(attr->pValue, value, value_len);
		free(value);
		return CKR_OK;
	}

	return CKR_ATTRIBUTE_TYPE_INVALID;
}

static CK_RV
get_gostr3410_params(const u8 *params, size_t params_len, CK_ATTRIBUTE_PTR attr)
{
	size_t i;

	if (!params || params_len == sizeof(int))
		return CKR_ATTRIBUTE_TYPE_INVALID;

	for (i = 0; i < sizeof(gostr3410_param_oid)/sizeof(gostr3410_param_oid[0]); ++i) {
		if (gostr3410_param_oid[i].oid_id == ((int*)params)[0]) {
			check_attribute_buffer(attr, gostr3410_param_oid[i].encoded_oid_size);
			memcpy(attr->pValue, gostr3410_param_oid[i].encoded_oid,
					gostr3410_param_oid[i].encoded_oid_size);
			return CKR_OK;
		}
	}
	return CKR_ATTRIBUTE_TYPE_INVALID;
}

/*
 * Map pkcs15 usage bits to pkcs11 usage attributes.
 *
 * It's not totally clear to me whether SC_PKCS15_PRKEY_USAGE_NONREPUDIATION should
 * be treated as being equivalent with CKA_SIGN or not...
 */
static CK_RV
get_usage_bit(unsigned int usage, CK_ATTRIBUTE_PTR attr)
{
	static struct {
		CK_ATTRIBUTE_TYPE type;
		unsigned int	flag;
	} flag_mapping[] = {
		{ CKA_ENCRYPT,		SC_PKCS15_PRKEY_USAGE_ENCRYPT },
		{ CKA_DECRYPT,		SC_PKCS15_PRKEY_USAGE_DECRYPT },
		{ CKA_SIGN,		SC_PKCS15_PRKEY_USAGE_SIGN|SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
		{ CKA_SIGN_RECOVER,	SC_PKCS15_PRKEY_USAGE_SIGNRECOVER },
		{ CKA_WRAP,		SC_PKCS15_PRKEY_USAGE_WRAP },
		{ CKA_UNWRAP,		SC_PKCS15_PRKEY_USAGE_UNWRAP },
		{ CKA_VERIFY,		SC_PKCS15_PRKEY_USAGE_VERIFY },
		{ CKA_VERIFY_RECOVER,	SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER },
		{ CKA_DERIVE,		SC_PKCS15_PRKEY_USAGE_DERIVE },
		{ CKA_OPENSC_NON_REPUDIATION, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
		{ 0, 0 }
	};
	unsigned int mask = 0, j;

	for (j = 0; (mask = flag_mapping[j].flag) != 0; j++) {
		if (flag_mapping[j].type == attr->type)
			break;
	}
	if (mask == 0)
		return CKR_ATTRIBUTE_TYPE_INVALID;

	check_attribute_buffer(attr, sizeof(CK_BBOOL));
	*(CK_BBOOL*)attr->pValue = (usage & mask)? TRUE : FALSE;

	return CKR_OK;
}


static CK_RV
register_gost_mechanisms(struct sc_pkcs11_card *p11card, int flags)
{
	CK_MECHANISM_INFO mech_info;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rc;

	mech_info.flags = CKF_HW | CKF_SIGN | CKF_DECRYPT;
#ifdef ENABLE_OPENSSL
	/* That practise definitely conflicts with CKF_HW -- andre 2010-11-28 */
	mech_info.flags |= CKF_VERIFY;
#endif
	mech_info.ulMinKeySize = SC_PKCS15_GOSTR3410_KEYSIZE;
	mech_info.ulMaxKeySize = SC_PKCS15_GOSTR3410_KEYSIZE;

	if (flags & SC_ALGORITHM_GOSTR3410_HASH_NONE) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_GOSTR3410,
				&mech_info, CKK_GOSTR3410, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}
	if (flags & SC_ALGORITHM_GOSTR3410_HASH_GOSTR3411) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_GOSTR3410_WITH_GOSTR3411,
				&mech_info, CKK_GOSTR3410, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}
	if (flags & SC_ALGORITHM_ONBOARD_KEY_GEN) {
		mech_info.flags = CKF_HW | CKF_GENERATE_KEY_PAIR;
		mt = sc_pkcs11_new_fw_mechanism(CKM_GOSTR3410_KEY_PAIR_GEN,
				&mech_info, CKK_GOSTR3410, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

	return CKR_OK;
}


static CK_RV register_ec_mechanisms(struct sc_pkcs11_card *p11card, int flags,
		unsigned long ext_flags, CK_ULONG min_key_size, CK_ULONG max_key_size)
{
	CK_MECHANISM_INFO mech_info;
	sc_pkcs11_mechanism_type_t *mt;
	CK_FLAGS ec_flags = 0;
	CK_RV rc;

	if (ext_flags & SC_ALGORITHM_EXT_EC_F_P)
		ec_flags |= CKF_EC_F_P;
	if (ext_flags & SC_ALGORITHM_EXT_EC_F_2M)
		ec_flags |= CKF_EC_F_2M;
	if (ext_flags & SC_ALGORITHM_EXT_EC_ECPARAMETERS)
		ec_flags |= CKF_EC_ECPARAMETERS;
	if (ext_flags & SC_ALGORITHM_EXT_EC_NAMEDCURVE)
		ec_flags |= CKF_EC_NAMEDCURVE;
	if (ext_flags & SC_ALGORITHM_EXT_EC_UNCOMPRESES)
		ec_flags |= CKF_EC_UNCOMPRESS;
	if (ext_flags & SC_ALGORITHM_EXT_EC_COMPRESS)
		ec_flags |= CKF_EC_COMPRESS;

	mech_info.flags = CKF_HW | CKF_SIGN; /* check for more */
	mech_info.flags |= ec_flags;
	mech_info.ulMinKeySize = min_key_size;
	mech_info.ulMaxKeySize = max_key_size;

	if(flags & SC_ALGORITHM_ECDSA_HASH_NONE) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_ECDSA, &mech_info, CKK_EC, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

#ifdef ENABLE_OPENSSL
	if(flags & SC_ALGORITHM_ECDSA_HASH_SHA1) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_ECDSA_SHA1, &mech_info, CKK_EC, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}
#endif

	/* ADD ECDH mechanisms */
	/* The PIV uses curves where CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE produce the same results */
	if(flags & SC_ALGORITHM_ECDH_CDH_RAW) {
		mech_info.flags &= ~CKF_SIGN;
		mech_info.flags |= CKF_DERIVE;

		mt = sc_pkcs11_new_fw_mechanism(CKM_ECDH1_COFACTOR_DERIVE, &mech_info, CKK_EC, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;

		mt = sc_pkcs11_new_fw_mechanism(CKM_ECDH1_DERIVE, &mech_info, CKK_EC, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

	if (flags & SC_ALGORITHM_ONBOARD_KEY_GEN) {
		mech_info.flags = CKF_HW | CKF_GENERATE_KEY_PAIR;
		mech_info.flags |= ec_flags;
		mt = sc_pkcs11_new_fw_mechanism(CKM_EC_KEY_PAIR_GEN, &mech_info, CKK_EC, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

	return CKR_OK;
}

static int sc_pkcs11_register_aes_mechanisms(struct sc_pkcs11_card *p11card, int flags,
		CK_ULONG min_key_size, CK_ULONG max_key_size)
{
	int rc;
	CK_MECHANISM_INFO mech_info;
	sc_pkcs11_mechanism_type_t *mt;
	sc_card_t* card = p11card->card;
	memset(&mech_info, 0, sizeof(mech_info));
	mech_info.flags = CKF_ENCRYPT | CKF_DECRYPT;
	mech_info.ulMinKeySize = min_key_size;
	mech_info.ulMaxKeySize = max_key_size;

	if ((card->caps & SC_CARD_CAP_UNWRAP_KEY) == SC_CARD_CAP_UNWRAP_KEY)
		mech_info.flags |= CKF_UNWRAP;
	if ((card->caps & SC_CARD_CAP_WRAP_KEY) == SC_CARD_CAP_WRAP_KEY)
		mech_info.flags |= CKF_WRAP;

	mt = sc_pkcs11_new_fw_mechanism(CKM_AES_ECB, &mech_info, CKK_AES, NULL, NULL);
	if (!mt)
		return CKR_HOST_MEMORY;
	rc = sc_pkcs11_register_mechanism(p11card, mt);
	if (rc != CKR_OK)
			return rc;

	mt = sc_pkcs11_new_fw_mechanism(CKM_AES_CBC, &mech_info, CKK_AES, NULL, NULL);
	if (!mt)
		return CKR_HOST_MEMORY;
	rc = sc_pkcs11_register_mechanism(p11card, mt);
	if (rc != CKR_OK)
			return rc;

	mt = sc_pkcs11_new_fw_mechanism(CKM_AES_CBC_PAD, &mech_info, CKK_AES, NULL, NULL);
	if (!mt)
		return CKR_HOST_MEMORY;
	rc = sc_pkcs11_register_mechanism(p11card, mt);
	if (rc != CKR_OK)
			return rc;

	return CKR_OK;
}

/*
 * Mechanism handling
 * FIXME: We should consult the card's algorithm list to
 * find out what operations it supports
 */
static CK_RV
register_mechanisms(struct sc_pkcs11_card *p11card)
{
	sc_card_t *card = p11card->card;
	sc_algorithm_info_t *alg_info;
	CK_MECHANISM_INFO mech_info;
	CK_ULONG ec_min_key_size, ec_max_key_size,
		aes_min_key_size, aes_max_key_size;
	unsigned long ec_ext_flags;
	sc_pkcs11_mechanism_type_t *mt;
	unsigned int num;
	int rsa_flags = 0, ec_flags = 0, gostr_flags = 0, aes_flags = 0;
	CK_RV rc;

	/* Register generic mechanisms */
	sc_pkcs11_register_generic_mechanisms(p11card);

	mech_info.flags = CKF_HW | CKF_SIGN | CKF_DECRYPT;
#ifdef ENABLE_OPENSSL
	/* That practise definitely conflicts with CKF_HW -- andre 2010-11-28 */
	mech_info.flags |= CKF_VERIFY;
#endif
	if ((card->caps & SC_CARD_CAP_UNWRAP_KEY) == SC_CARD_CAP_UNWRAP_KEY)
		mech_info.flags |= CKF_UNWRAP;
	if ((card->caps & SC_CARD_CAP_WRAP_KEY) == SC_CARD_CAP_WRAP_KEY)
		mech_info.flags |= CKF_WRAP;

	mech_info.ulMinKeySize = ~0;
	mech_info.ulMaxKeySize = 0;
	ec_min_key_size = ~0;
	ec_max_key_size = 0;
	aes_min_key_size = ~0;
	aes_max_key_size = 0;

	ec_ext_flags = 0;

	/* For now, we just OR all the algorithm specific
	 * flags, based on the assumption that cards don't
	 * support different modes for different key *sizes*. */
	num = card->algorithm_count;
	alg_info = card->algorithms;
	while (num--) {
		switch (alg_info->algorithm) {
			case SC_ALGORITHM_RSA:
				if (alg_info->key_length < mech_info.ulMinKeySize)
					mech_info.ulMinKeySize = alg_info->key_length;
				if (alg_info->key_length > mech_info.ulMaxKeySize)
					mech_info.ulMaxKeySize = alg_info->key_length;
				rsa_flags |= alg_info->flags;
				break;
			case SC_ALGORITHM_EC:
				if (alg_info->key_length < ec_min_key_size)
					ec_min_key_size = alg_info->key_length;
				if (alg_info->key_length > ec_max_key_size)
					ec_max_key_size = alg_info->key_length;
				ec_flags |= alg_info->flags;
				ec_ext_flags |= alg_info->u._ec.ext_flags;
				break;
			case SC_ALGORITHM_GOSTR3410:
				gostr_flags |= alg_info->flags;
				break;
			case SC_ALGORITHM_AES:
				aes_flags |= alg_info->flags;
				if (alg_info->key_length < aes_min_key_size)
					aes_min_key_size = alg_info->key_length;
				if (alg_info->key_length > aes_max_key_size)
					aes_max_key_size = alg_info->key_length;
				break;
		}
		alg_info++;
	}

	if (ec_flags & SC_ALGORITHM_ECDSA_RAW) {
		rc = register_ec_mechanisms(p11card, ec_flags, ec_ext_flags, ec_min_key_size, ec_max_key_size);
		if (rc != CKR_OK)
			return rc;
	}

	if (gostr_flags & (SC_ALGORITHM_GOSTR3410_RAW
				| SC_ALGORITHM_GOSTR3410_HASH_NONE
				| SC_ALGORITHM_GOSTR3410_HASH_GOSTR3411)) {
		if (gostr_flags & SC_ALGORITHM_GOSTR3410_RAW)
			gostr_flags |= SC_ALGORITHM_GOSTR3410_HASH_NONE;
		rc = register_gost_mechanisms(p11card, gostr_flags);
		if (rc != CKR_OK)
			return rc;
	}

	/* Check if we support raw RSA */
	if (rsa_flags & SC_ALGORITHM_RSA_RAW) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_RSA_X_509, &mech_info, CKK_RSA, NULL, NULL);
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;

		/* We support PKCS1 padding in software */
		/* either the card supports it or OpenSC does */
		rsa_flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
#ifdef ENABLE_OPENSSL
		rsa_flags |= SC_ALGORITHM_RSA_PAD_PSS;
#endif
	}

	if (rsa_flags & SC_ALGORITHM_RSA_PAD_ISO9796) {
		/* Supported in hardware only, if the card driver declares it. */
		mt = sc_pkcs11_new_fw_mechanism(CKM_RSA_9796, &mech_info, CKK_RSA, NULL, NULL);
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

#ifdef ENABLE_OPENSSL
	/* all our software hashes are in OpenSSL */
	/* Only if card did not list the hashes, will we
	 * help it a little, by adding all the OpenSSL hashes
	 * that have PKCS#11 mechanisms.
	 */
	if (!(rsa_flags & (SC_ALGORITHM_RSA_HASHES & ~SC_ALGORITHM_RSA_HASH_NONE))) {
		rsa_flags |= SC_ALGORITHM_RSA_HASHES;
	}
#endif

	/* No need to Check for PKCS1  We support it in software and turned it on above so always added it */
	if (rsa_flags & SC_ALGORITHM_RSA_PAD_PKCS1) {
		mt = sc_pkcs11_new_fw_mechanism(CKM_RSA_PKCS, &mech_info, CKK_RSA, NULL, NULL);
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;

#ifdef ENABLE_OPENSSL
		/* sc_pkcs11_register_sign_and_hash_mechanism expects software hash */
		/* All hashes are in OpenSSL
		 * Either the card set the hashes or we helped it above */

		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA1_RSA_PKCS, CKM_SHA_1, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA224) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA224_RSA_PKCS, CKM_SHA224, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA256_RSA_PKCS, CKM_SHA256, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA384) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA384_RSA_PKCS, CKM_SHA384, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA512) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA512_RSA_PKCS, CKM_SHA512, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_MD5) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_MD5_RSA_PKCS, CKM_MD5, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_RIPEMD160) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_RIPEMD160_RSA_PKCS, CKM_RIPEMD160, mt);
			if (rc != CKR_OK)
				return rc;
		}
#endif /* ENABLE_OPENSSL */
	}

	if (rsa_flags & SC_ALGORITHM_RSA_PAD_PSS) {
		mech_info.flags &= ~(CKF_DECRYPT|CKF_ENCRYPT);
		mt = sc_pkcs11_new_fw_mechanism(CKM_RSA_PKCS_PSS, &mech_info, CKK_RSA, NULL, NULL);
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;

		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA1_RSA_PKCS_PSS, CKM_SHA_1, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA224) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA224_RSA_PKCS_PSS, CKM_SHA224, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA256_RSA_PKCS_PSS, CKM_SHA256, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA384) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA384_RSA_PKCS_PSS, CKM_SHA384, mt);
			if (rc != CKR_OK)
				return rc;
		}
		if (rsa_flags & SC_ALGORITHM_RSA_HASH_SHA512) {
			rc = sc_pkcs11_register_sign_and_hash_mechanism(p11card,
				CKM_SHA512_RSA_PKCS_PSS, CKM_SHA512, mt);
			if (rc != CKR_OK)
				return rc;
		}
	}

	if (rsa_flags & SC_ALGORITHM_ONBOARD_KEY_GEN) {
		mech_info.flags = CKF_GENERATE_KEY_PAIR;
		mt = sc_pkcs11_new_fw_mechanism(CKM_RSA_PKCS_KEY_PAIR_GEN, &mech_info, CKK_RSA, NULL, NULL);
		if (!mt)
			return CKR_HOST_MEMORY;
		rc = sc_pkcs11_register_mechanism(p11card, mt);
		if (rc != CKR_OK)
			return rc;
	}

	if (aes_max_key_size > 0) {
		rc = sc_pkcs11_register_aes_mechanisms(p11card, aes_flags, aes_min_key_size, aes_max_key_size);
		if (rc != CKR_OK)
			return rc;
	}


	return CKR_OK;
}


static int
lock_card(struct pkcs15_fw_data *fw_data)
{
	int	rc;

	if ((rc = sc_lock(fw_data->p15_card->card)) < 0)
		sc_log(context, "Failed to lock card (%d)", rc);
	else
		fw_data->locked++;

	return rc;
}


static int
unlock_card(struct pkcs15_fw_data *fw_data)
{
	while (fw_data->locked) {
		sc_unlock(fw_data->p15_card->card);
		fw_data->locked--;
	}
	return 0;
}


static int
reselect_app_df(sc_pkcs15_card_t *p15card)
{
	int r = SC_SUCCESS;

	if (p15card->file_app != NULL) {
		/* if the application df (of the pkcs15 application) is specified select it */
		sc_path_t *tpath = &p15card->file_app->path;
		sc_log(p15card->card->ctx, "reselect application df");
		r = sc_select_file(p15card->card, tpath, NULL);
	}
	return r;
}