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
|
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Dr Stephen Henson <stephen.henson@gemplus.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*
* This file implements the Symkey wrapper and the PKCS context
* Interfaces.
*/
#include "seccomon.h"
#include "secmod.h"
#include "nssilock.h"
#include "secmodi.h"
#include "pkcs11.h"
#include "pk11func.h"
#include "secitem.h"
#include "key.h"
#include "secoid.h"
#include "secasn1.h"
#include "sechash.h"
#include "cert.h"
#include "secerr.h"
#define PAIRWISE_SECITEM_TYPE siBuffer
#define PAIRWISE_DIGEST_LENGTH SHA1_LENGTH /* 160-bits */
#define PAIRWISE_MESSAGE_LENGTH 20 /* 160-bits */
/* forward static declarations. */
static PK11SymKey *pk11_DeriveWithTemplate(PK11SymKey *baseKey,
CK_MECHANISM_TYPE derive, SECItem *param, CK_MECHANISM_TYPE target,
CK_ATTRIBUTE_TYPE operation, int keySize, CK_ATTRIBUTE *userAttr,
unsigned int numAttrs);
/*
* strip leading zero's from key material
*/
void
pk11_SignedToUnsigned(CK_ATTRIBUTE *attrib) {
char *ptr = (char *)attrib->pValue;
unsigned long len = attrib->ulValueLen;
while (len && (*ptr == 0)) {
len--;
ptr++;
}
attrib->pValue = ptr;
attrib->ulValueLen = len;
}
/*
* get a new session on a slot. If we run out of session, use the slot's
* 'exclusive' session. In this case owner becomes false.
*/
static CK_SESSION_HANDLE
pk11_GetNewSession(PK11SlotInfo *slot,PRBool *owner)
{
CK_SESSION_HANDLE session;
*owner = PR_TRUE;
if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
if ( PK11_GETTAB(slot)->C_OpenSession(slot->slotID,CKF_SERIAL_SESSION,
slot,pk11_notify,&session) != CKR_OK) {
*owner = PR_FALSE;
session = slot->session;
}
if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
return session;
}
static void
pk11_CloseSession(PK11SlotInfo *slot,CK_SESSION_HANDLE session,PRBool owner)
{
if (!owner) return;
if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
(void) PK11_GETTAB(slot)->C_CloseSession(session);
if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
}
SECStatus
PK11_CreateNewObject(PK11SlotInfo *slot, CK_SESSION_HANDLE session,
CK_ATTRIBUTE *theTemplate, int count,
PRBool token, CK_OBJECT_HANDLE *objectID)
{
CK_SESSION_HANDLE rwsession;
CK_RV crv;
SECStatus rv = SECSuccess;
rwsession = session;
if (rwsession == CK_INVALID_SESSION) {
if (token) {
rwsession = PK11_GetRWSession(slot);
} else {
rwsession = slot->session;
PK11_EnterSlotMonitor(slot);
}
}
crv = PK11_GETTAB(slot)->C_CreateObject(rwsession, theTemplate,
count,objectID);
if(crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
rv = SECFailure;
}
if (session == CK_INVALID_SESSION) {
if (token) {
PK11_RestoreROSession(slot, rwsession);
} else {
PK11_ExitSlotMonitor(slot);
}
}
return rv;
}
static void
pk11_EnterKeyMonitor(PK11SymKey *symKey) {
if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
PK11_EnterSlotMonitor(symKey->slot);
}
static void
pk11_ExitKeyMonitor(PK11SymKey *symKey) {
if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
PK11_ExitSlotMonitor(symKey->slot);
}
static PK11SymKey *pk11SymKeyHead = NULL;
static PK11SymKey *
pk11_getKeyFromList(PK11SlotInfo *slot) {
PK11SymKey *symKey = NULL;
PK11_USE_THREADS(PZ_Lock(slot->freeListLock);)
if (slot->freeSymKeysHead) {
symKey = slot->freeSymKeysHead;
slot->freeSymKeysHead = symKey->next;
slot->keyCount--;
}
PK11_USE_THREADS(PZ_Unlock(slot->freeListLock);)
if (symKey) {
symKey->next = NULL;
if (!symKey->sessionOwner)
symKey->session = pk11_GetNewSession(slot,&symKey->sessionOwner);
return symKey;
}
symKey = (PK11SymKey *)PORT_ZAlloc(sizeof(PK11SymKey));
if (symKey == NULL) {
return NULL;
}
symKey->refLock = PZ_NewLock(nssILockRefLock);
if (symKey->refLock == NULL) {
PORT_Free(symKey);
return NULL;
}
symKey->session = pk11_GetNewSession(slot,&symKey->sessionOwner);
symKey->next = NULL;
return symKey;
}
void
PK11_CleanKeyList(PK11SlotInfo *slot)
{
PK11SymKey *symKey = NULL;
while (slot->freeSymKeysHead) {
symKey = slot->freeSymKeysHead;
slot->freeSymKeysHead = symKey->next;
pk11_CloseSession(slot, symKey->session,symKey->sessionOwner);
PK11_USE_THREADS(PZ_DestroyLock(symKey->refLock);)
PORT_Free(symKey);
};
return;
}
/*
* create a symetric key:
* Slot is the slot to create the key in.
* type is the mechainism type
*/
PK11SymKey *
PK11_CreateSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, void *wincx)
{
PK11SymKey *symKey = pk11_getKeyFromList(slot);
if (symKey == NULL) {
return NULL;
}
symKey->type = type;
symKey->data.data = NULL;
symKey->data.len = 0;
symKey->owner = PR_TRUE;
symKey->objectID = CK_INVALID_KEY;
symKey->slot = slot;
symKey->series = slot->series;
symKey->cx = wincx;
symKey->size = 0;
symKey->refCount = 1;
symKey->origin = PK11_OriginNULL;
symKey->origin = PK11_OriginNULL;
PK11_ReferenceSlot(slot);
return symKey;
}
/*
* destroy a symetric key
*/
void
PK11_FreeSymKey(PK11SymKey *symKey)
{
PRBool destroy = PR_FALSE;
PK11SlotInfo *slot;
PRBool freeit = PR_TRUE;
PK11_USE_THREADS(PZ_Lock(symKey->refLock);)
if (symKey->refCount-- == 1) {
destroy= PR_TRUE;
}
PK11_USE_THREADS(PZ_Unlock(symKey->refLock);)
if (destroy) {
if ((symKey->owner) && symKey->objectID != CK_INVALID_KEY) {
pk11_EnterKeyMonitor(symKey);
(void) PK11_GETTAB(symKey->slot)->
C_DestroyObject(symKey->session, symKey->objectID);
pk11_ExitKeyMonitor(symKey);
}
if (symKey->data.data) {
PORT_Memset(symKey->data.data, 0, symKey->data.len);
PORT_Free(symKey->data.data);
}
slot = symKey->slot;
PK11_USE_THREADS(PZ_Lock(slot->freeListLock);)
if (slot->keyCount < slot->maxKeyCount) {
symKey->next = slot->freeSymKeysHead;
slot->freeSymKeysHead = symKey;
slot->keyCount++;
symKey->slot = NULL;
freeit = PR_FALSE;
}
PK11_USE_THREADS(PZ_Unlock(slot->freeListLock);)
if (freeit) {
pk11_CloseSession(symKey->slot, symKey->session,
symKey->sessionOwner);
PK11_USE_THREADS(PZ_DestroyLock(symKey->refLock);)
PORT_Free(symKey);
}
PK11_FreeSlot(slot);
}
}
PK11SymKey *
PK11_ReferenceSymKey(PK11SymKey *symKey)
{
PK11_USE_THREADS(PZ_Lock(symKey->refLock);)
symKey->refCount++;
PK11_USE_THREADS(PZ_Unlock(symKey->refLock);)
return symKey;
}
/*
* turn key handle into an appropriate key object
*/
PK11SymKey *
PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent, PK11Origin origin,
CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID, PRBool owner, void *wincx)
{
PK11SymKey *symKey;
if (keyID == CK_INVALID_KEY) {
return NULL;
}
symKey = PK11_CreateSymKey(slot,type,wincx);
if (symKey == NULL) {
return NULL;
}
symKey->objectID = keyID;
symKey->origin = origin;
symKey->owner = owner;
/* adopt the parent's session */
/* This is only used by SSL. What we really want here is a session
* structure with a ref count so the session goes away only after all the
* keys do. */
if (owner && parent) {
pk11_CloseSession(symKey->slot, symKey->session,symKey->sessionOwner);
symKey->sessionOwner = parent->sessionOwner;
symKey->session = parent->session;
parent->sessionOwner = PR_FALSE;
}
return symKey;
}
/*
* turn key handle into an appropriate key object
*/
PK11SymKey *
PK11_GetWrapKey(PK11SlotInfo *slot, int wrap, CK_MECHANISM_TYPE type,
int series, void *wincx)
{
PK11SymKey *symKey = NULL;
if (slot->series != series) return NULL;
if (slot->refKeys[wrap] == CK_INVALID_KEY) return NULL;
if (type == CKM_INVALID_MECHANISM) type = slot->wrapMechanism;
symKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive,
slot->wrapMechanism, slot->refKeys[wrap], PR_FALSE, wincx);
return symKey;
}
void
PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey)
{
/* save the handle and mechanism for the wrapping key */
/* mark the key and session as not owned by us to they don't get freed
* when the key goes way... that lets us reuse the key later */
slot->refKeys[wrap] = wrapKey->objectID;
wrapKey->owner = PR_FALSE;
wrapKey->sessionOwner = PR_FALSE;
slot->wrapMechanism = wrapKey->type;
}
CK_MECHANISM_TYPE
PK11_GetMechanism(PK11SymKey *symKey)
{
return symKey->type;
}
/*
* figure out if a key is still valid or if it is stale.
*/
PRBool
PK11_VerifyKeyOK(PK11SymKey *key) {
if (!PK11_IsPresent(key->slot)) {
return PR_FALSE;
}
return (PRBool)(key->series == key->slot->series);
}
static PK11SymKey *
pk11_ImportSymKeyWithTempl(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
PK11Origin origin, CK_ATTRIBUTE *keyTemplate,
unsigned int templateCount, SECItem *key, void *wincx)
{
PK11SymKey * symKey;
SECStatus rv;
symKey = PK11_CreateSymKey(slot,type,wincx);
if (symKey == NULL) {
return NULL;
}
symKey->size = key->len;
PK11_SETATTRS(&keyTemplate[templateCount], CKA_VALUE, key->data, key->len);
templateCount++;
if (SECITEM_CopyItem(NULL,&symKey->data,key) != SECSuccess) {
PK11_FreeSymKey(symKey);
return NULL;
}
symKey->origin = origin;
/* import the keys */
rv = PK11_CreateNewObject(slot, symKey->session, keyTemplate,
templateCount, PR_FALSE, &symKey->objectID);
if ( rv != SECSuccess) {
PK11_FreeSymKey(symKey);
return NULL;
}
return symKey;
}
/*
* turn key bits into an appropriate key object
*/
PK11SymKey *
PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,void *wincx)
{
PK11SymKey * symKey;
unsigned int templateCount = 0;
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
CK_BBOOL cktrue = CK_TRUE; /* sigh */
CK_ATTRIBUTE keyTemplate[5];
CK_ATTRIBUTE * attrs = keyTemplate;
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
/* PK11_SETATTRS(attrs, CKA_VALUE, key->data, key->len); attrs++; */
templateCount = attrs - keyTemplate;
PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
keyType = PK11_GetKeyType(type,key->len);
symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, keyTemplate,
templateCount, key, wincx);
return symKey;
}
/*
* import a public key into the desired slot
*/
CK_OBJECT_HANDLE
PK11_ImportPublicKey(PK11SlotInfo *slot, SECKEYPublicKey *pubKey,
PRBool isToken)
{
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
CK_OBJECT_HANDLE objectID;
CK_ATTRIBUTE theTemplate[10];
CK_ATTRIBUTE *signedattr = NULL;
CK_ATTRIBUTE *attrs = theTemplate;
int signedcount = 0;
int templateCount = 0;
SECStatus rv;
/* if we already have an object in the desired slot, use it */
if (!isToken && pubKey->pkcs11Slot == slot) {
return pubKey->pkcs11ID;
}
/* free the existing key */
if (pubKey->pkcs11Slot != NULL) {
PK11SlotInfo *oSlot = pubKey->pkcs11Slot;
PK11_EnterSlotMonitor(oSlot);
(void) PK11_GETTAB(oSlot)->C_DestroyObject(oSlot->session,
pubKey->pkcs11ID);
PK11_ExitSlotMonitor(oSlot);
PK11_FreeSlot(oSlot);
pubKey->pkcs11Slot = NULL;
}
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
PK11_SETATTRS(attrs, CKA_TOKEN, isToken ? &cktrue : &ckfalse,
sizeof(CK_BBOOL) ); attrs++;
/* now import the key */
{
switch (pubKey->keyType) {
case rsaKey:
keyType = CKK_RSA;
PK11_SETATTRS(attrs, CKA_WRAP, &cktrue, sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_ENCRYPT, &cktrue,
sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL)); attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_MODULUS, pubKey->u.rsa.modulus.data,
pubKey->u.rsa.modulus.len); attrs++;
PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
pubKey->u.rsa.publicExponent.data,
pubKey->u.rsa.publicExponent.len); attrs++;
break;
case dsaKey:
keyType = CKK_DSA;
PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dsa.params.prime.data,
pubKey->u.dsa.params.prime.len); attrs++;
PK11_SETATTRS(attrs,CKA_SUBPRIME,pubKey->u.dsa.params.subPrime.data,
pubKey->u.dsa.params.subPrime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dsa.params.base.data,
pubKey->u.dsa.params.base.len); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dsa.publicValue.data,
pubKey->u.dsa.publicValue.len); attrs++;
break;
case fortezzaKey:
keyType = CKK_DSA;
PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_PRIME,pubKey->u.fortezza.params.prime.data,
pubKey->u.fortezza.params.prime.len); attrs++;
PK11_SETATTRS(attrs,CKA_SUBPRIME,
pubKey->u.fortezza.params.subPrime.data,
pubKey->u.fortezza.params.subPrime.len);attrs++;
PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.fortezza.params.base.data,
pubKey->u.fortezza.params.base.len); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.fortezza.DSSKey.data,
pubKey->u.fortezza.DSSKey.len); attrs++;
break;
case dhKey:
keyType = CKK_DH;
PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dh.prime.data,
pubKey->u.dh.prime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dh.base.data,
pubKey->u.dh.base.len); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dh.publicValue.data,
pubKey->u.dh.publicValue.len); attrs++;
break;
/* what about fortezza??? */
default:
PORT_SetError( SEC_ERROR_BAD_KEY );
return CK_INVALID_KEY;
}
templateCount = attrs - theTemplate;
signedcount = attrs - signedattr;
PORT_Assert(templateCount <= (sizeof(theTemplate)/sizeof(CK_ATTRIBUTE)));
for (attrs=signedattr; signedcount; attrs++, signedcount--) {
pk11_SignedToUnsigned(attrs);
}
rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, theTemplate,
templateCount, isToken, &objectID);
if ( rv != SECSuccess) {
return CK_INVALID_KEY;
}
}
pubKey->pkcs11ID = objectID;
pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
return objectID;
}
/*
* return the slot associated with a symetric key
*/
PK11SlotInfo *
PK11_GetSlotFromKey(PK11SymKey *symKey)
{
return PK11_ReferenceSlot(symKey->slot);
}
PK11SymKey *
PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *keyID,
void *wincx)
{
CK_ATTRIBUTE findTemp[4];
CK_ATTRIBUTE *attrs;
CK_BBOOL ckTrue = CK_TRUE;
CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
int tsize = 0;
CK_OBJECT_HANDLE key_id;
attrs = findTemp;
PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++;
PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++;
if (keyID) {
PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len); attrs++;
}
tsize = attrs - findTemp;
PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE));
key_id = pk11_FindObjectByTemplate(slot,findTemp,tsize);
if (key_id == CK_INVALID_KEY) {
return NULL;
}
return PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive, type, key_id,
PR_FALSE, wincx);
}
void *
PK11_GetWindow(PK11SymKey *key)
{
return key->cx;
}
/*
* extract a symetric key value. NOTE: if the key is sensitive, we will
* not be able to do this operation. This function is used to move
* keys from one token to another */
SECStatus
PK11_ExtractKeyValue(PK11SymKey *symKey)
{
if (symKey->data.data != NULL) return SECSuccess;
if (symKey->slot == NULL) {
PORT_SetError( SEC_ERROR_INVALID_KEY );
return SECFailure;
}
return PK11_ReadAttribute(symKey->slot,symKey->objectID,CKA_VALUE,NULL,
&symKey->data);
}
SECItem *
__PK11_GetKeyData(PK11SymKey *symKey)
{
return &symKey->data;
}
SECItem *
PK11_GetKeyData(PK11SymKey *symKey)
{
return __PK11_GetKeyData(symKey);
}
/*
* take an attribute and copy it into a secitem, converting unsigned to signed.
*/
static CK_RV
pk11_Attr2SecItem(PRArenaPool *arena, CK_ATTRIBUTE *attr, SECItem *item) {
unsigned char *dataPtr;
item->len = attr->ulValueLen;
dataPtr = (unsigned char*) PORT_ArenaAlloc(arena, item->len+1);
if ( dataPtr == NULL) {
return CKR_HOST_MEMORY;
}
*dataPtr = 0;
item->data = dataPtr+1;
PORT_Memcpy(item->data,attr->pValue,item->len);
if (item->data[0] & 0x80) {
item->data = item->data-1;
item->len++;
}
return CKR_OK;
}
/*
* extract a public key from a slot and id
*/
SECKEYPublicKey *
PK11_ExtractPublicKey(PK11SlotInfo *slot,KeyType keyType,CK_OBJECT_HANDLE id)
{
CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
PRArenaPool *arena;
PRArenaPool *tmp_arena;
SECKEYPublicKey *pubKey;
int templateCount = 0;
CK_KEY_TYPE pk11KeyType;
CK_RV crv;
CK_ATTRIBUTE template[8];
CK_ATTRIBUTE *attrs= template;
CK_ATTRIBUTE *modulus,*exponent,*base,*prime,*subprime,*value;
/* if we didn't know the key type, get it */
if (keyType== nullKey) {
pk11KeyType = PK11_ReadULongAttribute(slot,id,CKA_KEY_TYPE);
if (pk11KeyType == CK_UNAVAILABLE_INFORMATION) {
return NULL;
}
switch (pk11KeyType) {
case CKK_RSA:
keyType = rsaKey;
break;
case CKK_DSA:
keyType = dsaKey;
break;
case CKK_DH:
keyType = dhKey;
break;
default:
PORT_SetError( SEC_ERROR_BAD_KEY );
return NULL;
}
}
/* now we need to create space for the public key */
arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) return NULL;
tmp_arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
if (tmp_arena == NULL) {
PORT_FreeArena (arena, PR_FALSE);
return NULL;
}
pubKey = (SECKEYPublicKey *)
PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
if (pubKey == NULL) {
PORT_FreeArena (arena, PR_FALSE);
PORT_FreeArena (tmp_arena, PR_FALSE);
return NULL;
}
pubKey->arena = arena;
pubKey->keyType = keyType;
pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
pubKey->pkcs11ID = id;
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass,
sizeof(keyClass)); attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &pk11KeyType,
sizeof(pk11KeyType) ); attrs++;
switch (pubKey->keyType) {
case rsaKey:
modulus = attrs;
PK11_SETATTRS(attrs, CKA_MODULUS, NULL, 0); attrs++;
exponent = attrs;
PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, NULL, 0); attrs++;
templateCount = attrs - template;
PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
if (crv != CKR_OK) break;
if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_RSA)) {
crv = CKR_OBJECT_HANDLE_INVALID;
break;
}
crv = pk11_Attr2SecItem(arena,modulus,&pubKey->u.rsa.modulus);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,exponent,&pubKey->u.rsa.publicExponent);
if (crv != CKR_OK) break;
break;
case dsaKey:
prime = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++;
subprime = attrs;
PK11_SETATTRS(attrs, CKA_SUBPRIME, NULL, 0); attrs++;
base = attrs;
PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++;
value = attrs;
PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++;
templateCount = attrs - template;
PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
if (crv != CKR_OK) break;
if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DSA)) {
crv = CKR_OBJECT_HANDLE_INVALID;
break;
}
crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dsa.params.prime);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,subprime,&pubKey->u.dsa.params.subPrime);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dsa.params.base);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dsa.publicValue);
if (crv != CKR_OK) break;
break;
case dhKey:
prime = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++;
base = attrs;
PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++;
value =attrs;
PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++;
templateCount = attrs - template;
PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
if (crv != CKR_OK) break;
if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DH)) {
crv = CKR_OBJECT_HANDLE_INVALID;
break;
}
crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dh.prime);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dh.base);
if (crv != CKR_OK) break;
crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dh.publicValue);
if (crv != CKR_OK) break;
break;
case fortezzaKey:
case nullKey:
default:
crv = CKR_OBJECT_HANDLE_INVALID;
break;
}
PORT_FreeArena(tmp_arena,PR_FALSE);
if (crv != CKR_OK) {
PORT_FreeArena(arena,PR_FALSE);
PK11_FreeSlot(slot);
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
return pubKey;
}
/*
* Build a Private Key structure from raw PKCS #11 information.
*/
SECKEYPrivateKey *
PK11_MakePrivKey(PK11SlotInfo *slot, KeyType keyType,
PRBool isTemp, CK_OBJECT_HANDLE privID, void *wincx)
{
PRArenaPool *arena;
SECKEYPrivateKey *privKey;
/* don't know? look it up */
if (keyType == nullKey) {
CK_KEY_TYPE pk11Type = CKK_RSA;
pk11Type = PK11_ReadULongAttribute(slot,privID,CKA_KEY_TYPE);
isTemp = (PRBool)!PK11_HasAttributeSet(slot,privID,CKA_TOKEN);
switch (pk11Type) {
case CKK_RSA: keyType = rsaKey; break;
case CKK_DSA: keyType = dsaKey; break;
case CKK_DH: keyType = dhKey; break;
case CKK_KEA: keyType = fortezzaKey; break;
default:
break;
}
}
/* now we need to create space for the private key */
arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) return NULL;
privKey = (SECKEYPrivateKey *)
PORT_ArenaZAlloc(arena, sizeof(SECKEYPrivateKey));
if (privKey == NULL) {
PORT_FreeArena(arena, PR_FALSE);
return NULL;
}
privKey->arena = arena;
privKey->keyType = keyType;
privKey->pkcs11Slot = PK11_ReferenceSlot(slot);
privKey->pkcs11ID = privID;
privKey->pkcs11IsTemp = isTemp;
privKey->wincx = wincx;
return privKey;
}
/* return the keylength if possible. '0' if not */
unsigned int
PK11_GetKeyLength(PK11SymKey *key)
{
if (key->size != 0) return key->size ;
if (key->data.data == NULL) {
PK11_ExtractKeyValue(key);
}
/* key is probably secret. Look up it's type and length */
/* this is new PKCS #11 version 2.0 functionality. */
if (key->size == 0) {
CK_ULONG keyLength;
keyLength = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_VALUE_LEN);
/* doesn't have a length field, check the known PKCS #11 key types,
* which don't have this field */
if (keyLength == CK_UNAVAILABLE_INFORMATION) {
CK_KEY_TYPE keyType;
keyType = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_KEY_TYPE);
switch (keyType) {
case CKK_DES: key->size = 8; break;
case CKK_DES2: key->size = 16; break;
case CKK_DES3: key->size = 24; break;
case CKK_SKIPJACK: key->size = 10; break;
case CKK_BATON: key->size = 20; break;
case CKK_JUNIPER: key->size = 20; break;
case CKK_GENERIC_SECRET:
if (key->type == CKM_SSL3_PRE_MASTER_KEY_GEN) {
key->size=48;
}
break;
default: break;
}
} else {
key->size = (unsigned int)keyLength;
}
}
return key->size;
}
/* return the strength of a key. This is different from length in that
* 1) it returns the size in bits, and 2) it returns only the secret portions
* of the key minus any checksums or parity.
*/
unsigned int
PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid)
{
int size=0;
CK_MECHANISM_TYPE mechanism= CKM_INVALID_MECHANISM; /* RC2 only */
SECItem *param = NULL; /* RC2 only */
CK_RC2_CBC_PARAMS *rc2_params = NULL; /* RC2 ONLY */
unsigned int effectiveBits = 0; /* RC2 ONLY */
switch (PK11_GetKeyType(key->type,0)) {
case CKK_CDMF:
return 40;
case CKK_DES:
return 56;
case CKK_DES3:
case CKK_DES2:
size = PK11_GetKeyLength(key);
if (size == 16) {
/* double des */
return 112; /* 16*7 */
}
return 168;
/*
* RC2 has is different than other ciphers in that it allows the user
* to deprecating keysize while still requiring all the bits for the
* original key. The info
* on what the effective key strength is in the parameter for the key.
* In S/MIME this parameter is stored in the DER encoded algid. In Our
* other uses of RC2, effectiveBits == keyBits, so this code functions
* correctly without an algid.
*/
case CKK_RC2:
/* if no algid was provided, fall through to default */
if (!algid) {
break;
}
/* verify that the algid is for RC2 */
mechanism = PK11_AlgtagToMechanism(SECOID_GetAlgorithmTag(algid));
if ((mechanism != CKM_RC2_CBC) && (mechanism != CKM_RC2_ECB)) {
break;
}
/* now get effective bits from the algorithm ID. */
param = PK11_ParamFromAlgid(algid);
/* if we couldn't get memory just use key length */
if (param == NULL) {
break;
}
rc2_params = (CK_RC2_CBC_PARAMS *) param->data;
/* paranoia... shouldn't happen */
PORT_Assert(param->data != NULL);
if (param->data == NULL) {
SECITEM_FreeItem(param,PR_TRUE);
break;
}
effectiveBits = (unsigned int)rc2_params->ulEffectiveBits;
SECITEM_FreeItem(param,PR_TRUE);
param = NULL; rc2_params=NULL; /* paranoia */
/* we have effective bits, is and allocated memory is free, now
* we need to return the smaller of effective bits and keysize */
size = PK11_GetKeyLength(key);
if ((unsigned int)size*8 > effectiveBits) {
return effectiveBits;
}
return size*8; /* the actual key is smaller, the strength can't be
* greater than the actual key size */
default:
break;
}
return PK11_GetKeyLength(key) * 8;
}
/* Make a Key type to an appropriate signing/verification mechanism */
static CK_MECHANISM_TYPE
pk11_mapSignKeyType(KeyType keyType)
{
switch (keyType) {
case rsaKey:
return CKM_RSA_PKCS;
case fortezzaKey:
case dsaKey:
return CKM_DSA;
case dhKey:
default:
break;
}
return CKM_INVALID_MECHANISM;
}
static CK_MECHANISM_TYPE
pk11_mapWrapKeyType(KeyType keyType)
{
switch (keyType) {
case rsaKey:
return CKM_RSA_PKCS;
/* Add fortezza?? */
default:
break;
}
return CKM_INVALID_MECHANISM;
}
/*
* Some non-compliant PKCS #11 vendors do not give us the modulus, so actually
* set up a signature to get the signaure length.
*/
static int
pk11_backupGetSignLength(SECKEYPrivateKey *key)
{
PK11SlotInfo *slot = key->pkcs11Slot;
CK_MECHANISM mech = {0, NULL, 0 };
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_ULONG len;
CK_RV crv;
unsigned char h_data[20] = { 0 };
unsigned char buf[20]; /* obviously to small */
CK_ULONG smallLen = sizeof(buf);
mech.mechanism = pk11_mapSignKeyType(key->keyType);
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_SignInit(session,&mech,key->pkcs11ID);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return -1;
}
len = 0;
crv = PK11_GETTAB(slot)->C_Sign(session,h_data,sizeof(h_data),
NULL, &len);
/* now call C_Sign with too small a buffer to clear the session state */
(void) PK11_GETTAB(slot)->
C_Sign(session,h_data,sizeof(h_data),buf,&smallLen);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return -1;
}
return len;
}
/*
* get the length of a signature object based on the key
*/
int
PK11_SignatureLen(SECKEYPrivateKey *key)
{
PK11SlotInfo *slot = key->pkcs11Slot;
int val;
switch (key->keyType) {
case rsaKey:
val = PK11_GetPrivateModulusLen(key);
if (val == -1) {
break; /* failed */
}
return (unsigned long) val;
case fortezzaKey:
case dsaKey:
return 40;
default:
break;
}
PORT_SetError( SEC_ERROR_INVALID_KEY );
return 0;
}
PK11SlotInfo *
PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key)
{
PK11SlotInfo *slot = key->pkcs11Slot;
slot = PK11_ReferenceSlot(slot);
return slot;
}
/*
* Get the modulus length for raw parsing
*/
int
PK11_GetPrivateModulusLen(SECKEYPrivateKey *key)
{
CK_ATTRIBUTE theTemplate = { CKA_MODULUS, NULL, 0 };
PK11SlotInfo *slot = key->pkcs11Slot;
CK_RV crv;
int length;
switch (key->keyType) {
case rsaKey:
crv = PK11_GetAttributes(NULL, slot, key->pkcs11ID, &theTemplate, 1);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return -1;
}
length = theTemplate.ulValueLen;
if ( *(unsigned char *)theTemplate.pValue == 0) {
length--;
}
if (theTemplate.pValue != NULL)
PORT_Free(theTemplate.pValue);
return (int) length;
case fortezzaKey:
case dsaKey:
case dhKey:
default:
break;
}
if (theTemplate.pValue != NULL)
PORT_Free(theTemplate.pValue);
PORT_SetError( SEC_ERROR_INVALID_KEY );
return -1;
}
/*
* copy a key (or any other object) on a token
*/
CK_OBJECT_HANDLE
PK11_CopyKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE srcObject)
{
CK_OBJECT_HANDLE destObject;
CK_RV crv;
PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_CopyObject(slot->session,srcObject,NULL,0,
&destObject);
PK11_ExitSlotMonitor(slot);
if (crv == CKR_OK) return destObject;
PORT_SetError( PK11_MapError(crv) );
return CK_INVALID_KEY;
}
PK11SymKey *
pk11_KeyExchange(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey);
/*
* The next two utilities are to deal with the fact that a given operation
* may be a multi-slot affair. This creates a new key object that is copied
* into the new slot.
*/
PK11SymKey *
pk11_CopyToSlot(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey)
{
SECStatus rv;
PK11SymKey *newKey = NULL;
/* Extract the raw key data if possible */
if (symKey->data.data == NULL) {
rv = PK11_ExtractKeyValue(symKey);
/* KEY is sensitive, we're try key exchanging it. */
if (rv != SECSuccess) {
return pk11_KeyExchange(slot, type, operation, symKey);
}
}
newKey = PK11_ImportSymKey(slot, type, symKey->origin, operation,
&symKey->data, symKey->cx);
if (newKey == NULL) newKey = pk11_KeyExchange(slot,type,operation,symKey);
return newKey;
}
/*
* Make sure the slot we are in the correct slot for the operation
*/
static PK11SymKey *
pk11_ForceSlot(PK11SymKey *symKey,CK_MECHANISM_TYPE type,
CK_ATTRIBUTE_TYPE operation)
{
PK11SlotInfo *slot = symKey->slot;
PK11SymKey *newKey = NULL;
if ((slot== NULL) || !PK11_DoesMechanism(slot,type)) {
slot = PK11_GetBestSlot(type,symKey->cx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
newKey = pk11_CopyToSlot(slot, type, operation, symKey);
PK11_FreeSlot(slot);
}
return newKey;
}
/*
* Use the token to Generate a key. keySize must be 'zero' for fixed key
* length algorithms. NOTE: this means we can never generate a DES2 key
* from this interface!
*/
PK11SymKey *
PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
int keySize, SECItem *keyid, PRBool isToken, void *wincx)
{
PK11SymKey *symKey;
CK_ATTRIBUTE genTemplate[5];
CK_ATTRIBUTE *attrs = genTemplate;
int count = sizeof(genTemplate)/sizeof(genTemplate[0]);
CK_SESSION_HANDLE session;
CK_MECHANISM mechanism;
CK_RV crv;
PRBool weird = PR_FALSE; /* hack for fortezza */
CK_BBOOL ckfalse = CK_FALSE;
CK_BBOOL cktrue = CK_TRUE;
CK_ULONG ck_key_size; /* only used for variable-length keys */
if ((keySize == -1) && (type == CKM_SKIPJACK_CBC64)) {
weird = PR_TRUE;
keySize = 0;
}
/* TNH: Isn't this redundant, since "handleKey" will set defaults? */
PK11_SETATTRS(attrs, (!weird)
? CKA_ENCRYPT : CKA_DECRYPT, &cktrue, sizeof(CK_BBOOL)); attrs++;
if (keySize != 0) {
ck_key_size = keySize; /* Convert to PK11 type */
PK11_SETATTRS(attrs, CKA_VALUE_LEN, &ck_key_size, sizeof(ck_key_size));
attrs++;
}
/* Include key id value if provided */
if (keyid) {
PK11_SETATTRS(attrs, CKA_ID, keyid->data, keyid->len); attrs++;
}
if (isToken) {
PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue)); attrs++;
}
PK11_SETATTRS(attrs, CKA_SIGN, &cktrue, sizeof(cktrue)); attrs++;
count = attrs - genTemplate;
PR_ASSERT(count <= sizeof(genTemplate)/sizeof(CK_ATTRIBUTE));
/* find a slot to generate the key into */
/* Only do slot management if this is not a token key */
if (!isToken && (slot == NULL || !PK11_DoesMechanism(slot,type))) {
PK11SlotInfo *bestSlot;
bestSlot = PK11_GetBestSlot(type,wincx); /* TNH: references the slot? */
if (bestSlot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
symKey = PK11_CreateSymKey(bestSlot,type,wincx);
PK11_FreeSlot(bestSlot);
} else {
symKey = PK11_CreateSymKey(slot, type, wincx);
}
if (symKey == NULL) return NULL;
symKey->size = keySize;
symKey->origin = (!weird) ? PK11_OriginGenerated : PK11_OriginFortezzaHack;
/* Initialize the Key Gen Mechanism */
mechanism.mechanism = PK11_GetKeyGen(type);
if (mechanism.mechanism == CKM_FAKE_RANDOM) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
/* Set the parameters for the key gen if provided */
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
if (param) {
mechanism.pParameter = param->data;
mechanism.ulParameterLen = param->len;
}
/* Get session and perform locking */
if (isToken) {
session = PK11_GetRWSession(symKey->slot); /* Should always be original slot */
} else {
session = symKey->session;
pk11_EnterKeyMonitor(symKey);
}
crv = PK11_GETTAB(symKey->slot)->C_GenerateKey(session,
&mechanism, genTemplate, count, &symKey->objectID);
/* Release lock and session */
if (isToken) {
PK11_RestoreROSession(symKey->slot, session);
} else {
pk11_ExitKeyMonitor(symKey);
}
if (crv != CKR_OK) {
PK11_FreeSymKey(symKey);
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
return symKey;
}
PK11SymKey *
PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
int keySize, void *wincx)
{
return PK11_TokenKeyGen(slot, type, param, keySize, 0, PR_FALSE, wincx);
}
/* --- */
PK11SymKey *
PK11_GenDES3TokenKey(PK11SlotInfo *slot, SECItem *keyid, void *cx)
{
return PK11_TokenKeyGen(slot, CKM_DES3_CBC, 0, 0, keyid, PR_TRUE, cx);
}
/*
* PKCS #11 pairwise consistency check utilized to validate key pair.
*/
static SECStatus
pk11_PairwiseConsistencyCheck(SECKEYPublicKey *pubKey,
SECKEYPrivateKey *privKey, CK_MECHANISM *mech, void* wincx )
{
/* Variables used for Encrypt/Decrypt functions. */
unsigned char *known_message = (unsigned char *)"Known Crypto Message";
CK_BBOOL isEncryptable = CK_FALSE;
CK_BBOOL canSignVerify = CK_FALSE;
CK_BBOOL isDerivable = CK_FALSE;
unsigned char plaintext[PAIRWISE_MESSAGE_LENGTH];
CK_ULONG bytes_decrypted;
PK11SlotInfo *slot;
CK_OBJECT_HANDLE id;
unsigned char *ciphertext;
unsigned char *text_compared;
CK_ULONG max_bytes_encrypted;
CK_ULONG bytes_encrypted;
CK_ULONG bytes_compared;
CK_RV crv;
/* Variables used for Signature/Verification functions. */
unsigned char *known_digest = (unsigned char *)"Mozilla Rules World!";
SECItem signature;
SECItem digest; /* always uses SHA-1 digest */
int signature_length;
SECStatus rv;
/**************************************************/
/* Pairwise Consistency Check of Encrypt/Decrypt. */
/**************************************************/
isEncryptable = PK11_HasAttributeSet( privKey->pkcs11Slot,
privKey->pkcs11ID, CKA_DECRYPT );
/* If the encryption attribute is set; attempt to encrypt */
/* with the public key and decrypt with the private key. */
if( isEncryptable ) {
/* Find a module to encrypt against */
slot = PK11_GetBestSlot(pk11_mapWrapKeyType(privKey->keyType),wincx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
id = PK11_ImportPublicKey(slot,pubKey,PR_FALSE);
if (id == CK_INVALID_KEY) {
PK11_FreeSlot(slot);
return SECFailure;
}
/* Compute max bytes encrypted from modulus length of private key. */
max_bytes_encrypted = PK11_GetPrivateModulusLen( privKey );
/* Prepare for encryption using the public key. */
PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB( slot )->C_EncryptInit( slot->session,
mech, id );
if( crv != CKR_OK ) {
PK11_ExitSlotMonitor(slot);
PORT_SetError( PK11_MapError( crv ) );
PK11_FreeSlot(slot);
return SECFailure;
}
/* Allocate space for ciphertext. */
ciphertext = (unsigned char *) PORT_Alloc( max_bytes_encrypted );
if( ciphertext == NULL ) {
PK11_ExitSlotMonitor(slot);
PORT_SetError( SEC_ERROR_NO_MEMORY );
PK11_FreeSlot(slot);
return SECFailure;
}
/* Initialize bytes encrypted to max bytes encrypted. */
bytes_encrypted = max_bytes_encrypted;
/* Encrypt using the public key. */
crv = PK11_GETTAB( slot )->C_Encrypt( slot->session,
known_message,
PAIRWISE_MESSAGE_LENGTH,
ciphertext,
&bytes_encrypted );
PK11_ExitSlotMonitor(slot);
PK11_FreeSlot(slot);
if( crv != CKR_OK ) {
PORT_SetError( PK11_MapError( crv ) );
PORT_Free( ciphertext );
return SECFailure;
}
/* Always use the smaller of these two values . . . */
bytes_compared = ( bytes_encrypted > PAIRWISE_MESSAGE_LENGTH )
? PAIRWISE_MESSAGE_LENGTH
: bytes_encrypted;
/* If there was a failure, the plaintext */
/* goes at the end, therefore . . . */
text_compared = ( bytes_encrypted > PAIRWISE_MESSAGE_LENGTH )
? (ciphertext + bytes_encrypted -
PAIRWISE_MESSAGE_LENGTH )
: ciphertext;
/* Check to ensure that ciphertext does */
/* NOT EQUAL known input message text */
/* per FIPS PUB 140-1 directive. */
if( ( bytes_encrypted != max_bytes_encrypted ) ||
( PORT_Memcmp( text_compared, known_message,
bytes_compared ) == 0 ) ) {
/* Set error to Invalid PRIVATE Key. */
PORT_SetError( SEC_ERROR_INVALID_KEY );
PORT_Free( ciphertext );
return SECFailure;
}
slot = privKey->pkcs11Slot;
/* Prepare for decryption using the private key. */
PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB( slot )->C_DecryptInit( slot->session,
mech,
privKey->pkcs11ID );
if( crv != CKR_OK ) {
PK11_ExitSlotMonitor(slot);
PORT_SetError( PK11_MapError(crv) );
PORT_Free( ciphertext );
PK11_FreeSlot(slot);
return SECFailure;
}
/* Initialize bytes decrypted to be the */
/* expected PAIRWISE_MESSAGE_LENGTH. */
bytes_decrypted = PAIRWISE_MESSAGE_LENGTH;
/* Decrypt using the private key. */
/* NOTE: No need to reset the */
/* value of bytes_encrypted. */
crv = PK11_GETTAB( slot )->C_Decrypt( slot->session,
ciphertext,
bytes_encrypted,
plaintext,
&bytes_decrypted );
PK11_ExitSlotMonitor(slot);
/* Finished with ciphertext; free it. */
PORT_Free( ciphertext );
if( crv != CKR_OK ) {
PORT_SetError( PK11_MapError(crv) );
PK11_FreeSlot(slot);
return SECFailure;
}
/* Check to ensure that the output plaintext */
/* does EQUAL known input message text. */
if( ( bytes_decrypted != PAIRWISE_MESSAGE_LENGTH ) ||
( PORT_Memcmp( plaintext, known_message,
PAIRWISE_MESSAGE_LENGTH ) != 0 ) ) {
/* Set error to Bad PUBLIC Key. */
PORT_SetError( SEC_ERROR_BAD_KEY );
PK11_FreeSlot(slot);
return SECFailure;
}
}
/**********************************************/
/* Pairwise Consistency Check of Sign/Verify. */
/**********************************************/
canSignVerify = PK11_HasAttributeSet ( privKey->pkcs11Slot,
privKey->pkcs11ID, CKA_SIGN);
if (canSignVerify)
{
/* Initialize signature and digest data. */
signature.data = NULL;
digest.data = NULL;
/* Determine length of signature. */
signature_length = PK11_SignatureLen( privKey );
if( signature_length == 0 )
goto failure;
/* Allocate space for signature data. */
signature.data = (unsigned char *) PORT_Alloc( signature_length );
if( signature.data == NULL ) {
PORT_SetError( SEC_ERROR_NO_MEMORY );
goto failure;
}
/* Allocate space for known digest data. */
digest.data = (unsigned char *) PORT_Alloc( PAIRWISE_DIGEST_LENGTH );
if( digest.data == NULL ) {
PORT_SetError( SEC_ERROR_NO_MEMORY );
goto failure;
}
/* "Fill" signature type and length. */
signature.type = PAIRWISE_SECITEM_TYPE;
signature.len = signature_length;
/* "Fill" digest with known SHA-1 digest parameters. */
digest.type = PAIRWISE_SECITEM_TYPE;
PORT_Memcpy( digest.data, known_digest, PAIRWISE_DIGEST_LENGTH );
digest.len = PAIRWISE_DIGEST_LENGTH;
/* Sign the known hash using the private key. */
rv = PK11_Sign( privKey, &signature, &digest );
if( rv != SECSuccess )
goto failure;
/* Verify the known hash using the public key. */
rv = PK11_Verify( pubKey, &signature, &digest, wincx );
if( rv != SECSuccess )
goto failure;
/* Free signature and digest data. */
PORT_Free( signature.data );
PORT_Free( digest.data );
}
/**********************************************/
/* Pairwise Consistency Check for Derivation */
/**********************************************/
isDerivable = PK11_HasAttributeSet ( privKey->pkcs11Slot,
privKey->pkcs11ID, CKA_DERIVE);
if (isDerivable)
{
/*
* We are not doing consistency check for Diffie-Hellman Key -
* otherwise it would be here
*/
}
return SECSuccess;
failure:
if( signature.data != NULL )
PORT_Free( signature.data );
if( digest.data != NULL )
PORT_Free( digest.data );
return SECFailure;
}
/*
* take a private key in one pkcs11 module and load it into another:
* NOTE: the source private key is a rare animal... it can't be sensitive.
* This is used to do a key gen using one pkcs11 module and storing the
* result into another.
*/
SECKEYPrivateKey *
pk11_loadPrivKey(PK11SlotInfo *slot,SECKEYPrivateKey *privKey,
SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive)
{
CK_ATTRIBUTE privTemplate[] = {
/* class must be first */
{ CKA_CLASS, NULL, 0 },
{ CKA_KEY_TYPE, NULL, 0 },
/* these three must be next */
{ CKA_TOKEN, NULL, 0 },
{ CKA_PRIVATE, NULL, 0 },
{ CKA_SENSITIVE, NULL, 0 },
{ CKA_ID, NULL, 0 },
#ifdef notdef
{ CKA_LABEL, NULL, 0 },
{ CKA_SUBJECT, NULL, 0 },
#endif
/* RSA */
{ CKA_MODULUS, NULL, 0 },
{ CKA_PRIVATE_EXPONENT, NULL, 0 },
{ CKA_PUBLIC_EXPONENT, NULL, 0 },
{ CKA_PRIME_1, NULL, 0 },
{ CKA_PRIME_2, NULL, 0 },
{ CKA_EXPONENT_1, NULL, 0 },
{ CKA_EXPONENT_2, NULL, 0 },
{ CKA_COEFFICIENT, NULL, 0 },
};
CK_ATTRIBUTE *attrs = NULL, *ap;
int templateSize = sizeof(privTemplate)/sizeof(privTemplate[0]);
PRArenaPool *arena;
CK_OBJECT_HANDLE objectID;
int i, count = 0;
int extra_count = 0;
CK_RV crv;
SECStatus rv;
for (i=0; i < templateSize; i++) {
if (privTemplate[i].type == CKA_MODULUS) {
attrs= &privTemplate[i];
count = i;
break;
}
}
PORT_Assert(attrs != NULL);
if (attrs == NULL) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return NULL;
}
ap = attrs;
switch (privKey->keyType) {
case rsaKey:
count = templateSize;
extra_count = templateSize - (attrs - privTemplate);
break;
case dsaKey:
ap->type = CKA_PRIME; ap++; count++; extra_count++;
ap->type = CKA_SUBPRIME; ap++; count++; extra_count++;
ap->type = CKA_BASE; ap++; count++; extra_count++;
ap->type = CKA_VALUE; ap++; count++; extra_count++;
break;
case dhKey:
ap->type = CKA_PRIME; ap++; count++; extra_count++;
ap->type = CKA_BASE; ap++; count++; extra_count++;
ap->type = CKA_VALUE; ap++; count++; extra_count++;
break;
default:
count = 0;
extra_count = 0;
break;
}
if (count == 0) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return NULL;
}
arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) return NULL;
/*
* read out the old attributes.
*/
crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID,
privTemplate,count);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
PORT_FreeArena(arena, PR_TRUE);
return NULL;
}
/* Reset sensitive, token, and private */
*(CK_BBOOL *)(privTemplate[2].pValue) = token ? CK_TRUE : CK_FALSE;
*(CK_BBOOL *)(privTemplate[3].pValue) = token ? CK_TRUE : CK_FALSE;
*(CK_BBOOL *)(privTemplate[4].pValue) = sensitive ? CK_TRUE : CK_FALSE;
/* Not everyone can handle zero padded key values, give
* them the raw data as unsigned */
for (ap=attrs; extra_count; ap++, extra_count--) {
pk11_SignedToUnsigned(ap);
}
/* now Store the puppies */
rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, privTemplate,
count, token, &objectID);
PORT_FreeArena(arena, PR_TRUE);
if (rv != SECSuccess) {
return NULL;
}
/* try loading the public key as a token object */
if (pubKey) {
PK11_ImportPublicKey(slot, pubKey, PR_TRUE);
if (pubKey->pkcs11Slot) {
PK11_FreeSlot(pubKey->pkcs11Slot);
pubKey->pkcs11Slot = NULL;
pubKey->pkcs11ID = CK_INVALID_KEY;
}
}
/* build new key structure */
return PK11_MakePrivKey(slot, privKey->keyType, (PRBool)!token,
objectID, privKey->wincx);
}
/*
* Use the token to Generate a key. keySize must be 'zero' for fixed key
* length algorithms. NOTE: this means we can never generate a DES2 key
* from this interface!
*/
SECKEYPrivateKey *
PK11_GenerateKeyPair(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
void *param, SECKEYPublicKey **pubKey, PRBool token,
PRBool sensitive, void *wincx)
{
/* we have to use these native types because when we call PKCS 11 modules
* we have to make sure that we are using the correct sizes for all the
* parameters. */
CK_BBOOL ckfalse = CK_FALSE;
CK_BBOOL cktrue = CK_TRUE;
CK_ULONG modulusBits;
CK_BYTE publicExponent[4];
CK_ATTRIBUTE privTemplate[] = {
{ CKA_SENSITIVE, NULL, 0},
{ CKA_TOKEN, NULL, 0},
{ CKA_PRIVATE, NULL, 0},
{ CKA_DERIVE, NULL, 0},
{ CKA_UNWRAP, NULL, 0},
{ CKA_SIGN, NULL, 0},
{ CKA_DECRYPT, NULL, 0},
};
CK_ATTRIBUTE rsaPubTemplate[] = {
{ CKA_MODULUS_BITS, NULL, 0},
{ CKA_PUBLIC_EXPONENT, NULL, 0},
{ CKA_TOKEN, NULL, 0},
{ CKA_DERIVE, NULL, 0},
{ CKA_WRAP, NULL, 0},
{ CKA_VERIFY, NULL, 0},
{ CKA_VERIFY_RECOVER, NULL, 0},
{ CKA_ENCRYPT, NULL, 0},
};
CK_ATTRIBUTE dsaPubTemplate[] = {
{ CKA_PRIME, NULL, 0 },
{ CKA_SUBPRIME, NULL, 0 },
{ CKA_BASE, NULL, 0 },
{ CKA_TOKEN, NULL, 0},
{ CKA_DERIVE, NULL, 0},
{ CKA_WRAP, NULL, 0},
{ CKA_VERIFY, NULL, 0},
{ CKA_VERIFY_RECOVER, NULL, 0},
{ CKA_ENCRYPT, NULL, 0},
};
CK_ATTRIBUTE dhPubTemplate[] = {
{ CKA_PRIME, NULL, 0 },
{ CKA_BASE, NULL, 0 },
{ CKA_TOKEN, NULL, 0},
{ CKA_DERIVE, NULL, 0},
{ CKA_WRAP, NULL, 0},
{ CKA_VERIFY, NULL, 0},
{ CKA_VERIFY_RECOVER, NULL, 0},
{ CKA_ENCRYPT, NULL, 0},
};
int dsaPubCount = sizeof(dsaPubTemplate)/sizeof(dsaPubTemplate[0]);
/*CK_ULONG key_size = 0;*/
CK_ATTRIBUTE *pubTemplate;
int privCount = sizeof(privTemplate)/sizeof(privTemplate[0]);
int rsaPubCount = sizeof(rsaPubTemplate)/sizeof(rsaPubTemplate[0]);
int dhPubCount = sizeof(dhPubTemplate)/sizeof(dhPubTemplate[0]);
int pubCount = 0;
PK11RSAGenParams *rsaParams;
PQGParams *dsaParams;
DHParams * dhParams;
CK_MECHANISM mechanism;
CK_MECHANISM test_mech;
CK_SESSION_HANDLE session_handle;
CK_RV crv;
CK_OBJECT_HANDLE privID,pubID;
SECKEYPrivateKey *privKey;
KeyType keyType;
PRBool restore;
int peCount,i;
CK_ATTRIBUTE *attrs;
CK_ATTRIBUTE *privattrs;
SECItem *pubKeyIndex;
CK_ATTRIBUTE setTemplate;
SECStatus rv;
CK_MECHANISM_INFO mechanism_info;
CK_OBJECT_CLASS keyClass;
SECItem *cka_id;
PRBool haslock = PR_FALSE;
PRBool pubIsToken = PR_FALSE;
PORT_Assert(slot != NULL);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE);
return NULL;
}
/* if our slot really doesn't do this mechanism, Generate the key
* in our internal token and write it out */
if (!PK11_DoesMechanism(slot,type)) {
PK11SlotInfo *int_slot = PK11_GetInternalSlot();
/* don't loop forever looking for a slot */
if (slot == int_slot) {
PK11_FreeSlot(int_slot);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return NULL;
}
/* if there isn't a suitable slot, then we can't do the keygen */
if (int_slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
/* generate the temporary key to load */
privKey = PK11_GenerateKeyPair(int_slot,type, param, pubKey, PR_FALSE,
PR_FALSE, wincx);
PK11_FreeSlot(int_slot);
/* if successful, load the temp key into the new token */
if (privKey != NULL) {
SECKEYPrivateKey *newPrivKey = pk11_loadPrivKey(slot,privKey,
*pubKey,token,sensitive);
SECKEY_DestroyPrivateKey(privKey);
if (newPrivKey == NULL) {
SECKEY_DestroyPublicKey(*pubKey);
*pubKey = NULL;
}
return newPrivKey;
}
return NULL;
}
mechanism.mechanism = type;
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
test_mech.pParameter = NULL;
test_mech.ulParameterLen = 0;
/* set up the private key template */
privattrs = privTemplate;
PK11_SETATTRS(privattrs, CKA_SENSITIVE, sensitive ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
PK11_SETATTRS(privattrs, CKA_TOKEN, token ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
PK11_SETATTRS(privattrs, CKA_PRIVATE, sensitive ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
/* set up the mechanism specific info */
switch (type) {
case CKM_RSA_PKCS_KEY_PAIR_GEN:
rsaParams = (PK11RSAGenParams *)param;
modulusBits = rsaParams->keySizeInBits;
peCount = 0;
/* convert pe to a PKCS #11 string */
for (i=0; i < 4; i++) {
if (peCount || (rsaParams->pe &
((unsigned long)0xff000000L >> (i*8)))) {
publicExponent[peCount] =
(CK_BYTE)((rsaParams->pe >> (3-i)*8) & 0xff);
peCount++;
}
}
PORT_Assert(peCount != 0);
attrs = rsaPubTemplate;
PK11_SETATTRS(attrs, CKA_MODULUS_BITS,
&modulusBits, sizeof(modulusBits)); attrs++;
PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
publicExponent, peCount);attrs++;
pubTemplate = rsaPubTemplate;
pubCount = rsaPubCount;
keyType = rsaKey;
test_mech.mechanism = CKM_RSA_PKCS;
break;
case CKM_DSA_KEY_PAIR_GEN:
dsaParams = (PQGParams *)param;
attrs = dsaPubTemplate;
PK11_SETATTRS(attrs, CKA_PRIME, dsaParams->prime.data,
dsaParams->prime.len); attrs++;
PK11_SETATTRS(attrs, CKA_SUBPRIME, dsaParams->subPrime.data,
dsaParams->subPrime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, dsaParams->base.data,
dsaParams->base.len); attrs++;
pubTemplate = dsaPubTemplate;
pubCount = dsaPubCount;
keyType = dsaKey;
test_mech.mechanism = CKM_DSA;
break;
case CKM_DH_PKCS_KEY_PAIR_GEN:
dhParams = (DHParams *)param;
attrs = dhPubTemplate;
PK11_SETATTRS(attrs, CKA_PRIME, dhParams->prime.data,
dhParams->prime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, dhParams->base.data,
dhParams->base.len); attrs++;
pubTemplate = dhPubTemplate;
pubCount = dhPubCount;
keyType = dhKey;
test_mech.mechanism = CKM_DH_PKCS_DERIVE;
break;
default:
PORT_SetError( SEC_ERROR_BAD_KEY );
return NULL;
}
/* now query the slot to find out how "good" a key we can generate */
if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
test_mech.mechanism,&mechanism_info);
if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
if ((crv != CKR_OK) || (mechanism_info.flags == 0)) {
/* must be old module... guess what it should be... */
switch (test_mech.mechanism) {
case CKM_RSA_PKCS:
mechanism_info.flags = (CKF_SIGN | CKF_DECRYPT |
CKF_WRAP | CKF_VERIFY_RECOVER | CKF_ENCRYPT | CKF_WRAP);;
break;
case CKM_DSA:
mechanism_info.flags = CKF_SIGN | CKF_VERIFY;
break;
case CKM_DH_PKCS_DERIVE:
mechanism_info.flags = CKF_DERIVE;
break;
default:
break;
}
}
/* set the public key objects */
PK11_SETATTRS(attrs, CKA_TOKEN, token ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_DERIVE,
mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_WRAP,
mechanism_info.flags & CKF_WRAP ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_VERIFY,
mechanism_info.flags & CKF_VERIFY ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_VERIFY_RECOVER,
mechanism_info.flags & CKF_VERIFY_RECOVER ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_ENCRYPT,
mechanism_info.flags & CKF_ENCRYPT? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(privattrs, CKA_DERIVE,
mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
PK11_SETATTRS(privattrs, CKA_UNWRAP,
mechanism_info.flags & CKF_UNWRAP ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
PK11_SETATTRS(privattrs, CKA_SIGN,
mechanism_info.flags & CKF_SIGN ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
PK11_SETATTRS(privattrs, CKA_DECRYPT,
mechanism_info.flags & CKF_DECRYPT ? &cktrue : &ckfalse,
sizeof(CK_BBOOL)); privattrs++;
if (token) {
session_handle = PK11_GetRWSession(slot);
haslock = PK11_RWSessionHasLock(slot,session_handle);
restore = PR_TRUE;
} else {
PK11_EnterSlotMonitor(slot); /* gross!! */
session_handle = slot->session;
restore = PR_FALSE;
haslock = PR_TRUE;
}
crv = PK11_GETTAB(slot)->C_GenerateKeyPair(session_handle, &mechanism,
pubTemplate,pubCount,privTemplate,privCount,&pubID,&privID);
if (crv != CKR_OK) {
if (restore) {
PK11_RestoreROSession(slot,session_handle);
} else PK11_ExitSlotMonitor(slot);
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
/* This locking code is dangerous and needs to be more thought
* out... the real problem is that we're holding the mutex open this long
*/
if (haslock) { PK11_ExitSlotMonitor(slot); }
/* swap around the ID's for older PKCS #11 modules */
keyClass = PK11_ReadULongAttribute(slot,pubID,CKA_CLASS);
if (keyClass != CKO_PUBLIC_KEY) {
CK_OBJECT_HANDLE tmp = pubID;
pubID = privID;
privID = tmp;
}
*pubKey = PK11_ExtractPublicKey(slot, keyType, pubID);
if (*pubKey == NULL) {
if (restore) {
/* we may have to restore the mutex so it get's exited properly
* in RestoreROSession */
if (haslock) PK11_EnterSlotMonitor(slot);
PK11_RestoreROSession(slot,session_handle);
}
PK11_DestroyObject(slot,pubID);
PK11_DestroyObject(slot,privID);
return NULL;
}
/* set the ID to the public key so we can find it again */
pubKeyIndex = NULL;
switch (type) {
case CKM_RSA_PKCS_KEY_PAIR_GEN:
pubKeyIndex = &(*pubKey)->u.rsa.modulus;
break;
case CKM_DSA_KEY_PAIR_GEN:
pubKeyIndex = &(*pubKey)->u.dsa.publicValue;
break;
case CKM_DH_PKCS_KEY_PAIR_GEN:
pubKeyIndex = &(*pubKey)->u.dh.publicValue;
break;
}
PORT_Assert(pubKeyIndex != NULL);
cka_id = PK11_MakeIDFromPubKey(pubKeyIndex);
pubIsToken = (PRBool)PK11_HasAttributeSet(slot,pubID, CKA_TOKEN);
PK11_SETATTRS(&setTemplate, CKA_ID, cka_id->data, cka_id->len);
if (haslock) { PK11_EnterSlotMonitor(slot); }
crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, privID,
&setTemplate, 1);
if (crv == CKR_OK && pubIsToken) {
crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, pubID,
&setTemplate, 1);
}
if (restore) {
PK11_RestoreROSession(slot,session_handle);
} else {
PK11_ExitSlotMonitor(slot);
}
SECITEM_FreeItem(cka_id,PR_TRUE);
if (crv != CKR_OK) {
PK11_DestroyObject(slot,pubID);
PK11_DestroyObject(slot,privID);
PORT_SetError( PK11_MapError(crv) );
*pubKey = NULL;
return NULL;
}
privKey = PK11_MakePrivKey(slot,keyType,(PRBool)!token,privID,wincx);
if (privKey == NULL) {
SECKEY_DestroyPublicKey(*pubKey);
PK11_DestroyObject(slot,privID);
*pubKey = NULL;
return NULL; /* due to pairwise consistency check */
}
/* Perform PKCS #11 pairwise consistency check. */
rv = pk11_PairwiseConsistencyCheck( *pubKey, privKey, &test_mech, wincx );
if( rv != SECSuccess ) {
SECKEY_DestroyPublicKey( *pubKey );
SECKEY_DestroyPrivateKey( privKey );
*pubKey = NULL;
privKey = NULL;
return NULL;
}
return privKey;
}
/*
* This function does a straight public key wrap (which only RSA can do).
* Use PK11_PubGenKey and PK11_WrapSymKey to implement the FORTEZZA and
* Diffie-Hellman Ciphers. */
SECStatus
PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
PK11SymKey *symKey, SECItem *wrappedKey)
{
PK11SlotInfo *slot;
CK_ULONG len = wrappedKey->len;
PK11SymKey *newKey = NULL;
CK_OBJECT_HANDLE id;
CK_MECHANISM mechanism;
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
/* if this slot doesn't support the mechanism, go to a slot that does */
newKey = pk11_ForceSlot(symKey,type,CKA_ENCRYPT);
if (newKey != NULL) {
symKey = newKey;
}
if ((symKey == NULL) || (symKey->slot == NULL)) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
slot = symKey->slot;
mechanism.mechanism = pk11_mapWrapKeyType(pubKey->keyType);
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
id = PK11_ImportPublicKey(slot,pubKey,PR_FALSE);
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_WrapKey(session,&mechanism,
id,symKey->objectID,wrappedKey->data,&len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
if (newKey) {
PK11_FreeSymKey(newKey);
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
wrappedKey->len = len;
return SECSuccess;
}
/*
* this little function uses the Encrypt function to wrap a key, just in
* case we have problems with the wrap implementation for a token.
*/
static SECStatus
pk11_HandWrap(PK11SymKey *wrappingKey, SECItem *param, CK_MECHANISM_TYPE type,
SECItem *inKey, SECItem *outKey)
{
PK11SlotInfo *slot;
CK_ULONG len;
SECItem *data;
CK_MECHANISM mech;
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
slot = wrappingKey->slot;
/* use NULL IV's for wrapping */
mech.mechanism = type;
if (param) {
mech.pParameter = param->data;
mech.ulParameterLen = param->len;
} else {
mech.pParameter = NULL;
mech.ulParameterLen = 0;
}
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_EncryptInit(session,&mech,
wrappingKey->objectID);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
/* keys are almost always aligned, but if we get this far,
* we've gone above and beyond anyway... */
data = PK11_BlockData(inKey,PK11_GetBlockSize(type,param));
if (data == NULL) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
len = outKey->len;
crv = PK11_GETTAB(slot)->C_Encrypt(session,data->data,data->len,
outKey->data, &len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
SECITEM_FreeItem(data,PR_TRUE);
outKey->len = len;
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/*
* This function does a symetric based wrap.
*/
SECStatus
PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *param,
PK11SymKey *wrappingKey, PK11SymKey *symKey, SECItem *wrappedKey)
{
PK11SlotInfo *slot;
CK_ULONG len = wrappedKey->len;
PK11SymKey *newKey = NULL;
SECItem *param_save = NULL;
CK_MECHANISM mechanism;
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
SECStatus rv;
/* if this slot doesn't support the mechanism, go to a slot that does */
/* Force symKey and wrappingKey into the same slot */
if ((wrappingKey->slot == NULL) || (symKey->slot != wrappingKey->slot)) {
/* first try copying the wrapping Key to the symKey slot */
if (symKey->slot && PK11_DoesMechanism(symKey->slot,type)) {
newKey = pk11_CopyToSlot(symKey->slot,type,CKA_WRAP,wrappingKey);
}
/* Nope, try it the other way */
if (newKey == NULL) {
if (wrappingKey->slot) {
newKey = pk11_CopyToSlot(wrappingKey->slot,
symKey->type, CKA_ENCRYPT, symKey);
}
/* just not playing... one last thing, can we get symKey's data?
* If it's possible, we it should already be in the
* symKey->data.data pointer because pk11_CopyToSlot would have
* tried to put it there. */
if (newKey == NULL) {
/* Can't get symKey's data: Game Over */
if (symKey->data.data == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
if (param == NULL) {
param_save = param = PK11_ParamFromIV(type,NULL);
}
rv = pk11_HandWrap(wrappingKey, param, type,
&symKey->data,wrappedKey);
if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
return rv;
}
/* we successfully moved the sym Key */
symKey = newKey;
} else {
/* we successfully moved the wrapping Key */
wrappingKey = newKey;
}
}
/* at this point both keys are in the same token */
slot = wrappingKey->slot;
mechanism.mechanism = type;
/* use NULL IV's for wrapping */
if (param == NULL) {
param_save = param = PK11_ParamFromIV(type,NULL);
}
if (param) {
mechanism.pParameter = param->data;
mechanism.ulParameterLen = param->len;
} else {
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
}
len = wrappedKey->len;
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_WrapKey(session, &mechanism,
wrappingKey->objectID, symKey->objectID,
wrappedKey->data, &len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
rv = SECSuccess;
if (crv != CKR_OK) {
/* can't wrap it? try hand wrapping it... */
do {
if (symKey->data.data == NULL) {
rv = PK11_ExtractKeyValue(symKey);
if (rv != SECSuccess) break;
}
rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data,
wrappedKey);
} while (PR_FALSE);
} else {
wrappedKey->len = len;
}
if (newKey) PK11_FreeSymKey(newKey);
if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
return rv;
}
/*
* This Generates a new key based on a symetricKey
*/
PK11SymKey *
PK11_Derive( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, SECItem *param,
CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
int keySize)
{
return pk11_DeriveWithTemplate(baseKey, derive, param, target, operation,
keySize, NULL, 0);
}
#define MAX_TEMPL_ATTRS 16 /* maximum attributes in template */
/* This mask includes all CK_FLAGs with an equivalent CKA_ attribute. */
#define CKF_KEY_OPERATION_FLAGS 0x000e7b00UL
static unsigned int
pk11_FlagsToAttributes(CK_FLAGS flags, CK_ATTRIBUTE *attrs, CK_BBOOL *ckTrue)
{
const static CK_ATTRIBUTE_TYPE attrTypes[12] = {
CKA_ENCRYPT, CKA_DECRYPT, 0 /* DIGEST */, CKA_SIGN,
CKA_SIGN_RECOVER, CKA_VERIFY, CKA_VERIFY_RECOVER, 0 /* GEN */,
0 /* GEN PAIR */, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE
};
const CK_ATTRIBUTE_TYPE *pType = attrTypes;
CK_ATTRIBUTE *attr = attrs;
CK_FLAGS test = CKF_ENCRYPT;
PR_ASSERT(!(flags & ~CKF_KEY_OPERATION_FLAGS));
flags &= CKF_KEY_OPERATION_FLAGS;
for (; flags && test <= CKF_DERIVE; test <<= 1, ++pType) {
if (test & flags) {
flags ^= test;
PK11_SETATTRS(attr, *pType, ckTrue, sizeof *ckTrue);
++attr;
}
}
return (attr - attrs);
}
PK11SymKey *
PK11_DeriveWithFlags( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
int keySize, CK_FLAGS flags)
{
CK_BBOOL ckTrue = CK_TRUE;
CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
unsigned int templateCount;
templateCount = pk11_FlagsToAttributes(flags, keyTemplate, &ckTrue);
return pk11_DeriveWithTemplate(baseKey, derive, param, target, operation,
keySize, keyTemplate, templateCount);
}
static PRBool
pk11_FindAttrInTemplate(CK_ATTRIBUTE * attr,
unsigned int numAttrs,
CK_ATTRIBUTE_TYPE target)
{
for (; numAttrs > 0; ++attr, --numAttrs) {
if (attr->type == target)
return PR_TRUE;
}
return PR_FALSE;
}
static PK11SymKey *
pk11_DeriveWithTemplate( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs)
{
PK11SlotInfo * slot = baseKey->slot;
PK11SymKey * symKey;
PK11SymKey * newBaseKey = NULL;
CK_BBOOL cktrue = CK_TRUE;
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
CK_ULONG valueLen = 0;
CK_MECHANISM mechanism;
CK_RV crv;
CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
CK_ATTRIBUTE * attrs = keyTemplate;
unsigned int templateCount;
if (numAttrs > MAX_TEMPL_ATTRS) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
/* first copy caller attributes in. */
for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
*attrs++ = *userAttr++;
}
/* We only add the following attributes to the template if the caller
** didn't already supply them.
*/
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
attrs++;
}
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
keyType = PK11_GetKeyType(target, keySize);
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType );
attrs++;
}
if (keySize > 0 &&
!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
valueLen = (CK_ULONG)keySize;
PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
attrs++;
}
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue); attrs++;
}
templateCount = attrs - keyTemplate;
PR_ASSERT(templateCount <= MAX_TEMPL_ATTRS);
/* move the key to a slot that can do the function */
if (!PK11_DoesMechanism(slot,derive)) {
/* get a new base key & slot */
PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
if (newSlot == NULL) return NULL;
newBaseKey = pk11_CopyToSlot (newSlot, derive, CKA_DERIVE,
baseKey);
PK11_FreeSlot(newSlot);
if (newBaseKey == NULL) return NULL;
baseKey = newBaseKey;
slot = baseKey->slot;
}
/* get our key Structure */
symKey = PK11_CreateSymKey(slot,target,baseKey->cx);
if (symKey == NULL) {
return NULL;
}
symKey->size = keySize;
mechanism.mechanism = derive;
if (param) {
mechanism.pParameter = param->data;
mechanism.ulParameterLen = param->len;
} else {
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
}
symKey->origin=PK11_OriginDerive;
pk11_EnterKeyMonitor(symKey);
crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
pk11_ExitKeyMonitor(symKey);
if (newBaseKey) PK11_FreeSymKey(newBaseKey);
if (crv != CKR_OK) {
PK11_FreeSymKey(symKey);
return NULL;
}
return symKey;
}
/* build a public KEA key from the public value */
SECKEYPublicKey *
PK11_MakeKEAPubKey(unsigned char *keyData,int length)
{
SECKEYPublicKey *pubk;
SECItem pkData;
SECStatus rv;
PRArenaPool *arena;
pkData.data = keyData;
pkData.len = length;
arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE);
if (arena == NULL)
return NULL;
pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
if (pubk == NULL) {
PORT_FreeArena (arena, PR_FALSE);
return NULL;
}
pubk->arena = arena;
pubk->pkcs11Slot = 0;
pubk->pkcs11ID = CK_INVALID_KEY;
pubk->keyType = fortezzaKey;
rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.KEAKey, &pkData);
if (rv != SECSuccess) {
PORT_FreeArena (arena, PR_FALSE);
return NULL;
}
return pubk;
}
/*
* This Generates a wrapping key based on a privateKey, publicKey, and two
* random numbers. For Mail usage RandomB should be NULL. In the Sender's
* case RandomA is generate, outherwize it is passed.
*/
static unsigned char *rb_email = NULL;
PK11SymKey *
PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
PRBool isSender, SECItem *randomA, SECItem *randomB,
CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
CK_ATTRIBUTE_TYPE operation, int keySize,void *wincx)
{
PK11SlotInfo *slot = privKey->pkcs11Slot;
CK_MECHANISM mechanism;
PK11SymKey *symKey;
CK_RV crv;
if (rb_email == NULL) {
rb_email = PORT_ZAlloc(128);
if (rb_email == NULL) {
return NULL;
}
rb_email[127] = 1;
}
/* get our key Structure */
symKey = PK11_CreateSymKey(slot,target,wincx);
if (symKey == NULL) {
return NULL;
}
symKey->origin = PK11_OriginDerive;
switch (privKey->keyType) {
case rsaKey:
case nullKey:
PORT_SetError(SEC_ERROR_BAD_KEY);
break;
/* case keaKey: */
case dsaKey:
case fortezzaKey:
{
CK_KEA_DERIVE_PARAMS param;
param.isSender = (CK_BBOOL) isSender;
param.ulRandomLen = randomA->len;
param.pRandomA = randomA->data;
param.pRandomB = rb_email;
if (randomB)
param.pRandomB = randomB->data;
if (pubKey->keyType == fortezzaKey) {
param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
param.pPublicData = pubKey->u.fortezza.KEAKey.data;
} else {
/* assert type == keaKey */
/* XXX change to match key key types */
param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
param.pPublicData = pubKey->u.fortezza.KEAKey.data;
}
mechanism.mechanism = derive;
mechanism.pParameter = ¶m;
mechanism.ulParameterLen = sizeof(param);
/* get a new symKey structure */
pk11_EnterKeyMonitor(symKey);
crv=PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
privKey->pkcs11ID, NULL, 0, &symKey->objectID);
pk11_ExitKeyMonitor(symKey);
if (crv == CKR_OK) return symKey;
PORT_SetError( PK11_MapError(crv) );
}
break;
case dhKey:
{
CK_BBOOL cktrue = CK_TRUE;
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
CK_ULONG key_size = 0;
CK_ATTRIBUTE keyTemplate[4];
int templateCount;
CK_ATTRIBUTE *attrs = keyTemplate;
if (pubKey->keyType != dhKey) {
PORT_SetError(SEC_ERROR_BAD_KEY);
break;
}
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
attrs++;
PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
attrs++;
templateCount = attrs - keyTemplate;
PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
keyType = PK11_GetKeyType(target,keySize);
key_size = keySize;
symKey->size = keySize;
if (key_size == 0) templateCount--;
mechanism.mechanism = derive;
/* we can undefine these when we define diffie-helman keys */
mechanism.pParameter = pubKey->u.dh.publicValue.data;
mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
pk11_EnterKeyMonitor(symKey);
crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
privKey->pkcs11ID, keyTemplate, templateCount, &symKey->objectID);
pk11_ExitKeyMonitor(symKey);
if (crv == CKR_OK) return symKey;
PORT_SetError( PK11_MapError(crv) );
}
break;
}
PK11_FreeSymKey(symKey);
return NULL;
}
/*
* this little function uses the Decrypt function to unwrap a key, just in
* case we are having problem with unwrap. NOTE: The key size may
* not be preserved properly for some algorithms!
*/
static PK11SymKey *
pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target,
CK_ATTRIBUTE *keyTemplate, unsigned int templateCount,
int key_size, void * wincx, CK_RV *crvp)
{
CK_ULONG len;
SECItem outKey;
PK11SymKey *symKey;
CK_RV crv;
PRBool owner = PR_TRUE;
PRBool bool = PR_TRUE;
CK_SESSION_HANDLE session;
/* remove any VALUE_LEN parameters */
if (keyTemplate[templateCount-1].type == CKA_VALUE_LEN) {
templateCount--;
}
/* keys are almost always aligned, but if we get this far,
* we've gone above and beyond anyway... */
outKey.data = (unsigned char*)PORT_Alloc(inKey->len);
if (outKey.data == NULL) {
PORT_SetError( SEC_ERROR_NO_MEMORY );
if (crvp) *crvp = CKR_HOST_MEMORY;
return NULL;
}
len = inKey->len;
/* use NULL IV's for wrapping */
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_DecryptInit(session,mech,wrappingKey);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_Free(outKey.data);
PORT_SetError( PK11_MapError(crv) );
if (crvp) *crvp =crv;
return NULL;
}
crv = PK11_GETTAB(slot)->C_Decrypt(session,inKey->data,inKey->len,
outKey.data, &len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
if (crv != CKR_OK) {
PORT_Free(outKey.data);
PORT_SetError( PK11_MapError(crv) );
if (crvp) *crvp =crv;
return NULL;
}
outKey.len = (key_size == 0) ? len : key_size;
if (PK11_DoesMechanism(slot,target)) {
symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
keyTemplate, templateCount,
&outKey, wincx);
} else {
slot = PK11_GetBestSlot(target,wincx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
PORT_Free(outKey.data);
if (crvp) *crvp = CKR_DEVICE_ERROR;
return NULL;
}
symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
keyTemplate, templateCount,
&outKey, wincx);
PK11_FreeSlot(slot);
}
PORT_Free(outKey.data);
if (crvp) *crvp = symKey? CKR_OK : CKR_DEVICE_ERROR;
return symKey;
}
/*
* The wrap/unwrap function is pretty much the same for private and
* public keys. It's just getting the Object ID and slot right. This is
* the combined unwrap function.
*/
static PK11SymKey *
pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs)
{
PK11SymKey * symKey;
SECItem * param_free = NULL;
CK_BBOOL ckfalse = CK_FALSE;
CK_BBOOL cktrue = CK_TRUE;
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
CK_ULONG valueLen = 0;
CK_MECHANISM mechanism;
CK_RV crv;
CK_MECHANISM_INFO mechanism_info;
CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
CK_ATTRIBUTE * attrs = keyTemplate;
unsigned int templateCount;
if (numAttrs > MAX_TEMPL_ATTRS) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
/* first copy caller attributes in. */
for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
*attrs++ = *userAttr++;
}
/* We only add the following attributes to the template if the caller
** didn't already supply them.
*/
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
attrs++;
}
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
keyType = PK11_GetKeyType(target, keySize);
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType );
attrs++;
}
if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
}
/*
* must be last in case we need to use this template to import the key
*/
if (keySize > 0 &&
!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
valueLen = (CK_ULONG)keySize;
PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
attrs++;
}
templateCount = attrs - keyTemplate;
PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
/* find out if we can do wrap directly. Because the RSA case if *very*
* common, cache the results for it. */
if ((wrapType == CKM_RSA_PKCS) && (slot->hasRSAInfo)) {
mechanism_info.flags = slot->RSAInfoFlags;
} else {
if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,wrapType,
&mechanism_info);
if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
if (crv != CKR_OK) {
mechanism_info.flags = 0;
}
if (wrapType == CKM_RSA_PKCS) {
slot->RSAInfoFlags = mechanism_info.flags;
slot->hasRSAInfo = PR_TRUE;
}
}
/* initialize the mechanism structure */
mechanism.mechanism = wrapType;
/* use NULL IV's for wrapping */
if (param == NULL) param = param_free = PK11_ParamFromIV(wrapType,NULL);
if (param) {
mechanism.pParameter = param->data;
mechanism.ulParameterLen = param->len;
} else {
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
}
if ((mechanism_info.flags & CKF_DECRYPT)
&& !PK11_DoesMechanism(slot,target)) {
symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
target, keyTemplate, templateCount, keySize,
wincx, &crv);
if (symKey) {
if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
return symKey;
}
/*
* if the RSA OP simply failed, don't try to unwrap again
* with this module.
*/
if (crv == CKR_DEVICE_ERROR){
return NULL;
}
/* fall through, maybe they incorrectly set CKF_DECRYPT */
}
/* get our key Structure */
symKey = PK11_CreateSymKey(slot,target,wincx);
if (symKey == NULL) {
if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
return NULL;
}
symKey->size = keySize;
symKey->origin = PK11_OriginUnwrap;
pk11_EnterKeyMonitor(symKey);
crv = PK11_GETTAB(slot)->C_UnwrapKey(symKey->session,&mechanism,wrappingKey,
wrappedKey->data, wrappedKey->len, keyTemplate, templateCount,
&symKey->objectID);
pk11_ExitKeyMonitor(symKey);
if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
if ((crv != CKR_OK) && (crv != CKR_DEVICE_ERROR)) {
/* try hand Unwrapping */
PK11_FreeSymKey(symKey);
symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
target, keyTemplate, templateCount, keySize,
wincx, NULL);
}
return symKey;
}
/* use a symetric key to unwrap another symetric key */
PK11SymKey *
PK11_UnwrapSymKey( PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
SECItem *param, SECItem *wrappedKey,
CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
int keySize)
{
return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
wrapType, param, wrappedKey, target, operation, keySize,
wrappingKey->cx, NULL, 0);
}
/* use a symetric key to unwrap another symetric key */
PK11SymKey *
PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
SECItem *param, SECItem *wrappedKey,
CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
int keySize, CK_FLAGS flags)
{
CK_BBOOL ckTrue = CK_TRUE;
CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
unsigned int templateCount;
templateCount = pk11_FlagsToAttributes(flags, keyTemplate, &ckTrue);
return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
wrapType, param, wrappedKey, target, operation, keySize,
wrappingKey->cx, keyTemplate, templateCount);
}
/* unwrap a symetric key with a private key. */
PK11SymKey *
PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
{
CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
PK11_HandlePasswordCheck(wrappingKey->pkcs11Slot,wrappingKey->wincx);
return pk11_AnyUnwrapKey(wrappingKey->pkcs11Slot, wrappingKey->pkcs11ID,
wrapType, NULL, wrappedKey, target, operation, keySize,
wrappingKey->wincx, NULL, 0);
}
/*
* Recover the Signed data. We need this because our old verify can't
* figure out which hash algorithm to use until we decryptted this.
*/
SECStatus
PK11_VerifyRecover(SECKEYPublicKey *key,
SECItem *sig, SECItem *dsig, void *wincx)
{
PK11SlotInfo *slot = key->pkcs11Slot;
CK_OBJECT_HANDLE id = key->pkcs11ID;
CK_MECHANISM mech = {0, NULL, 0 };
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_ULONG len;
CK_RV crv;
mech.mechanism = pk11_mapSignKeyType(key->keyType);
if (slot == NULL) {
slot = PK11_GetBestSlot(mech.mechanism,wincx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
id = PK11_ImportPublicKey(slot,key,PR_FALSE);
}
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_VerifyRecoverInit(session,&mech,id);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
len = dsig->len;
crv = PK11_GETTAB(slot)->C_VerifyRecover(session,sig->data,
sig->len, dsig->data, &len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
dsig->len = len;
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/*
* verify a signature from its hash.
*/
SECStatus
PK11_Verify(SECKEYPublicKey *key, SECItem *sig, SECItem *hash, void *wincx)
{
PK11SlotInfo *slot = key->pkcs11Slot;
PK11SlotInfo *tmpslot = key->pkcs11Slot;
CK_OBJECT_HANDLE id = key->pkcs11ID;
CK_MECHANISM mech = {0, NULL, 0 };
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
mech.mechanism = pk11_mapSignKeyType(key->keyType);
if (slot == NULL) {
if (mech.mechanism == CKM_DSA) {
slot = PK11_GetInternalSlot(); /* use internal slot for
DSA verify */
} else {
slot = PK11_GetBestSlot(mech.mechanism,wincx);
};
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
id = PK11_ImportPublicKey(slot,key,PR_FALSE);
}
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_VerifyInit(session,&mech,id);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
crv = PK11_GETTAB(slot)->C_Verify(session,hash->data,
hash->len, sig->data, sig->len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/*
* sign a hash. The algorithm is determined by the key.
*/
SECStatus
PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, SECItem *hash)
{
PK11SlotInfo *slot = key->pkcs11Slot;
CK_MECHANISM mech = {0, NULL, 0 };
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_ULONG len;
CK_RV crv;
mech.mechanism = pk11_mapSignKeyType(key->keyType);
PK11_HandlePasswordCheck(slot, key->wincx);
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_SignInit(session,&mech,key->pkcs11ID);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
len = sig->len;
crv = PK11_GETTAB(slot)->C_Sign(session,hash->data,
hash->len, sig->data, &len);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
sig->len = len;
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/*
* Now SSL 2.0 uses raw RSA stuff. These next to functions *must* use
* RSA keys, or they'll fail. We do the checks up front. If anyone comes
* up with a meaning for rawdecrypt for any other public key operation,
* then we need to move this check into some of PK11_PubDecrypt callers,
* (namely SSL 2.0).
*/
SECStatus
PK11_PubDecryptRaw(SECKEYPrivateKey *key, unsigned char *data,
unsigned *outLen, unsigned int maxLen, unsigned char *enc,
unsigned encLen)
{
PK11SlotInfo *slot = key->pkcs11Slot;
CK_MECHANISM mech = {CKM_RSA_X_509, NULL, 0 };
CK_ULONG out = maxLen;
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
if (key->keyType != rsaKey) {
PORT_SetError( SEC_ERROR_INVALID_KEY );
return SECFailure;
}
/* Why do we do a PK11_handle check here? for simple
* decryption? .. because the user may have asked for 'ask always'
* and this is a private key operation. In practice, thought, it's mute
* since only servers wind up using this function */
PK11_HandlePasswordCheck(slot, key->wincx);
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_DecryptInit(session,&mech,key->pkcs11ID);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
crv = PK11_GETTAB(slot)->C_Decrypt(session,enc, encLen,
data, &out);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
*outLen = out;
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/* The encrypt version of the above function */
SECStatus
PK11_PubEncryptRaw(SECKEYPublicKey *key, unsigned char *enc,
unsigned char *data, unsigned dataLen, void *wincx)
{
PK11SlotInfo *slot;
CK_MECHANISM mech = {CKM_RSA_X_509, NULL, 0 };
CK_OBJECT_HANDLE id;
CK_ULONG out = dataLen;
PRBool owner = PR_TRUE;
CK_SESSION_HANDLE session;
CK_RV crv;
if (key->keyType != rsaKey) {
PORT_SetError( SEC_ERROR_BAD_KEY );
return SECFailure;
}
slot = PK11_GetBestSlot(mech.mechanism, wincx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return SECFailure;
}
id = PK11_ImportPublicKey(slot,key,PR_FALSE);
session = pk11_GetNewSession(slot,&owner);
if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
crv = PK11_GETTAB(slot)->C_EncryptInit(session,&mech,id);
if (crv != CKR_OK) {
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
crv = PK11_GETTAB(slot)->C_Encrypt(session,data,dataLen,enc,&out);
if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
pk11_CloseSession(slot,session,owner);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/**********************************************************************
*
* Now Deal with Crypto Contexts
*
**********************************************************************/
/*
* the monitors...
*/
void
PK11_EnterContextMonitor(PK11Context *cx) {
/* if we own the session and our slot is ThreadSafe, only monitor
* the Context */
if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
/* Should this use monitors instead? */
PZ_Lock(cx->sessionLock);
} else {
PK11_EnterSlotMonitor(cx->slot);
}
}
void
PK11_ExitContextMonitor(PK11Context *cx) {
/* if we own the session and our slot is ThreadSafe, only monitor
* the Context */
if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
/* Should this use monitors instead? */
PZ_Unlock(cx->sessionLock);
} else {
PK11_ExitSlotMonitor(cx->slot);
}
}
/*
* Free up a Cipher Context
*/
void
PK11_DestroyContext(PK11Context *context, PRBool freeit)
{
pk11_CloseSession(context->slot,context->session,context->ownSession);
/* initialize the critical fields of the context */
if (context->savedData != NULL ) PORT_Free(context->savedData);
if (context->key) PK11_FreeSymKey(context->key);
if (context->param) SECITEM_FreeItem(context->param, PR_TRUE);
if (context->sessionLock) PZ_DestroyLock(context->sessionLock);
PK11_FreeSlot(context->slot);
if (freeit) PORT_Free(context);
}
/*
* save the current context. Allocate Space if necessary.
*/
static void *
pk11_saveContextHelper(PK11Context *context, void *space,
unsigned long *savedLength, PRBool staticBuffer, PRBool recurse)
{
CK_ULONG length;
CK_RV crv;
if (staticBuffer) PORT_Assert(space != NULL);
if (space == NULL) {
crv =PK11_GETTAB(context->slot)->C_GetOperationState(context->session,
NULL,&length);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
space = PORT_Alloc(length);
if (space == NULL) return NULL;
*savedLength = length;
}
crv = PK11_GETTAB(context->slot)->C_GetOperationState(context->session,
(CK_BYTE_PTR)space,savedLength);
if (!staticBuffer && !recurse && (crv == CKR_BUFFER_TOO_SMALL)) {
if (!staticBuffer) PORT_Free(space);
return pk11_saveContextHelper(context, NULL,
savedLength, PR_FALSE, PR_TRUE);
}
if (crv != CKR_OK) {
if (!staticBuffer) PORT_Free(space);
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
return space;
}
void *
pk11_saveContext(PK11Context *context, void *space, unsigned long *savedLength)
{
return pk11_saveContextHelper(context, space,
savedLength, PR_FALSE, PR_FALSE);
}
/*
* restore the current context
*/
SECStatus
pk11_restoreContext(PK11Context *context,void *space, unsigned long savedLength)
{
CK_RV crv;
CK_OBJECT_HANDLE objectID = (context->key) ? context->key->objectID:
CK_INVALID_KEY;
PORT_Assert(space != NULL);
if (space == NULL) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
crv = PK11_GETTAB(context->slot)->C_SetOperationState(context->session,
(CK_BYTE_PTR)space, savedLength, objectID, 0);
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv));
return SECFailure;
}
return SECSuccess;
}
SECStatus pk11_Finalize(PK11Context *context);
/*
* Context initialization. Used by all flavors of CreateContext
*/
static SECStatus
pk11_context_init(PK11Context *context, CK_MECHANISM *mech_info)
{
CK_RV crv;
PK11SymKey *symKey = context->key;
SECStatus rv = SECSuccess;
switch (context->operation) {
case CKA_ENCRYPT:
crv=PK11_GETTAB(context->slot)->C_EncryptInit(context->session,
mech_info, symKey->objectID);
break;
case CKA_DECRYPT:
if (context->fortezzaHack) {
CK_ULONG count = 0;;
/* generate the IV for fortezza */
crv=PK11_GETTAB(context->slot)->C_EncryptInit(context->session,
mech_info, symKey->objectID);
if (crv != CKR_OK) break;
PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
NULL, &count);
}
crv=PK11_GETTAB(context->slot)->C_DecryptInit(context->session,
mech_info, symKey->objectID);
break;
case CKA_SIGN:
crv=PK11_GETTAB(context->slot)->C_SignInit(context->session,
mech_info, symKey->objectID);
break;
case CKA_VERIFY:
crv=PK11_GETTAB(context->slot)->C_SignInit(context->session,
mech_info, symKey->objectID);
break;
case CKA_DIGEST:
crv=PK11_GETTAB(context->slot)->C_DigestInit(context->session,
mech_info);
break;
default:
crv = CKR_OPERATION_NOT_INITIALIZED;
break;
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
/*
* handle session starvation case.. use our last session to multiplex
*/
if (!context->ownSession) {
context->savedData = pk11_saveContext(context,context->savedData,
&context->savedLength);
if (context->savedData == NULL) rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
return rv;
}
/*
* Common Helper Function do come up with a new context.
*/
static PK11Context *pk11_CreateNewContextInSlot(CK_MECHANISM_TYPE type,
PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey,
SECItem *param)
{
CK_MECHANISM mech_info;
PK11Context *context;
SECStatus rv;
PORT_Assert(slot != NULL);
if (!slot) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
context = (PK11Context *) PORT_Alloc(sizeof(PK11Context));
if (context == NULL) {
return NULL;
}
/* now deal with the fortezza hack... the fortezza hack is an attempt
* to get around the issue of the card not allowing you to do a FORTEZZA
* LoadIV/Encrypt, which was added because such a combination could be
* use to circumvent the key escrow system. Unfortunately SSL needs to
* do this kind of operation, so in SSL we do a loadIV (to verify it),
* Then GenerateIV, and through away the first 8 bytes on either side
* of the connection.*/
context->fortezzaHack = PR_FALSE;
if (type == CKM_SKIPJACK_CBC64) {
if (symKey->origin == PK11_OriginFortezzaHack) {
context->fortezzaHack = PR_TRUE;
}
}
/* initialize the critical fields of the context */
context->operation = operation;
context->key = symKey ? PK11_ReferenceSymKey(symKey) : NULL;
context->slot = PK11_ReferenceSlot(slot);
context->session = pk11_GetNewSession(slot,&context->ownSession);
context->cx = symKey ? symKey->cx : NULL;
/* get our session */
context->savedData = NULL;
/* save the parameters so that some digesting stuff can do multiple
* begins on a single context */
context->type = type;
context->param = SECITEM_DupItem(param);
context->init = PR_FALSE;
context->sessionLock = PZ_NewLock(nssILockPK11cxt);
if ((context->param == NULL) || (context->sessionLock == NULL)) {
PK11_DestroyContext(context,PR_TRUE);
return NULL;
}
mech_info.mechanism = type;
mech_info.pParameter = param->data;
mech_info.ulParameterLen = param->len;
PK11_EnterContextMonitor(context);
rv = pk11_context_init(context,&mech_info);
PK11_ExitContextMonitor(context);
if (rv != SECSuccess) {
PK11_DestroyContext(context,PR_TRUE);
return NULL;
}
context->init = PR_TRUE;
return context;
}
/*
* put together the various PK11_Create_Context calls used by different
* parts of libsec.
*/
PK11Context *
__PK11_CreateContextByRawKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
SECItem *param, void *wincx)
{
PK11SymKey *symKey;
PK11Context *context;
/* first get a slot */
if (slot == NULL) {
slot = PK11_GetBestSlot(type,wincx);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
} else {
PK11_ReferenceSlot(slot);
}
/* now import the key */
symKey = PK11_ImportSymKey(slot, type, origin, operation, key, wincx);
if (symKey == NULL) return NULL;
context = PK11_CreateContextBySymKey(type, operation, symKey, param);
PK11_FreeSymKey(symKey);
PK11_FreeSlot(slot);
return context;
}
PK11Context *
PK11_CreateContextByRawKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
SECItem *param, void *wincx)
{
return __PK11_CreateContextByRawKey(slot, type, origin, operation,
key, param, wincx);
}
/*
* Create a context from a key. We really should make sure we aren't using
* the same key in multiple session!
*/
PK11Context *
PK11_CreateContextBySymKey(CK_MECHANISM_TYPE type,CK_ATTRIBUTE_TYPE operation,
PK11SymKey *symKey, SECItem *param)
{
PK11SymKey *newKey;
PK11Context *context;
/* if this slot doesn't support the mechanism, go to a slot that does */
newKey = pk11_ForceSlot(symKey,type,operation);
if (newKey == NULL) {
PK11_ReferenceSymKey(symKey);
} else {
symKey = newKey;
}
/* Context Adopts the symKey.... */
context = pk11_CreateNewContextInSlot(type, symKey->slot, operation, symKey,
param);
PK11_FreeSymKey(symKey);
return context;
}
/*
* Digest contexts don't need keys, but the do need to find a slot.
* Macing should use PK11_CreateContextBySymKey.
*/
PK11Context *
PK11_CreateDigestContext(SECOidTag hashAlg)
{
/* digesting has to work without authentication to the slot */
CK_MECHANISM_TYPE type;
PK11SlotInfo *slot;
PK11Context *context;
SECItem param;
type = PK11_AlgtagToMechanism(hashAlg);
slot = PK11_GetBestSlot(type, NULL);
if (slot == NULL) {
PORT_SetError( SEC_ERROR_NO_MODULE );
return NULL;
}
/* maybe should really be PK11_GenerateNewParam?? */
param.data = NULL;
param.len = 0;
context = pk11_CreateNewContextInSlot(type, slot, CKA_DIGEST, NULL, ¶m);
PK11_FreeSlot(slot);
return context;
}
/*
* create a new context which is the clone of the state of old context.
*/
PK11Context * PK11_CloneContext(PK11Context *old)
{
PK11Context *newcx;
PRBool needFree = PR_FALSE;
SECStatus rv = SECSuccess;
void *data;
unsigned long len;
newcx = pk11_CreateNewContextInSlot(old->type, old->slot, old->operation,
old->key, old->param);
if (newcx == NULL) return NULL;
/* now clone the save state. First we need to find the save state
* of the old session. If the old context owns it's session,
* the state needs to be saved, otherwise the state is in saveData. */
if (old->ownSession) {
PK11_EnterContextMonitor(old);
data=pk11_saveContext(old,NULL,&len);
PK11_ExitContextMonitor(old);
needFree = PR_TRUE;
} else {
data = old->savedData;
len = old->savedLength;
}
if (data == NULL) {
PK11_DestroyContext(newcx,PR_TRUE);
return NULL;
}
/* now copy that state into our new context. Again we have different
* work if the new context owns it's own session. If it does, we
* restore the state gathered above. If it doesn't, we copy the
* saveData pointer... */
if (newcx->ownSession) {
PK11_EnterContextMonitor(newcx);
rv = pk11_restoreContext(newcx,data,len);
PK11_ExitContextMonitor(newcx);
} else {
PORT_Assert(newcx->savedData != NULL);
if ((newcx->savedData == NULL) || (newcx->savedLength < len)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
rv = SECFailure;
} else {
PORT_Memcpy(newcx->savedData,data,len);
newcx->savedLength = len;
}
}
if (needFree) PORT_Free(data);
if (rv != SECSuccess) {
PK11_DestroyContext(newcx,PR_TRUE);
return NULL;
}
return newcx;
}
/*
* save the current context state into a variable. Required to make FORTEZZA
* work.
*/
SECStatus
PK11_SaveContext(PK11Context *cx,unsigned char *save,int *len, int saveLength)
{
unsigned char * data = NULL;
CK_ULONG length = saveLength;
if (cx->ownSession) {
PK11_EnterContextMonitor(cx);
data = (unsigned char*)pk11_saveContextHelper(cx,save,&length,
PR_FALSE,PR_FALSE);
PK11_ExitContextMonitor(cx);
if (data) *len = length;
} else if (saveLength >= cx->savedLength) {
data = (unsigned char*)cx->savedData;
if (cx->savedData) {
PORT_Memcpy(save,cx->savedData,cx->savedLength);
}
*len = cx->savedLength;
}
return (data != NULL) ? SECSuccess : SECFailure;
}
/*
* restore the context state into a new running context. Also required for
* FORTEZZA .
*/
SECStatus
PK11_RestoreContext(PK11Context *cx,unsigned char *save,int len)
{
SECStatus rv = SECSuccess;
if (cx->ownSession) {
PK11_EnterContextMonitor(cx);
pk11_Finalize(cx);
rv = pk11_restoreContext(cx,save,len);
PK11_ExitContextMonitor(cx);
} else {
PORT_Assert(cx->savedData != NULL);
if ((cx->savedData == NULL) || (cx->savedLength < (unsigned) len)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
rv = SECFailure;
} else {
PORT_Memcpy(cx->savedData,save,len);
cx->savedLength = len;
}
}
return rv;
}
/*
* This is to get FIPS compliance until we can convert
* libjar to use PK11_ hashing functions. It returns PR_FALSE
* if we can't get a PK11 Context.
*/
PRBool
PK11_HashOK(SECOidTag algID) {
PK11Context *cx;
cx = PK11_CreateDigestContext(algID);
if (cx == NULL) return PR_FALSE;
PK11_DestroyContext(cx, PR_TRUE);
return PR_TRUE;
}
/*
* start a new digesting or Mac'ing operation on this context
*/
SECStatus PK11_DigestBegin(PK11Context *cx)
{
CK_MECHANISM mech_info;
SECStatus rv;
if (cx->init == PR_TRUE) {
return SECSuccess;
}
/*
* make sure the old context is clear first
*/
PK11_EnterContextMonitor(cx);
pk11_Finalize(cx);
mech_info.mechanism = cx->type;
mech_info.pParameter = cx->param->data;
mech_info.ulParameterLen = cx->param->len;
rv = pk11_context_init(cx,&mech_info);
PK11_ExitContextMonitor(cx);
if (rv != SECSuccess) {
return SECFailure;
}
cx->init = PR_TRUE;
return SECSuccess;
}
SECStatus
PK11_HashBuf(SECOidTag hashAlg, unsigned char *out, unsigned char *in,
int32 len) {
PK11Context *context;
unsigned int max_length;
unsigned int out_length;
SECStatus rv;
context = PK11_CreateDigestContext(hashAlg);
if (context == NULL) return SECFailure;
rv = PK11_DigestBegin(context);
if (rv != SECSuccess) {
PK11_DestroyContext(context, PR_TRUE);
return rv;
}
rv = PK11_DigestOp(context, in, len);
if (rv != SECSuccess) {
PK11_DestroyContext(context, PR_TRUE);
return rv;
}
/* we need the output length ... maybe this should be table driven...*/
switch (hashAlg) {
case SEC_OID_SHA1: max_length = SHA1_LENGTH; break;
case SEC_OID_MD2: max_length = MD2_LENGTH; break;
case SEC_OID_MD5: max_length = MD5_LENGTH; break;
default: max_length = 16; break;
}
rv = PK11_DigestFinal(context,out,&out_length,max_length);
PK11_DestroyContext(context, PR_TRUE);
return rv;
}
/*
* execute a bulk encryption operation
*/
SECStatus
PK11_CipherOp(PK11Context *context, unsigned char * out, int *outlen,
int maxout, unsigned char *in, int inlen)
{
CK_RV crv = CKR_OK;
CK_ULONG length = maxout;
CK_ULONG offset =0;
PK11SymKey *symKey = context->key;
SECStatus rv = SECSuccess;
unsigned char *saveOut = out;
unsigned char *allocOut = NULL;
/* if we ran out of session, we need to restore our previously stored
* state.
*/
PK11_EnterContextMonitor(context);
if (!context->ownSession) {
rv = pk11_restoreContext(context,context->savedData,
context->savedLength);
if (rv != SECSuccess) {
PK11_ExitContextMonitor(context);
return rv;
}
}
/*
* The fortezza hack is to send 8 extra bytes on the first encrypted and
* loose them on the first decrypt.
*/
if (context->fortezzaHack) {
unsigned char random[8];
if (context->operation == CKA_ENCRYPT) {
PK11_ExitContextMonitor(context);
rv = PK11_GenerateRandom(random,sizeof(random));
PK11_EnterContextMonitor(context);
/* since we are offseting the output, we can't encrypt back into
* the same buffer... allocate a temporary buffer just for this
* call. */
allocOut = out = (unsigned char*)PORT_Alloc(maxout);
if (out == NULL) {
PK11_ExitContextMonitor(context);
return SECFailure;
}
crv = PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session,
random,sizeof(random),out,&length);
out += length;
maxout -= length;
offset = length;
} else if (context->operation == CKA_DECRYPT) {
length = sizeof(random);
crv = PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session,
in,sizeof(random),random,&length);
inlen -= length;
in += length;
context->fortezzaHack = PR_FALSE;
}
}
switch (context->operation) {
case CKA_ENCRYPT:
length = maxout;
crv=PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session,
in, inlen, out, &length);
length += offset;
break;
case CKA_DECRYPT:
length = maxout;
crv=PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session,
in, inlen, out, &length);
break;
default:
crv = CKR_OPERATION_NOT_INITIALIZED;
break;
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
*outlen = 0;
rv = SECFailure;
} else {
*outlen = length;
}
if (context->fortezzaHack) {
if (context->operation == CKA_ENCRYPT) {
PORT_Assert(allocOut);
PORT_Memcpy(saveOut, allocOut, length);
PORT_Free(allocOut);
}
context->fortezzaHack = PR_FALSE;
}
/*
* handle session starvation case.. use our last session to multiplex
*/
if (!context->ownSession) {
context->savedData = pk11_saveContext(context,context->savedData,
&context->savedLength);
if (context->savedData == NULL) rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
PK11_ExitContextMonitor(context);
return rv;
}
/*
* execute a digest/signature operation
*/
SECStatus
PK11_DigestOp(PK11Context *context, const unsigned char * in, unsigned inLen)
{
CK_RV crv = CKR_OK;
SECStatus rv = SECSuccess;
/* if we ran out of session, we need to restore our previously stored
* state.
*/
context->init = PR_FALSE;
PK11_EnterContextMonitor(context);
if (!context->ownSession) {
rv = pk11_restoreContext(context,context->savedData,
context->savedLength);
if (rv != SECSuccess) {
PK11_ExitContextMonitor(context);
return rv;
}
}
switch (context->operation) {
/* also for MAC'ing */
case CKA_SIGN:
crv=PK11_GETTAB(context->slot)->C_SignUpdate(context->session,
(unsigned char *)in,
inLen);
break;
case CKA_VERIFY:
crv=PK11_GETTAB(context->slot)->C_VerifyUpdate(context->session,
(unsigned char *)in,
inLen);
break;
case CKA_DIGEST:
crv=PK11_GETTAB(context->slot)->C_DigestUpdate(context->session,
(unsigned char *)in,
inLen);
break;
default:
crv = CKR_OPERATION_NOT_INITIALIZED;
break;
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
rv = SECFailure;
}
/*
* handle session starvation case.. use our last session to multiplex
*/
if (!context->ownSession) {
context->savedData = pk11_saveContext(context,context->savedData,
&context->savedLength);
if (context->savedData == NULL) rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
PK11_ExitContextMonitor(context);
return rv;
}
/*
* Digest a key if possible./
*/
SECStatus
PK11_DigestKey(PK11Context *context, PK11SymKey *key)
{
CK_RV crv = CKR_OK;
SECStatus rv = SECSuccess;
PK11SymKey *newKey = NULL;
/* if we ran out of session, we need to restore our previously stored
* state.
*/
if (context->slot != key->slot) {
newKey = pk11_CopyToSlot(context->slot,CKM_SSL3_SHA1_MAC,CKA_SIGN,key);
} else {
newKey = PK11_ReferenceSymKey(key);
}
context->init = PR_FALSE;
PK11_EnterContextMonitor(context);
if (!context->ownSession) {
rv = pk11_restoreContext(context,context->savedData,
context->savedLength);
if (rv != SECSuccess) {
PK11_ExitContextMonitor(context);
PK11_FreeSymKey(newKey);
return rv;
}
}
if (newKey == NULL) {
crv = CKR_KEY_TYPE_INCONSISTENT;
if (key->data.data) {
crv=PK11_GETTAB(context->slot)->C_DigestUpdate(context->session,
key->data.data,key->data.len);
}
} else {
crv=PK11_GETTAB(context->slot)->C_DigestKey(context->session,
newKey->objectID);
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
rv = SECFailure;
}
/*
* handle session starvation case.. use our last session to multiplex
*/
if (!context->ownSession) {
context->savedData = pk11_saveContext(context,context->savedData,
&context->savedLength);
if (context->savedData == NULL) rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
PK11_ExitContextMonitor(context);
if (newKey) PK11_FreeSymKey(newKey);
return rv;
}
/*
* externally callable version of the lowercase pk11_finalize().
*/
SECStatus
PK11_Finalize(PK11Context *context) {
SECStatus rv;
PK11_EnterContextMonitor(context);
rv = pk11_Finalize(context);
PK11_ExitContextMonitor(context);
return rv;
}
/*
* clean up a cipher operation, so the session can be used by
* someone new.
*/
SECStatus
pk11_Finalize(PK11Context *context)
{
CK_ULONG count = 0;
CK_RV crv;
if (!context->ownSession) {
return SECSuccess;
}
switch (context->operation) {
case CKA_ENCRYPT:
crv=PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
NULL,&count);
break;
case CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session,
NULL,&count);
break;
case CKA_SIGN:
crv=PK11_GETTAB(context->slot)->C_SignFinal(context->session,
NULL,&count);
break;
case CKA_VERIFY:
crv=PK11_GETTAB(context->slot)->C_VerifyFinal(context->session,
NULL,count);
break;
case CKA_DIGEST:
crv=PK11_GETTAB(context->slot)->C_DigestFinal(context->session,
NULL,&count);
break;
default:
crv = CKR_OPERATION_NOT_INITIALIZED;
break;
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/*
* Return the final digested or signed data...
* this routine can either take pre initialized data, or allocate data
* either out of an arena or out of the standard heap.
*/
SECStatus
PK11_DigestFinal(PK11Context *context,unsigned char *data,
unsigned int *outLen, unsigned int length)
{
CK_ULONG len;
CK_RV crv;
SECStatus rv;
/* if we ran out of session, we need to restore our previously stored
* state.
*/
PK11_EnterContextMonitor(context);
if (!context->ownSession) {
rv = pk11_restoreContext(context,context->savedData,
context->savedLength);
if (rv != SECSuccess) {
PK11_ExitContextMonitor(context);
return rv;
}
}
len = length;
switch (context->operation) {
case CKA_SIGN:
crv=PK11_GETTAB(context->slot)->C_SignFinal(context->session,
data,&len);
break;
case CKA_VERIFY:
crv=PK11_GETTAB(context->slot)->C_VerifyFinal(context->session,
data,len);
break;
case CKA_DIGEST:
crv=PK11_GETTAB(context->slot)->C_DigestFinal(context->session,
data,&len);
break;
case CKA_ENCRYPT:
crv=PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
data, &len);
break;
case CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session,
data, &len);
break;
default:
crv = CKR_OPERATION_NOT_INITIALIZED;
break;
}
PK11_ExitContextMonitor(context);
*outLen = (unsigned int) len;
context->init = PR_FALSE; /* allow Begin to start up again */
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
return SECSuccess;
}
/****************************************************************************
*
* Now Do The PBE Functions Here...
*
****************************************************************************/
static void
pk11_destroy_ck_pbe_params(CK_PBE_PARAMS *pbe_params)
{
if (pbe_params) {
if (pbe_params->pPassword)
PORT_ZFree(pbe_params->pPassword, PR_FALSE);
if (pbe_params->pSalt)
PORT_ZFree(pbe_params->pSalt, PR_FALSE);
PORT_ZFree(pbe_params, PR_TRUE);
}
}
SECItem *
PK11_CreatePBEParams(SECItem *salt, SECItem *pwd, unsigned int iterations)
{
CK_PBE_PARAMS *pbe_params = NULL;
SECItem *paramRV = NULL;
pbe_params = (CK_PBE_PARAMS *)PORT_ZAlloc(sizeof(CK_PBE_PARAMS));
pbe_params->pPassword = (CK_CHAR_PTR)PORT_ZAlloc(pwd->len);
if (pbe_params->pPassword != NULL) {
PORT_Memcpy(pbe_params->pPassword, pwd->data, pwd->len);
pbe_params->ulPasswordLen = pwd->len;
} else goto loser;
pbe_params->pSalt = (CK_CHAR_PTR)PORT_ZAlloc(salt->len);
if (pbe_params->pSalt != NULL) {
PORT_Memcpy(pbe_params->pSalt, salt->data, salt->len);
pbe_params->ulSaltLen = salt->len;
} else goto loser;
pbe_params->ulIteration = (CK_ULONG)iterations;
paramRV = SECITEM_AllocItem(NULL, NULL, sizeof(CK_PBE_PARAMS));
paramRV->data = (unsigned char *)pbe_params;
return paramRV;
loser:
pk11_destroy_ck_pbe_params(pbe_params);
return NULL;
}
void
PK11_DestroyPBEParams(SECItem *params)
{
pk11_destroy_ck_pbe_params((CK_PBE_PARAMS *)params->data);
}
SECAlgorithmID *
PK11_CreatePBEAlgorithmID(SECOidTag algorithm, int iteration, SECItem *salt)
{
SECAlgorithmID *algid;
algid = SEC_PKCS5CreateAlgorithmID(algorithm, salt, iteration);
return algid;
}
PK11SymKey *
PK11_PBEKeyGen(PK11SlotInfo *slot, SECAlgorithmID *algid, SECItem *pwitem,
PRBool faulty3DES, void *wincx)
{
/* pbe stuff */
CK_PBE_PARAMS *pbe_params;
CK_MECHANISM_TYPE type;
SECItem *mech;
PK11SymKey *symKey;
mech = PK11_ParamFromAlgid(algid);
type = PK11_AlgtagToMechanism(SECOID_FindOIDTag(&algid->algorithm));
if(faulty3DES && (type == CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC)) {
type = CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC;
}
if(mech == NULL) {
return NULL;
}
pbe_params = (CK_PBE_PARAMS *)mech->data;
pbe_params->pPassword = (CK_CHAR_PTR)PORT_ZAlloc(pwitem->len);
if(pbe_params->pPassword != NULL) {
PORT_Memcpy(pbe_params->pPassword, pwitem->data, pwitem->len);
pbe_params->ulPasswordLen = pwitem->len;
} else {
SECITEM_ZfreeItem(mech, PR_TRUE);
return NULL;
}
symKey = PK11_KeyGen(slot, type, mech, 0, wincx);
PORT_ZFree(pbe_params->pPassword, pwitem->len);
SECITEM_ZfreeItem(mech, PR_TRUE);
return symKey;
}
SECStatus
PK11_ImportEncryptedPrivateKeyInfo(PK11SlotInfo *slot,
SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
SECItem *nickname, SECItem *publicValue, PRBool isPerm,
PRBool isPrivate, KeyType keyType, unsigned int keyUsage,
void *wincx)
{
CK_MECHANISM_TYPE mechanism;
SECItem *pbe_param, crypto_param;
PK11SymKey *key = NULL;
SECStatus rv = SECSuccess;
CK_MECHANISM cryptoMech, pbeMech;
CK_RV crv;
SECKEYPrivateKey *privKey = NULL;
PRBool faulty3DES = PR_FALSE;
int usageCount;
CK_KEY_TYPE key_type;
CK_ATTRIBUTE_TYPE *usage;
CK_ATTRIBUTE_TYPE rsaUsage[] = {
CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER };
CK_ATTRIBUTE_TYPE dsaUsage[] = { CKA_SIGN };
CK_ATTRIBUTE_TYPE dhUsage[] = { CKA_DERIVE };
if((epki == NULL) || (pwitem == NULL))
return SECFailure;
crypto_param.data = NULL;
mechanism = PK11_AlgtagToMechanism(SECOID_FindOIDTag(
&epki->algorithm.algorithm));
switch (keyType) {
default:
case rsaKey:
key_type = CKK_RSA;
switch (keyUsage & (KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE)) {
case KU_KEY_ENCIPHERMENT:
usage = rsaUsage;
usageCount = 2;
break;
case KU_DIGITAL_SIGNATURE:
usage = &rsaUsage[2];
usageCount = 2;
break;
case KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE:
case 0: /* default to everything */
usage = rsaUsage;
usageCount = 4;
break;
}
break;
case dhKey:
key_type = CKK_DH;
usage = dhUsage;
usageCount = sizeof(dhUsage)/sizeof(dhUsage[0]);
break;
case dsaKey:
key_type = CKK_DSA;
usage = dsaUsage;
usageCount = sizeof(dsaUsage)/sizeof(dsaUsage[0]);
break;
}
try_faulty_3des:
pbe_param = PK11_ParamFromAlgid(&epki->algorithm);
key = PK11_PBEKeyGen(slot, &epki->algorithm, pwitem, faulty3DES, wincx);
if((key == NULL) || (pbe_param == NULL)) {
rv = SECFailure;
goto done;
}
pbeMech.mechanism = mechanism;
pbeMech.pParameter = pbe_param->data;
pbeMech.ulParameterLen = pbe_param->len;
crv = PK11_MapPBEMechanismToCryptoMechanism(&pbeMech, &cryptoMech,
pwitem, faulty3DES);
if(crv != CKR_OK) {
rv = SECFailure;
goto done;
}
cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMech.mechanism);
crypto_param.data = (unsigned char*)cryptoMech.pParameter;
crypto_param.len = cryptoMech.ulParameterLen;
privKey = PK11_UnwrapPrivKey(slot, key, cryptoMech.mechanism,
&crypto_param, &epki->encryptedData,
nickname, publicValue, isPerm, isPrivate,
key_type, usage, usageCount, wincx);
if(privKey) {
SECKEY_DestroyPrivateKey(privKey);
privKey = NULL;
rv = SECSuccess;
goto done;
}
/* if we are unable to import the key and the mechanism is
* CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC, then it is possible that
* the encrypted blob was created with a buggy key generation method
* which is described in the PKCS 12 implementation notes. So we
* need to try importing via that method.
*/
if((mechanism == CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC) && (!faulty3DES)) {
/* clean up after ourselves before redoing the key generation. */
PK11_FreeSymKey(key);
key = NULL;
if(pbe_param) {
SECITEM_ZfreeItem(pbe_param, PR_TRUE);
pbe_param = NULL;
}
if(crypto_param.data) {
SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
crypto_param.data = NULL;
cryptoMech.pParameter = NULL;
crypto_param.len = cryptoMech.ulParameterLen = 0;
}
faulty3DES = PR_TRUE;
goto try_faulty_3des;
}
/* key import really did fail */
rv = SECFailure;
done:
if(pbe_param != NULL) {
SECITEM_ZfreeItem(pbe_param, PR_TRUE);
pbe_param = NULL;
}
if(crypto_param.data != NULL) {
SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
}
if(key != NULL) {
PK11_FreeSymKey(key);
}
return rv;
}
SECStatus
PK11_ImportDERPrivateKeyInfo(PK11SlotInfo *slot, SECItem *derPKI,
SECItem *nickname, SECItem *publicValue, PRBool isPerm,
PRBool isPrivate, unsigned int keyUsage, void *wincx)
{
SECKEYPrivateKeyInfo *pki = NULL;
PRArenaPool *temparena = NULL;
SECStatus rv = SECFailure;
temparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
pki = PORT_ZNew(SECKEYPrivateKeyInfo);
rv = SEC_ASN1DecodeItem(temparena, pki, SECKEY_PrivateKeyInfoTemplate,
derPKI);
if( rv != SECSuccess ) {
goto finish;
}
rv = PK11_ImportPrivateKeyInfo(slot, pki, nickname, publicValue,
isPerm, isPrivate, keyUsage, wincx);
finish:
if( pki != NULL ) {
SECKEY_DestroyPrivateKeyInfo(pki, PR_TRUE /*freeit*/);
}
if( temparena != NULL ) {
PORT_FreeArena(temparena, PR_TRUE);
}
return rv;
}
/*
* import a private key info into the desired slot
*/
SECStatus
PK11_ImportPrivateKeyInfo(PK11SlotInfo *slot, SECKEYPrivateKeyInfo *pki,
SECItem *nickname, SECItem *publicValue, PRBool isPerm,
PRBool isPrivate, unsigned int keyUsage, void *wincx)
{
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_OBJECT_CLASS keyClass = CKO_PRIVATE_KEY;
CK_KEY_TYPE keyType = CKK_RSA;
CK_OBJECT_HANDLE objectID;
CK_ATTRIBUTE theTemplate[20];
int templateCount = 0;
SECStatus rv = SECFailure;
SECKEYLowPrivateKey *lpk = NULL;
const SEC_ASN1Template *keyTemplate, *paramTemplate;
void *paramDest = NULL;
PRArenaPool *arena;
CK_ATTRIBUTE *attrs;
CK_ATTRIBUTE *signedattr = NULL;
int signedcount = 0;
CK_ATTRIBUTE *ap;
SECItem *ck_id = NULL;
arena = PORT_NewArena(2048);
if(!arena) {
return SECFailure;
}
/* need to change this to use RSA/DSA keys */
lpk = (SECKEYLowPrivateKey *)PORT_ArenaZAlloc(arena,
sizeof(SECKEYLowPrivateKey));
if(lpk == NULL) {
goto loser;
}
lpk->arena = arena;
attrs = theTemplate;
switch(SECOID_GetAlgorithmTag(&pki->algorithm)) {
case SEC_OID_PKCS1_RSA_ENCRYPTION:
keyTemplate = SECKEY_RSAPrivateKeyTemplate;
paramTemplate = NULL;
paramDest = NULL;
lpk->keyType = rsaKey;
keyType = CKK_RSA;
break;
case SEC_OID_ANSIX9_DSA_SIGNATURE:
keyTemplate = SECKEY_DSAPrivateKeyExportTemplate;
paramTemplate = SECKEY_PQGParamsTemplate;
paramDest = &(lpk->u.dsa.params);
lpk->keyType = dsaKey;
keyType = CKK_DSA;
break;
case SEC_OID_X942_DIFFIE_HELMAN_KEY:
if(!publicValue) {
goto loser;
}
keyTemplate = SECKEY_DHPrivateKeyExportTemplate;
paramTemplate = NULL;
paramDest = NULL;
lpk->keyType = dhKey;
keyType = CKK_DH;
break;
default:
keyTemplate = NULL;
paramTemplate = NULL;
paramDest = NULL;
break;
}
if(!keyTemplate) {
goto loser;
}
/* decode the private key and any algorithm parameters */
rv = SEC_ASN1DecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
if(rv != SECSuccess) {
goto loser;
}
if(paramDest && paramTemplate) {
rv = SEC_ASN1DecodeItem(arena, paramDest, paramTemplate,
&(pki->algorithm.parameters));
if(rv != SECSuccess) {
goto loser;
}
}
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
PK11_SETATTRS(attrs, CKA_TOKEN, isPerm ? &cktrue : &ckfalse,
sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_SENSITIVE, isPrivate ? &cktrue : &ckfalse,
sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_PRIVATE, isPrivate ? &cktrue : &ckfalse,
sizeof(CK_BBOOL) ); attrs++;
switch (lpk->keyType) {
case rsaKey:
PK11_SETATTRS(attrs, CKA_UNWRAP, (keyUsage & KU_KEY_ENCIPHERMENT) ?
&cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_DECRYPT, (keyUsage & KU_DATA_ENCIPHERMENT) ?
&cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_SIGN, (keyUsage & KU_DIGITAL_SIGNATURE) ?
&cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
PK11_SETATTRS(attrs, CKA_SIGN_RECOVER,
(keyUsage & KU_DIGITAL_SIGNATURE) ?
&cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
ck_id = PK11_MakeIDFromPubKey(&lpk->u.rsa.modulus);
if (ck_id == NULL) {
goto loser;
}
PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
if (nickname) {
PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len); attrs++;
}
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_MODULUS, lpk->u.rsa.modulus.data,
lpk->u.rsa.modulus.len); attrs++;
PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
lpk->u.rsa.publicExponent.data,
lpk->u.rsa.publicExponent.len); attrs++;
PK11_SETATTRS(attrs, CKA_PRIVATE_EXPONENT,
lpk->u.rsa.privateExponent.data,
lpk->u.rsa.privateExponent.len); attrs++;
PK11_SETATTRS(attrs, CKA_PRIME_1,
lpk->u.rsa.prime1.data,
lpk->u.rsa.prime1.len); attrs++;
PK11_SETATTRS(attrs, CKA_PRIME_2,
lpk->u.rsa.prime2.data,
lpk->u.rsa.prime2.len); attrs++;
PK11_SETATTRS(attrs, CKA_EXPONENT_1,
lpk->u.rsa.exponent1.data,
lpk->u.rsa.exponent1.len); attrs++;
PK11_SETATTRS(attrs, CKA_EXPONENT_2,
lpk->u.rsa.exponent2.data,
lpk->u.rsa.exponent2.len); attrs++;
PK11_SETATTRS(attrs, CKA_COEFFICIENT,
lpk->u.rsa.coefficient.data,
lpk->u.rsa.coefficient.len); attrs++;
break;
case dsaKey:
/* To make our intenal PKCS #11 module work correctly with
* our database, we need to pass in the public key value for
* this dsa key. We have a netscape only CKA_ value to do this.
* Only send it to internal slots */
if( publicValue == NULL ) {
/*
* Try to extract the public value out of the private key.
* This might not work, since the public value is not
* required to be in the private key.
*/
publicValue = &lpk->u.dsa.publicValue;
if( publicValue->data == NULL || publicValue->len == 0) {
goto loser;
}
}
if (PK11_IsInternal(slot)) {
PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
publicValue->data, publicValue->len); attrs++;
}
PK11_SETATTRS(attrs, CKA_SIGN, &cktrue, sizeof(CK_BBOOL)); attrs++;
PK11_SETATTRS(attrs, CKA_SIGN_RECOVER, &cktrue, sizeof(CK_BBOOL)); attrs++;
if(nickname) {
PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len);
attrs++;
}
ck_id = PK11_MakeIDFromPubKey(publicValue);
if (ck_id == NULL) {
goto loser;
}
PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, lpk->u.dsa.params.prime.data,
lpk->u.dsa.params.prime.len); attrs++;
PK11_SETATTRS(attrs,CKA_SUBPRIME,lpk->u.dsa.params.subPrime.data,
lpk->u.dsa.params.subPrime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, lpk->u.dsa.params.base.data,
lpk->u.dsa.params.base.len); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.dsa.privateValue.data,
lpk->u.dsa.privateValue.len); attrs++;
break;
case dhKey:
/* To make our intenal PKCS #11 module work correctly with
* our database, we need to pass in the public key value for
* this dh key. We have a netscape only CKA_ value to do this.
* Only send it to internal slots */
if (PK11_IsInternal(slot)) {
PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
publicValue->data, publicValue->len); attrs++;
}
PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL)); attrs++;
if(nickname) {
PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len);
attrs++;
}
ck_id = PK11_MakeIDFromPubKey(publicValue);
if (ck_id == NULL) {
goto loser;
}
PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
signedattr = attrs;
PK11_SETATTRS(attrs, CKA_PRIME, lpk->u.dh.prime.data,
lpk->u.dh.prime.len); attrs++;
PK11_SETATTRS(attrs, CKA_BASE, lpk->u.dh.base.data,
lpk->u.dh.base.len); attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.dh.privateValue.data,
lpk->u.dh.privateValue.len); attrs++;
break;
/* what about fortezza??? */
default:
PORT_SetError(SEC_ERROR_BAD_KEY);
goto loser;
}
templateCount = attrs - theTemplate;
PR_ASSERT(templateCount <= sizeof(theTemplate)/sizeof(CK_ATTRIBUTE));
signedcount = attrs - signedattr;
for (ap=signedattr; signedcount; ap++, signedcount--) {
pk11_SignedToUnsigned(ap);
}
rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION,
theTemplate, templateCount, isPerm, &objectID);
if (ck_id) {
SECITEM_ZfreeItem(ck_id, PR_TRUE);
}
loser:
if (lpk!= NULL) {
SECKEY_LowDestroyPrivateKey(lpk);
}
return rv;
}
SECKEYPrivateKeyInfo *
PK11_ExportPrivateKeyInfo(CERTCertificate *cert, void *wincx)
{
return NULL;
}
static int
pk11_private_key_encrypt_buffer_length(SECKEYPrivateKey *key)
{
CK_ATTRIBUTE rsaTemplate = { CKA_MODULUS, NULL, 0 };
CK_ATTRIBUTE dsaTemplate = { CKA_PRIME, NULL, 0 };
CK_ATTRIBUTE_PTR pTemplate;
CK_RV crv;
int length;
if(!key) {
return -1;
}
switch (key->keyType) {
case rsaKey:
pTemplate = &rsaTemplate;
break;
case dsaKey:
case dhKey:
pTemplate = &dsaTemplate;
break;
case fortezzaKey:
default:
pTemplate = NULL;
}
if(!pTemplate) {
return -1;
}
crv = PK11_GetAttributes(NULL, key->pkcs11Slot, key->pkcs11ID,
pTemplate, 1);
if(crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return -1;
}
length = pTemplate->ulValueLen;
length *= 10;
if(pTemplate->pValue != NULL) {
PORT_Free(pTemplate->pValue);
}
return length;
}
SECKEYEncryptedPrivateKeyInfo *
PK11_ExportEncryptedPrivateKeyInfo(PK11SlotInfo *slot, SECOidTag algTag,
SECItem *pwitem, CERTCertificate *cert, int iteration, void *wincx)
{
SECKEYEncryptedPrivateKeyInfo *epki = NULL;
SECKEYPrivateKey *pk;
PRArenaPool *arena = NULL;
SECAlgorithmID *algid;
CK_MECHANISM_TYPE mechanism;
SECItem *pbe_param = NULL, crypto_param;
PK11SymKey *key = NULL;
SECStatus rv = SECSuccess;
CK_MECHANISM pbeMech, cryptoMech;
CK_ULONG encBufLenPtr;
CK_RV crv;
SECItem encryptedKey = {siBuffer,NULL,0};
int encryptBufLen;
if(!pwitem)
return NULL;
crypto_param.data = NULL;
arena = PORT_NewArena(2048);
epki = (SECKEYEncryptedPrivateKeyInfo *)PORT_ArenaZAlloc(arena,
sizeof(SECKEYEncryptedPrivateKeyInfo));
if(epki == NULL) {
rv = SECFailure;
goto loser;
}
epki->arena = arena;
algid = SEC_PKCS5CreateAlgorithmID(algTag, NULL, iteration);
if(algid == NULL) {
rv = SECFailure;
goto loser;
}
mechanism = PK11_AlgtagToMechanism(SECOID_FindOIDTag(&algid->algorithm));
pbe_param = PK11_ParamFromAlgid(algid);
pbeMech.mechanism = mechanism;
pbeMech.pParameter = pbe_param->data;
pbeMech.ulParameterLen = pbe_param->len;
key = PK11_PBEKeyGen(slot, algid, pwitem, PR_FALSE, wincx);
if((key == NULL) || (pbe_param == NULL)) {
rv = SECFailure;
goto loser;
}
crv = PK11_MapPBEMechanismToCryptoMechanism(&pbeMech, &cryptoMech,
pwitem, PR_FALSE);
if(crv != CKR_OK) {
rv = SECFailure;
goto loser;
}
cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMech.mechanism);
crypto_param.data = (unsigned char *)cryptoMech.pParameter;
crypto_param.len = cryptoMech.ulParameterLen;
pk = PK11_FindKeyByAnyCert(cert, wincx);
if(pk == NULL) {
rv = SECFailure;
goto loser;
}
encryptBufLen = pk11_private_key_encrypt_buffer_length(pk);
if(encryptBufLen == -1) {
rv = SECFailure;
goto loser;
}
encryptedKey.len = (unsigned int)encryptBufLen;
encBufLenPtr = (CK_ULONG) encryptBufLen;
encryptedKey.data = (unsigned char *)PORT_ZAlloc(encryptedKey.len);
if(!encryptedKey.data) {
rv = SECFailure;
goto loser;
}
/* we are extracting an encrypted privateKey structure.
* which needs to be freed along with the buffer into which it is
* returned. eventually, we should retrieve an encrypted key using
* pkcs8/pkcs5.
*/
PK11_EnterSlotMonitor(pk->pkcs11Slot);
crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session,
&cryptoMech, key->objectID, pk->pkcs11ID, encryptedKey.data,
&encBufLenPtr);
PK11_ExitSlotMonitor(pk->pkcs11Slot);
encryptedKey.len = (unsigned int) encBufLenPtr;
if(crv != CKR_OK) {
rv = SECFailure;
goto loser;
}
if(!encryptedKey.len) {
rv = SECFailure;
goto loser;
}
rv = SECITEM_CopyItem(arena, &epki->encryptedData, &encryptedKey);
if(rv != SECSuccess) {
goto loser;
}
rv = SECOID_CopyAlgorithmID(arena, &epki->algorithm, algid);
loser:
if(pbe_param != NULL) {
SECITEM_ZfreeItem(pbe_param, PR_TRUE);
pbe_param = NULL;
}
if(crypto_param.data != NULL) {
SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
crypto_param.data = NULL;
}
if(key != NULL) {
PK11_FreeSymKey(key);
}
if(rv == SECFailure) {
if(arena != NULL) {
PORT_FreeArena(arena, PR_TRUE);
}
epki = NULL;
}
return epki;
}
/*
* This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
* working. This function simply gets a valid IV for the keys.
*/
SECStatus
PK11_GenerateFortezzaIV(PK11SymKey *symKey,unsigned char *iv,int len)
{
CK_MECHANISM mech_info;
CK_ULONG count = 0;
CK_RV crv;
SECStatus rv = SECFailure;
mech_info.mechanism = CKM_SKIPJACK_CBC64;
mech_info.pParameter = iv;
mech_info.ulParameterLen = len;
/* generate the IV for fortezza */
PK11_EnterSlotMonitor(symKey->slot);
crv=PK11_GETTAB(symKey->slot)->C_EncryptInit(symKey->slot->session,
&mech_info, symKey->objectID);
if (crv == CKR_OK) {
PK11_GETTAB(symKey->slot)->C_EncryptFinal(symKey->slot->session,
NULL, &count);
rv = SECSuccess;
}
PK11_ExitSlotMonitor(symKey->slot);
return rv;
}
SECKEYPrivateKey *
PK11_UnwrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
CK_MECHANISM_TYPE wrapType, SECItem *param,
SECItem *wrappedKey, SECItem *label,
SECItem *idValue, PRBool perm, PRBool sensitive,
CK_KEY_TYPE keyType, CK_ATTRIBUTE_TYPE *usage, int usageCount,
void *wincx)
{
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_OBJECT_CLASS keyClass = CKO_PRIVATE_KEY;
CK_ATTRIBUTE keyTemplate[15] ;
int templateCount = 0;
CK_OBJECT_HANDLE privKeyID;
CK_MECHANISM mechanism;
CK_ATTRIBUTE *attrs = keyTemplate;
SECItem *param_free = NULL, *ck_id;
CK_RV crv;
CK_SESSION_HANDLE rwsession;
PK11SymKey *newKey = NULL;
int i;
if(!slot || !wrappedKey || !idValue) {
/* SET AN ERROR!!! */
return NULL;
}
ck_id = PK11_MakeIDFromPubKey(idValue);
if(!ck_id) {
return NULL;
}
PK11_SETATTRS(attrs, CKA_TOKEN, perm ? &cktrue : &ckfalse,
sizeof(cktrue)); attrs++;
PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass)); attrs++;
PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType)); attrs++;
PK11_SETATTRS(attrs, CKA_PRIVATE, sensitive ? &cktrue : &ckfalse,
sizeof(cktrue)); attrs++;
PK11_SETATTRS(attrs, CKA_SENSITIVE, sensitive ? &cktrue : &ckfalse,
sizeof(cktrue)); attrs++;
PK11_SETATTRS(attrs, CKA_LABEL, label->data, label->len); attrs++;
PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len); attrs++;
for (i=0; i < usageCount; i++) {
PK11_SETATTRS(attrs, usage[i], &cktrue, sizeof(cktrue)); attrs++;
}
if (PK11_IsInternal(slot)) {
PK11_SETATTRS(attrs, CKA_NETSCAPE_DB, idValue->data,
idValue->len); attrs++;
}
templateCount = attrs - keyTemplate;
PR_ASSERT(templateCount <= (sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)) );
mechanism.mechanism = wrapType;
if(!param) param = param_free= PK11_ParamFromIV(wrapType, NULL);
if(param) {
mechanism.pParameter = param->data;
mechanism.ulParameterLen = param->len;
} else {
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
}
if (wrappingKey->slot != slot) {
newKey = pk11_CopyToSlot(slot,wrapType,CKA_WRAP,wrappingKey);
} else {
newKey = PK11_ReferenceSymKey(wrappingKey);
}
if (newKey) {
if (perm) {
rwsession = PK11_GetRWSession(slot);
} else {
rwsession = slot->session;
}
crv = PK11_GETTAB(slot)->C_UnwrapKey(rwsession, &mechanism,
newKey->objectID,
wrappedKey->data,
wrappedKey->len, keyTemplate,
templateCount, &privKeyID);
if (perm) PK11_RestoreROSession(slot, rwsession);
PK11_FreeSymKey(newKey);
} else {
crv = CKR_FUNCTION_NOT_SUPPORTED;
}
if(ck_id) {
SECITEM_FreeItem(ck_id, PR_TRUE);
ck_id = NULL;
}
if (crv != CKR_OK) {
/* we couldn't unwrap the key, use the internal module to do the
* unwrap, then load the new key into the token */
PK11SlotInfo *int_slot = PK11_GetInternalSlot();
if (int_slot && (slot != int_slot)) {
SECKEYPrivateKey *privKey = PK11_UnwrapPrivKey(int_slot,
wrappingKey, wrapType, param, wrappedKey, label,
idValue, PR_FALSE, PR_FALSE,
keyType, usage, usageCount, wincx);
if (privKey) {
SECKEYPrivateKey *newPrivKey = pk11_loadPrivKey(slot,privKey,
NULL,perm,sensitive);
SECKEY_DestroyPrivateKey(privKey);
PK11_FreeSlot(int_slot);
return newPrivKey;
}
}
if (int_slot) PK11_FreeSlot(int_slot);
PORT_SetError( PK11_MapError(crv) );
return NULL;
}
return PK11_MakePrivKey(slot, nullKey, PR_FALSE, privKeyID, wincx);
}
#define ALLOC_BLOCK 10
/*
* Now we're going to wrap a SECKEYPrivateKey with a PK11SymKey
* The strategy is to get both keys to reside in the same slot,
* one that can perform the desired crypto mechanism and then
* call C_WrapKey after all the setup has taken place.
*/
SECStatus
PK11_WrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
SECKEYPrivateKey *privKey, CK_MECHANISM_TYPE wrapType,
SECItem *param, SECItem *wrappedKey, void *wincx)
{
PK11SlotInfo *privSlot = privKey->pkcs11Slot; /* The slot where
* the private key
* we are going to
* wrap lives.
*/
PK11SymKey *newSymKey = NULL;
SECKEYPrivateKey *newPrivKey = NULL;
SECItem *param_free = NULL;
CK_ULONG len = wrappedKey->len;
CK_MECHANISM mech;
CK_RV crv;
if (!privSlot || !PK11_DoesMechanism(privSlot, wrapType)) {
/* Figure out a slot that does the mechanism and try to import
* the private key onto that slot.
*/
PK11SlotInfo *int_slot = PK11_GetInternalSlot();
privSlot = int_slot; /* The private key has a new home */
newPrivKey = pk11_loadPrivKey(privSlot,privKey,NULL,PR_FALSE,PR_FALSE);
if (newPrivKey == NULL) {
PK11_FreeSlot (int_slot);
return SECFailure;
}
privKey = newPrivKey;
}
if (privSlot != wrappingKey->slot) {
newSymKey = pk11_CopyToSlot (privSlot, wrapType, CKA_WRAP,
wrappingKey);
wrappingKey = newSymKey;
}
if (wrappingKey == NULL) {
if (newPrivKey) {
SECKEY_DestroyPrivateKey(newPrivKey);
}
return SECFailure;
}
mech.mechanism = wrapType;
if (!param) {
param = param_free = PK11_ParamFromIV(wrapType, NULL);
}
if (param) {
mech.pParameter = param->data;
mech.ulParameterLen = param->len;
} else {
mech.pParameter = NULL;
mech.ulParameterLen = 0;
}
PK11_EnterSlotMonitor(privSlot);
crv = PK11_GETTAB(privSlot)->C_WrapKey(privSlot->session, &mech,
wrappingKey->objectID,
privKey->pkcs11ID,
wrappedKey->data, &len);
PK11_ExitSlotMonitor(privSlot);
if (newSymKey) {
PK11_FreeSymKey(newSymKey);
}
if (newPrivKey) {
SECKEY_DestroyPrivateKey(newPrivKey);
}
if (crv != CKR_OK) {
PORT_SetError( PK11_MapError(crv) );
return SECFailure;
}
wrappedKey->len = len;
return SECSuccess;
}
void
PK11_SetFortezzaHack(PK11SymKey *symKey) {
symKey->origin = PK11_OriginFortezzaHack;
}
SECItem*
PK11_DEREncodePublicKey(SECKEYPublicKey *pubk)
{
CERTSubjectPublicKeyInfo *spki=NULL;
SECItem *spkiDER = NULL;
if( pubk == NULL ) {
return NULL;
}
/* get the subjectpublickeyinfo */
spki = SECKEY_CreateSubjectPublicKeyInfo(pubk);
if( spki == NULL ) {
goto finish;
}
/* DER-encode the subjectpublickeyinfo */
spkiDER = SEC_ASN1EncodeItem(NULL /*arena*/, NULL/*dest*/, spki,
CERT_SubjectPublicKeyInfoTemplate);
finish:
return spkiDER;
}
PK11SymKey*
PK11_CopySymKeyForSigning(PK11SymKey *originalKey, CK_MECHANISM_TYPE mech)
{
return pk11_CopyToSlot(PK11_GetSlotFromKey(originalKey), mech, CKA_SIGN,
originalKey);
}
|