1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 the Initial Developer are Copyright (C) 1994-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Dr Stephen Henson <stephen.henson@gemplus.com>
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* This file implements PKCS 11 on top of our existing security modules
*
* For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
* This implementation has two slots:
* slot 1 is our generic crypto support. It does not require login.
* It supports Public Key ops, and all they bulk ciphers and hashes.
* It can also support Private Key ops for imported Private keys. It does
* not have any token storage.
* slot 2 is our private key support. It requires a login before use. It
* can store Private Keys and Certs as token objects. Currently only private
* keys and their associated Certificates are saved on the token.
*
* In this implementation, session objects are only visible to the session
* that created or generated them.
*/
#include "seccomon.h"
#include "secitem.h"
#include "pkcs11.h"
#include "pkcs11i.h"
#include "softoken.h"
#include "lowkeyi.h"
#include "blapi.h"
#include "secder.h"
#include "secport.h"
#include "pcert.h"
#include "secrng.h"
#include "softkver.h"
#include "keydbi.h"
#ifdef DEBUG
#include "cdbhdl.h"
#endif
/*
* ******************** Static data *******************************
*/
/* The next three strings must be exactly 32 characters long */
static char *manufacturerID = "Mozilla Foundation ";
static char manufacturerID_space[33];
static char *libraryDescription = "NSS Internal Crypto Services ";
static char libraryDescription_space[33];
/*
* In FIPS mode, we disallow login attempts for 1 second after a login
* failure so that there are at most 60 login attempts per minute.
*/
static PRIntervalTime loginWaitTime;
static PRUint32 minSessionObjectHandle = 1U;
#define __PASTE(x,y) x##y
/*
* we renamed all our internal functions, get the correct
* definitions for them...
*/
#undef CK_PKCS11_FUNCTION_INFO
#undef CK_NEED_ARG_LIST
#define CK_EXTERN extern
#define CK_PKCS11_FUNCTION_INFO(func) \
CK_RV __PASTE(NS,func)
#define CK_NEED_ARG_LIST 1
#include "pkcs11f.h"
/* build the crypto module table */
static const CK_FUNCTION_LIST sftk_funcList = {
{ 1, 10 },
#undef CK_PKCS11_FUNCTION_INFO
#undef CK_NEED_ARG_LIST
#define CK_PKCS11_FUNCTION_INFO(func) \
__PASTE(NS,func),
#include "pkcs11f.h"
};
#undef CK_PKCS11_FUNCTION_INFO
#undef CK_NEED_ARG_LIST
#undef __PASTE
/* List of DES Weak Keys */
typedef unsigned char desKey[8];
static const desKey sftk_desWeakTable[] = {
#ifdef noParity
/* weak */
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x1e, 0x1e, 0x1e, 0x1e, 0x0e, 0x0e, 0x0e, 0x0e },
{ 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0xf0, 0xf0 },
{ 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe },
/* semi-weak */
{ 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe },
{ 0xfe, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0xfe },
{ 0x1e, 0xe0, 0x1e, 0xe0, 0x0e, 0xf0, 0x0e, 0xf0 },
{ 0xe0, 0x1e, 0xe0, 0x1e, 0xf0, 0x0e, 0xf0, 0x0e },
{ 0x00, 0xe0, 0x00, 0xe0, 0x00, 0x0f, 0x00, 0x0f },
{ 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00 },
{ 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe },
{ 0xfe, 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e },
{ 0x00, 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e },
{ 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e, 0x00 },
{ 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0, 0xfe },
{ 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0 },
#else
/* weak */
{ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
{ 0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e },
{ 0xe0, 0xe0, 0xe0, 0xe0, 0xf1, 0xf1, 0xf1, 0xf1 },
{ 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe },
/* semi-weak */
{ 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe },
{ 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01 },
{ 0x1f, 0xe0, 0x1f, 0xe0, 0x0e, 0xf1, 0x0e, 0xf1 },
{ 0xe0, 0x1f, 0xe0, 0x1f, 0xf1, 0x0e, 0xf1, 0x0e },
{ 0x01, 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1 },
{ 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1, 0x01 },
{ 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe },
{ 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e },
{ 0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e },
{ 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01 },
{ 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe },
{ 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1 }
#endif
};
static const int sftk_desWeakTableSize = sizeof(sftk_desWeakTable)/
sizeof(sftk_desWeakTable[0]);
/* DES KEY Parity conversion table. Takes each byte/2 as an index, returns
* that byte with the proper parity bit set */
static const unsigned char parityTable[256] = {
/* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */
/* E */ 0x01,0x02,0x04,0x07,0x08,0x0b,0x0d,0x0e,
/* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */
/* O */ 0x10,0x13,0x15,0x16,0x19,0x1a,0x1c,0x1f,
/* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */
/* O */ 0x20,0x23,0x25,0x26,0x29,0x2a,0x2c,0x2f,
/* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */
/* E */ 0x31,0x32,0x34,0x37,0x38,0x3b,0x3d,0x3e,
/* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */
/* O */ 0x40,0x43,0x45,0x46,0x49,0x4a,0x4c,0x4f,
/* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */
/* E */ 0x51,0x52,0x54,0x57,0x58,0x5b,0x5d,0x5e,
/* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */
/* E */ 0x61,0x62,0x64,0x67,0x68,0x6b,0x6d,0x6e,
/* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */
/* O */ 0x70,0x73,0x75,0x76,0x79,0x7a,0x7c,0x7f,
/* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */
/* O */ 0x80,0x83,0x85,0x86,0x89,0x8a,0x8c,0x8f,
/* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */
/* E */ 0x91,0x92,0x94,0x97,0x98,0x9b,0x9d,0x9e,
/* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */
/* E */ 0xa1,0xa2,0xa4,0xa7,0xa8,0xab,0xad,0xae,
/* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */
/* O */ 0xb0,0xb3,0xb5,0xb6,0xb9,0xba,0xbc,0xbf,
/* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */
/* E */ 0xc1,0xc2,0xc4,0xc7,0xc8,0xcb,0xcd,0xce,
/* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */
/* O */ 0xd0,0xd3,0xd5,0xd6,0xd9,0xda,0xdc,0xdf,
/* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */
/* O */ 0xe0,0xe3,0xe5,0xe6,0xe9,0xea,0xec,0xef,
/* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */
/* E */ 0xf1,0xf2,0xf4,0xf7,0xf8,0xfb,0xfd,0xfe,
};
/* Mechanisms */
struct mechanismList {
CK_MECHANISM_TYPE type;
CK_MECHANISM_INFO info;
PRBool privkey;
};
/*
* the following table includes a complete list of mechanism defined by
* PKCS #11 version 2.01. Those Mechanisms not supported by this PKCS #11
* module are ifdef'ed out.
*/
#define CKF_EN_DE CKF_ENCRYPT | CKF_DECRYPT
#define CKF_WR_UN CKF_WRAP | CKF_UNWRAP
#define CKF_SN_VR CKF_SIGN | CKF_VERIFY
#define CKF_SN_RE CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER
#define CKF_EN_DE_WR_UN CKF_EN_DE | CKF_WR_UN
#define CKF_SN_VR_RE CKF_SN_VR | CKF_SN_RE
#define CKF_DUZ_IT_ALL CKF_EN_DE_WR_UN | CKF_SN_VR_RE
#define CKF_EC_PNU CKF_EC_FP | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS
#define CKF_EC_BPNU CKF_EC_F_2M | CKF_EC_PNU
#define CK_MAX 0xffffffff
static const struct mechanismList mechanisms[] = {
/*
* PKCS #11 Mechanism List.
*
* The first argument is the PKCS #11 Mechanism we support.
* The second argument is Mechanism info structure. It includes:
* The minimum key size,
* in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs.
* in bytes for RC5, AES, and CAST*
* ignored for DES*, IDEA and FORTEZZA based
* The maximum key size,
* in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs.
* in bytes for RC5, AES, and CAST*
* ignored for DES*, IDEA and FORTEZZA based
* Flags
* What operations are supported by this mechanism.
* The third argument is a bool which tells if this mechanism is
* supported in the database token.
*
*/
/* ------------------------- RSA Operations ---------------------------*/
{CKM_RSA_PKCS_KEY_PAIR_GEN,{RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_GENERATE_KEY_PAIR},PR_TRUE},
{CKM_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_DUZ_IT_ALL}, PR_TRUE},
#ifdef SFTK_RSA9796_SUPPORTED
{CKM_RSA_9796, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_DUZ_IT_ALL}, PR_TRUE},
#endif
{CKM_RSA_X_509, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_DUZ_IT_ALL}, PR_TRUE},
/* -------------- RSA Multipart Signing Operations -------------------- */
{CKM_MD2_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
{CKM_MD5_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
{CKM_SHA1_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
{CKM_SHA256_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
{CKM_SHA384_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
{CKM_SHA512_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX,
CKF_SN_VR}, PR_TRUE},
/* ------------------------- DSA Operations --------------------------- */
{CKM_DSA_KEY_PAIR_GEN, {DSA_MIN_P_BITS, DSA_MAX_P_BITS,
CKF_GENERATE_KEY_PAIR}, PR_TRUE},
{CKM_DSA, {DSA_MIN_P_BITS, DSA_MAX_P_BITS,
CKF_SN_VR}, PR_TRUE},
{CKM_DSA_SHA1, {DSA_MIN_P_BITS, DSA_MAX_P_BITS,
CKF_SN_VR}, PR_TRUE},
/* -------------------- Diffie Hellman Operations --------------------- */
/* no diffie hellman yet */
{CKM_DH_PKCS_KEY_PAIR_GEN, {DH_MIN_P_BITS, DH_MAX_P_BITS,
CKF_GENERATE_KEY_PAIR}, PR_TRUE},
{CKM_DH_PKCS_DERIVE, {DH_MIN_P_BITS, DH_MAX_P_BITS,
CKF_DERIVE}, PR_TRUE},
#ifdef NSS_ENABLE_ECC
/* -------------------- Elliptic Curve Operations --------------------- */
{CKM_EC_KEY_PAIR_GEN, {112, 571, CKF_GENERATE_KEY_PAIR|CKF_EC_BPNU}, PR_TRUE},
{CKM_ECDH1_DERIVE, {112, 571, CKF_DERIVE|CKF_EC_BPNU}, PR_TRUE},
{CKM_ECDSA, {112, 571, CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE},
{CKM_ECDSA_SHA1, {112, 571, CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE},
#endif /* NSS_ENABLE_ECC */
/* ------------------------- RC2 Operations --------------------------- */
{CKM_RC2_KEY_GEN, {1, 128, CKF_GENERATE}, PR_TRUE},
{CKM_RC2_ECB, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_RC2_CBC, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_RC2_MAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_RC2_MAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_RC2_CBC_PAD, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE},
/* ------------------------- RC4 Operations --------------------------- */
{CKM_RC4_KEY_GEN, {1, 256, CKF_GENERATE}, PR_FALSE},
{CKM_RC4, {1, 256, CKF_EN_DE_WR_UN}, PR_FALSE},
/* ------------------------- DES Operations --------------------------- */
{CKM_DES_KEY_GEN, { 8, 8, CKF_GENERATE}, PR_TRUE},
{CKM_DES_ECB, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_DES_CBC, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_DES_MAC, { 8, 8, CKF_SN_VR}, PR_TRUE},
{CKM_DES_MAC_GENERAL, { 8, 8, CKF_SN_VR}, PR_TRUE},
{CKM_DES_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_DES2_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE},
{CKM_DES3_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE },
{CKM_DES3_ECB, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE },
{CKM_DES3_CBC, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE },
{CKM_DES3_MAC, {24, 24, CKF_SN_VR}, PR_TRUE },
{CKM_DES3_MAC_GENERAL, {24, 24, CKF_SN_VR}, PR_TRUE },
{CKM_DES3_CBC_PAD, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE },
/* ------------------------- CDMF Operations --------------------------- */
{CKM_CDMF_KEY_GEN, {8, 8, CKF_GENERATE}, PR_TRUE},
{CKM_CDMF_ECB, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CDMF_CBC, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CDMF_MAC, {8, 8, CKF_SN_VR}, PR_TRUE},
{CKM_CDMF_MAC_GENERAL, {8, 8, CKF_SN_VR}, PR_TRUE},
{CKM_CDMF_CBC_PAD, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
/* ------------------------- AES Operations --------------------------- */
{CKM_AES_KEY_GEN, {16, 32, CKF_GENERATE}, PR_TRUE},
{CKM_AES_ECB, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_AES_CBC, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_AES_MAC, {16, 32, CKF_SN_VR}, PR_TRUE},
{CKM_AES_MAC_GENERAL, {16, 32, CKF_SN_VR}, PR_TRUE},
{CKM_AES_CBC_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
/* ------------------------- Hashing Operations ----------------------- */
{CKM_MD2, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_MD2_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_MD2_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_MD5, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_MD5_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_MD5_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA_1, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_SHA_1_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA_1_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA256, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_SHA256_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA256_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA384, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_SHA384_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA384_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA512, {0, 0, CKF_DIGEST}, PR_FALSE},
{CKM_SHA512_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_SHA512_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE},
{CKM_TLS_PRF_GENERAL, {0, 512, CKF_SN_VR}, PR_FALSE},
/* ------------------------- CAST Operations --------------------------- */
#ifdef NSS_SOFTOKEN_DOES_CAST
/* Cast operations are not supported ( yet? ) */
{CKM_CAST_KEY_GEN, {1, 8, CKF_GENERATE}, PR_TRUE},
{CKM_CAST_ECB, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST_CBC, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST_MAC, {1, 8, CKF_SN_VR}, PR_TRUE},
{CKM_CAST_MAC_GENERAL, {1, 8, CKF_SN_VR}, PR_TRUE},
{CKM_CAST_CBC_PAD, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST3_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE},
{CKM_CAST3_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST3_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST3_MAC, {1, 16, CKF_SN_VR}, PR_TRUE},
{CKM_CAST3_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE},
{CKM_CAST3_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST5_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE},
{CKM_CAST5_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST5_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_CAST5_MAC, {1, 16, CKF_SN_VR}, PR_TRUE},
{CKM_CAST5_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE},
{CKM_CAST5_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
#endif
#if NSS_SOFTOKEN_DOES_RC5
/* ------------------------- RC5 Operations --------------------------- */
{CKM_RC5_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE},
{CKM_RC5_ECB, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_RC5_CBC, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_RC5_MAC, {1, 32, CKF_SN_VR}, PR_TRUE},
{CKM_RC5_MAC_GENERAL, {1, 32, CKF_SN_VR}, PR_TRUE},
{CKM_RC5_CBC_PAD, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
#endif
#ifdef NSS_SOFTOKEN_DOES_IDEA
/* ------------------------- IDEA Operations -------------------------- */
{CKM_IDEA_KEY_GEN, {16, 16, CKF_GENERATE}, PR_TRUE},
{CKM_IDEA_ECB, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_IDEA_CBC, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_IDEA_MAC, {16, 16, CKF_SN_VR}, PR_TRUE},
{CKM_IDEA_MAC_GENERAL, {16, 16, CKF_SN_VR}, PR_TRUE},
{CKM_IDEA_CBC_PAD, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE},
#endif
/* --------------------- Secret Key Operations ------------------------ */
{CKM_GENERIC_SECRET_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE},
{CKM_CONCATENATE_BASE_AND_KEY, {1, 32, CKF_GENERATE}, PR_FALSE},
{CKM_CONCATENATE_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE},
{CKM_CONCATENATE_DATA_AND_BASE, {1, 32, CKF_GENERATE}, PR_FALSE},
{CKM_XOR_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE},
{CKM_EXTRACT_KEY_FROM_KEY, {1, 32, CKF_DERIVE}, PR_FALSE},
/* ---------------------- SSL Key Derivations ------------------------- */
{CKM_SSL3_PRE_MASTER_KEY_GEN, {48, 48, CKF_GENERATE}, PR_FALSE},
{CKM_SSL3_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE},
{CKM_SSL3_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE},
{CKM_SSL3_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE},
{CKM_SSL3_MD5_MAC, { 0, 16, CKF_DERIVE}, PR_FALSE},
{CKM_SSL3_SHA1_MAC, { 0, 20, CKF_DERIVE}, PR_FALSE},
{CKM_MD5_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE},
{CKM_MD2_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE},
{CKM_SHA1_KEY_DERIVATION, { 0, 20, CKF_DERIVE}, PR_FALSE},
{CKM_TLS_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE},
{CKM_TLS_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE},
{CKM_TLS_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE},
/* ---------------------- PBE Key Derivations ------------------------ */
{CKM_PBE_MD2_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE},
{CKM_PBE_MD5_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE},
/* ------------------ NETSCAPE PBE Key Derivations ------------------- */
{CKM_NETSCAPE_PBE_SHA1_DES_CBC, { 8, 8, CKF_GENERATE}, PR_TRUE},
{CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC, {24,24, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_DES3_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_DES2_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_RC2_40_CBC, {40,40, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_RC2_128_CBC, {128,128, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_RC4_40, {40,40, CKF_GENERATE}, PR_TRUE},
{CKM_PBE_SHA1_RC4_128, {128,128, CKF_GENERATE}, PR_TRUE},
{CKM_PBA_SHA1_WITH_SHA1_HMAC, {20,20, CKF_GENERATE}, PR_TRUE},
{CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN, {20,20, CKF_GENERATE}, PR_TRUE},
{CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE},
{CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE},
/* ------------------ AES Key Wrap (also encrypt) ------------------- */
{CKM_NETSCAPE_AES_KEY_WRAP, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
{CKM_NETSCAPE_AES_KEY_WRAP_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE},
};
static const CK_ULONG mechanismCount = sizeof(mechanisms)/sizeof(mechanisms[0]);
static char *
sftk_setStringName(const char *inString, char *buffer, int buffer_length)
{
int full_length, string_length;
full_length = buffer_length -1;
string_length = PORT_Strlen(inString);
/*
* shorten the string, respecting utf8 encoding
* to do so, we work backward from the end
* bytes looking from the end are either:
* - ascii [0x00,0x7f]
* - the [2-n]th byte of a multibyte sequence
* [0x3F,0xBF], i.e, most significant 2 bits are '10'
* - the first byte of a multibyte sequence [0xC0,0xFD],
* i.e, most significant 2 bits are '11'
*
* When the string is too long, we lop off any trailing '10' bytes,
* if any. When these are all eliminated we lop off
* one additional byte. Thus if we lopped any '10'
* we'll be lopping a '11' byte (the first byte of the multibyte sequence),
* otherwise we're lopping off an ascii character.
*
* To test for '10' bytes, we first AND it with
* 11000000 (0xc0) so that we get 10000000 (0x80) if and only if
* the byte starts with 10. We test for equality.
*/
while ( string_length > full_length ) {
/* need to shorten */
while ( string_length > 0 &&
((inString[string_length-1]&(char)0xc0) == (char)0x80)) {
/* lop off '10' byte */
string_length--;
}
/*
* test string_length in case bad data is received
* and string consisted of all '10' bytes,
* avoiding any infinite loop
*/
if ( string_length ) {
/* remove either '11' byte or an asci byte */
string_length--;
}
}
PORT_Memset(buffer,' ',full_length);
buffer[full_length] = 0;
PORT_Memcpy(buffer,inString,string_length);
return buffer;
}
/*
* Configuration utils
*/
static CK_RV
sftk_configure(const char *man, const char *libdes)
{
/* make sure the internationalization was done correctly... */
if (man) {
manufacturerID = sftk_setStringName(man,manufacturerID_space,
sizeof(manufacturerID_space));
}
if (libdes) {
libraryDescription = sftk_setStringName(libdes,
libraryDescription_space, sizeof(libraryDescription_space));
}
return CKR_OK;
}
/*
* ******************** Password Utilities *******************************
*/
/*
* see if the key DB password is enabled
*/
static PRBool
sftk_hasNullPassword(NSSLOWKEYDBHandle *keydb,SECItem **pwitem)
{
PRBool pwenabled;
pwenabled = PR_FALSE;
*pwitem = NULL;
if (nsslowkey_HasKeyDBPassword (keydb) == SECSuccess) {
*pwitem = nsslowkey_HashPassword("", keydb->global_salt);
if ( *pwitem ) {
if (nsslowkey_CheckKeyDBPassword (keydb, *pwitem) == SECSuccess) {
pwenabled = PR_TRUE;
} else {
SECITEM_ZfreeItem(*pwitem, PR_TRUE);
*pwitem = NULL;
}
}
}
return pwenabled;
}
/*
* ******************** Object Creation Utilities ***************************
*/
/* Make sure a given attribute exists. If it doesn't, initialize it to
* value and len
*/
CK_RV
sftk_defaultAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type,void *value,
unsigned int len)
{
if ( !sftk_hasAttribute(object, type)) {
return sftk_AddAttributeType(object,type,value,len);
}
return CKR_OK;
}
/*
* check the consistancy and initialize a Data Object
*/
static CK_RV
sftk_handleDataObject(SFTKSession *session,SFTKObject *object)
{
CK_RV crv;
/* first reject private and token data objects */
if (sftk_isTrue(object,CKA_PRIVATE) || sftk_isTrue(object,CKA_TOKEN)) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* now just verify the required date fields */
crv = sftk_defaultAttribute(object,CKA_APPLICATION,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_VALUE,NULL,0);
if (crv != CKR_OK) return crv;
return CKR_OK;
}
/*
* check the consistancy and initialize a Certificate Object
*/
static CK_RV
sftk_handleCertObject(SFTKSession *session,SFTKObject *object)
{
CK_CERTIFICATE_TYPE type;
SFTKAttribute *attribute;
CK_RV crv;
/* certificates must have a type */
if ( !sftk_hasAttribute(object,CKA_CERTIFICATE_TYPE) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* we can't store any certs private */
if (sftk_isTrue(object,CKA_PRIVATE)) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* We only support X.509 Certs for now */
attribute = sftk_FindAttribute(object,CKA_CERTIFICATE_TYPE);
if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE;
type = *(CK_CERTIFICATE_TYPE *)attribute->attrib.pValue;
sftk_FreeAttribute(attribute);
if (type != CKC_X_509) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* X.509 Certificate */
/* make sure we have a cert */
if ( !sftk_hasAttribute(object,CKA_VALUE) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* in PKCS #11, Subject is a required field */
if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* in PKCS #11, Issuer is a required field */
if ( !sftk_hasAttribute(object,CKA_ISSUER) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* in PKCS #11, Serial is a required field */
if ( !sftk_hasAttribute(object,CKA_SERIAL_NUMBER) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* add it to the object */
object->objectInfo = NULL;
object->infoFree = (SFTKFree) NULL;
/* now just verify the required date fields */
crv = sftk_defaultAttribute(object, CKA_ID, NULL, 0);
if (crv != CKR_OK) { return crv; }
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
SECItem derCert;
NSSLOWCERTCertificate *cert;
NSSLOWCERTCertTrust *trust = NULL;
NSSLOWCERTCertTrust userTrust =
{ CERTDB_USER, CERTDB_USER, CERTDB_USER };
NSSLOWCERTCertTrust defTrust =
{ CERTDB_TRUSTED_UNKNOWN,
CERTDB_TRUSTED_UNKNOWN, CERTDB_TRUSTED_UNKNOWN };
char *label = NULL;
char *email = NULL;
SECStatus rv;
PRBool inDB = PR_TRUE;
NSSLOWCERTCertDBHandle *certHandle = sftk_getCertDB(slot);
NSSLOWKEYDBHandle *keyHandle = NULL;
if (certHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
/* get the der cert */
attribute = sftk_FindAttribute(object,CKA_VALUE);
PORT_Assert(attribute);
derCert.type = 0;
derCert.data = (unsigned char *)attribute->attrib.pValue;
derCert.len = attribute->attrib.ulValueLen ;
label = sftk_getString(object,CKA_LABEL);
cert = nsslowcert_FindCertByDERCert(certHandle, &derCert);
if (cert == NULL) {
cert = nsslowcert_DecodeDERCertificate(&derCert, label);
inDB = PR_FALSE;
}
if (cert == NULL) {
if (label) PORT_Free(label);
sftk_FreeAttribute(attribute);
sftk_freeCertDB(certHandle);
return CKR_ATTRIBUTE_VALUE_INVALID;
}
keyHandle = sftk_getKeyDB(slot);
if (keyHandle) {
if (nsslowkey_KeyForCertExists(keyHandle,cert)) {
trust = &userTrust;
}
sftk_freeKeyDB(keyHandle);
}
if (!inDB) {
if (!trust) trust = &defTrust;
rv = nsslowcert_AddPermCert(certHandle, cert, label, trust);
} else {
rv = trust ? nsslowcert_ChangeCertTrust(certHandle,cert,trust) :
SECSuccess;
}
if (label) PORT_Free(label);
sftk_FreeAttribute(attribute);
if (rv != SECSuccess) {
sftk_freeCertDB(certHandle);
nsslowcert_DestroyCertificate(cert);
return CKR_DEVICE_ERROR;
}
/*
* Add a NULL S/MIME profile if necessary.
*/
email = sftk_getString(object,CKA_NETSCAPE_EMAIL);
if (email) {
certDBEntrySMime *entry;
entry = nsslowcert_ReadDBSMimeEntry(certHandle,email);
if (!entry) {
nsslowcert_SaveSMimeProfile(certHandle, email,
&cert->derSubject, NULL, NULL);
} else {
nsslowcert_DestroyDBEntry((certDBEntry *)entry);
}
PORT_Free(email);
}
sftk_freeCertDB(certHandle);
object->handle=sftk_mkHandle(slot,&cert->certKey,SFTK_TOKEN_TYPE_CERT);
nsslowcert_DestroyCertificate(cert);
}
return CKR_OK;
}
unsigned int
sftk_MapTrust(CK_TRUST trust, PRBool clientAuth)
{
unsigned int trustCA = clientAuth ? CERTDB_TRUSTED_CLIENT_CA :
CERTDB_TRUSTED_CA;
switch (trust) {
case CKT_NETSCAPE_TRUSTED:
return CERTDB_VALID_PEER|CERTDB_TRUSTED;
case CKT_NETSCAPE_TRUSTED_DELEGATOR:
return CERTDB_VALID_CA|trustCA;
case CKT_NETSCAPE_UNTRUSTED:
return CERTDB_NOT_TRUSTED;
case CKT_NETSCAPE_MUST_VERIFY:
return 0;
case CKT_NETSCAPE_VALID: /* implies must verify */
return CERTDB_VALID_PEER;
case CKT_NETSCAPE_VALID_DELEGATOR: /* implies must verify */
return CERTDB_VALID_CA;
default:
break;
}
return CERTDB_TRUSTED_UNKNOWN;
}
/*
* check the consistancy and initialize a Trust Object
*/
static CK_RV
sftk_handleTrustObject(SFTKSession *session,SFTKObject *object)
{
NSSLOWCERTIssuerAndSN issuerSN;
/* we can't store any certs private */
if (sftk_isTrue(object,CKA_PRIVATE)) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* certificates must have a type */
if ( !sftk_hasAttribute(object,CKA_ISSUER) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object,CKA_SERIAL_NUMBER) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object,CKA_CERT_SHA1_HASH) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object,CKA_CERT_MD5_HASH) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
SFTKAttribute *issuer = NULL;
SFTKAttribute *serial = NULL;
NSSLOWCERTCertificate *cert = NULL;
SFTKAttribute *trust;
CK_TRUST sslTrust = CKT_NETSCAPE_TRUST_UNKNOWN;
CK_TRUST clientTrust = CKT_NETSCAPE_TRUST_UNKNOWN;
CK_TRUST emailTrust = CKT_NETSCAPE_TRUST_UNKNOWN;
CK_TRUST signTrust = CKT_NETSCAPE_TRUST_UNKNOWN;
CK_BBOOL stepUp;
NSSLOWCERTCertTrust dbTrust = { 0 };
SECStatus rv;
NSSLOWCERTCertDBHandle *certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
issuer = sftk_FindAttribute(object,CKA_ISSUER);
PORT_Assert(issuer);
issuerSN.derIssuer.data = (unsigned char *)issuer->attrib.pValue;
issuerSN.derIssuer.len = issuer->attrib.ulValueLen ;
serial = sftk_FindAttribute(object,CKA_SERIAL_NUMBER);
PORT_Assert(serial);
issuerSN.serialNumber.data = (unsigned char *)serial->attrib.pValue;
issuerSN.serialNumber.len = serial->attrib.ulValueLen ;
cert = nsslowcert_FindCertByIssuerAndSN(certHandle,&issuerSN);
sftk_FreeAttribute(serial);
sftk_FreeAttribute(issuer);
if (cert == NULL) {
sftk_freeCertDB(certHandle);
return CKR_ATTRIBUTE_VALUE_INVALID;
}
trust = sftk_FindAttribute(object,CKA_TRUST_SERVER_AUTH);
if (trust) {
if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) {
PORT_Memcpy(&sslTrust,trust->attrib.pValue, sizeof(sslTrust));
}
sftk_FreeAttribute(trust);
}
trust = sftk_FindAttribute(object,CKA_TRUST_CLIENT_AUTH);
if (trust) {
if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) {
PORT_Memcpy(&clientTrust,trust->attrib.pValue,
sizeof(clientTrust));
}
sftk_FreeAttribute(trust);
}
trust = sftk_FindAttribute(object,CKA_TRUST_EMAIL_PROTECTION);
if (trust) {
if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) {
PORT_Memcpy(&emailTrust,trust->attrib.pValue,
sizeof(emailTrust));
}
sftk_FreeAttribute(trust);
}
trust = sftk_FindAttribute(object,CKA_TRUST_CODE_SIGNING);
if (trust) {
if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) {
PORT_Memcpy(&signTrust,trust->attrib.pValue,
sizeof(signTrust));
}
sftk_FreeAttribute(trust);
}
stepUp = CK_FALSE;
trust = sftk_FindAttribute(object,CKA_TRUST_STEP_UP_APPROVED);
if (trust) {
if (trust->attrib.ulValueLen == sizeof(CK_BBOOL)) {
stepUp = *(CK_BBOOL*)trust->attrib.pValue;
}
sftk_FreeAttribute(trust);
}
/* preserve certain old fields */
if (cert->trust) {
dbTrust.sslFlags =
cert->trust->sslFlags & CERTDB_PRESERVE_TRUST_BITS;
dbTrust.emailFlags=
cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS;
dbTrust.objectSigningFlags =
cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS;
}
dbTrust.sslFlags |= sftk_MapTrust(sslTrust,PR_FALSE);
dbTrust.sslFlags |= sftk_MapTrust(clientTrust,PR_TRUE);
dbTrust.emailFlags |= sftk_MapTrust(emailTrust,PR_FALSE);
dbTrust.objectSigningFlags |= sftk_MapTrust(signTrust,PR_FALSE);
if (stepUp) {
dbTrust.sslFlags |= CERTDB_GOVT_APPROVED_CA;
}
rv = nsslowcert_ChangeCertTrust(certHandle,cert,&dbTrust);
object->handle=sftk_mkHandle(slot,&cert->certKey,SFTK_TOKEN_TYPE_TRUST);
nsslowcert_DestroyCertificate(cert);
sftk_freeCertDB(certHandle);
if (rv != SECSuccess) {
return CKR_DEVICE_ERROR;
}
}
return CKR_OK;
}
/*
* check the consistancy and initialize a Trust Object
*/
static CK_RV
sftk_handleSMimeObject(SFTKSession *session,SFTKObject *object)
{
/* we can't store any certs private */
if (sftk_isTrue(object,CKA_PRIVATE)) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* certificates must have a type */
if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object,CKA_NETSCAPE_EMAIL) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
SECItem derSubj,rawProfile,rawTime,emailKey;
SECItem *pRawProfile = NULL;
SECItem *pRawTime = NULL;
char *email = NULL;
SFTKAttribute *subject,*profile,*time;
SECStatus rv;
NSSLOWCERTCertDBHandle *certHandle;
PORT_Assert(slot);
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
/* lookup SUBJECT */
subject = sftk_FindAttribute(object,CKA_SUBJECT);
PORT_Assert(subject);
derSubj.data = (unsigned char *)subject->attrib.pValue;
derSubj.len = subject->attrib.ulValueLen ;
derSubj.type = 0;
/* lookup VALUE */
profile = sftk_FindAttribute(object,CKA_VALUE);
if (profile) {
rawProfile.data = (unsigned char *)profile->attrib.pValue;
rawProfile.len = profile->attrib.ulValueLen ;
rawProfile.type = siBuffer;
pRawProfile = &rawProfile;
}
/* lookup Time */
time = sftk_FindAttribute(object,CKA_NETSCAPE_SMIME_TIMESTAMP);
if (time) {
rawTime.data = (unsigned char *)time->attrib.pValue;
rawTime.len = time->attrib.ulValueLen ;
rawTime.type = siBuffer;
pRawTime = &rawTime;
}
email = sftk_getString(object,CKA_NETSCAPE_EMAIL);
/* Store CRL by SUBJECT */
rv = nsslowcert_SaveSMimeProfile(certHandle, email, &derSubj,
pRawProfile,pRawTime);
sftk_freeCertDB(certHandle);
sftk_FreeAttribute(subject);
if (profile) sftk_FreeAttribute(profile);
if (time) sftk_FreeAttribute(time);
if (rv != SECSuccess) {
PORT_Free(email);
return CKR_DEVICE_ERROR;
}
emailKey.data = (unsigned char *)email;
emailKey.len = PORT_Strlen(email)+1;
object->handle = sftk_mkHandle(slot, &emailKey, SFTK_TOKEN_TYPE_SMIME);
PORT_Free(email);
}
return CKR_OK;
}
/*
* check the consistancy and initialize a Trust Object
*/
static CK_RV
sftk_handleCrlObject(SFTKSession *session,SFTKObject *object)
{
/* we can't store any certs private */
if (sftk_isTrue(object,CKA_PRIVATE)) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* certificates must have a type */
if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object,CKA_VALUE) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
PRBool isKRL = PR_FALSE;
SECItem derSubj,derCrl;
char *url = NULL;
SFTKAttribute *subject,*crl;
SECStatus rv;
NSSLOWCERTCertDBHandle *certHandle;
PORT_Assert(slot);
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
/* lookup SUBJECT */
subject = sftk_FindAttribute(object,CKA_SUBJECT);
PORT_Assert(subject);
derSubj.data = (unsigned char *)subject->attrib.pValue;
derSubj.len = subject->attrib.ulValueLen ;
/* lookup VALUE */
crl = sftk_FindAttribute(object,CKA_VALUE);
PORT_Assert(crl);
derCrl.data = (unsigned char *)crl->attrib.pValue;
derCrl.len = crl->attrib.ulValueLen ;
url = sftk_getString(object,CKA_NETSCAPE_URL);
isKRL = sftk_isTrue(object,CKA_NETSCAPE_KRL);
/* Store CRL by SUBJECT */
rv = nsslowcert_AddCrl(certHandle, &derCrl, &derSubj, url, isKRL);
sftk_freeCertDB(certHandle);
if (url) {
PORT_Free(url);
}
sftk_FreeAttribute(crl);
if (rv != SECSuccess) {
sftk_FreeAttribute(subject);
return CKR_DEVICE_ERROR;
}
/* if we overwrote the existing CRL, poison the handle entry so we get
* a new object handle */
(void) sftk_poisonHandle(slot, &derSubj,
isKRL ? SFTK_TOKEN_KRL_HANDLE : SFTK_TOKEN_TYPE_CRL);
object->handle = sftk_mkHandle(slot, &derSubj,
isKRL ? SFTK_TOKEN_KRL_HANDLE : SFTK_TOKEN_TYPE_CRL);
sftk_FreeAttribute(subject);
}
return CKR_OK;
}
/*
* check the consistancy and initialize a Public Key Object
*/
static CK_RV
sftk_handlePublicKeyObject(SFTKSession *session, SFTKObject *object,
CK_KEY_TYPE key_type)
{
CK_BBOOL encrypt = CK_TRUE;
CK_BBOOL recover = CK_TRUE;
CK_BBOOL wrap = CK_TRUE;
CK_BBOOL derive = CK_FALSE;
CK_BBOOL verify = CK_TRUE;
CK_ATTRIBUTE_TYPE pubKeyAttr = CKA_VALUE;
CK_RV crv;
switch (key_type) {
case CKK_RSA:
crv = sftk_ConstrainAttribute(object, CKA_MODULUS,
RSA_MIN_MODULUS_BITS, 0, 0);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_PUBLIC_EXPONENT, 2, 0, 0);
if (crv != CKR_OK) {
return crv;
}
pubKeyAttr = CKA_MODULUS;
break;
case CKK_DSA:
crv = sftk_ConstrainAttribute(object, CKA_SUBPRIME,
DSA_Q_BITS, DSA_Q_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_PRIME,
DSA_MIN_P_BITS, DSA_MAX_P_BITS, 64);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_BASE, 1, DSA_MAX_P_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_VALUE, 1, DSA_MAX_P_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
encrypt = CK_FALSE;
recover = CK_FALSE;
wrap = CK_FALSE;
break;
case CKK_DH:
crv = sftk_ConstrainAttribute(object, CKA_PRIME,
DH_MIN_P_BITS, DH_MAX_P_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_BASE, 1, DH_MAX_P_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_ConstrainAttribute(object, CKA_VALUE, 1, DH_MAX_P_BITS, 0);
if (crv != CKR_OK) {
return crv;
}
verify = CK_FALSE;
derive = CK_TRUE;
encrypt = CK_FALSE;
recover = CK_FALSE;
wrap = CK_FALSE;
break;
#ifdef NSS_ENABLE_ECC
case CKK_EC:
if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_EC_POINT)) {
return CKR_TEMPLATE_INCOMPLETE;
}
pubKeyAttr = CKA_EC_POINT;
derive = CK_TRUE; /* for ECDH */
verify = CK_TRUE; /* for ECDSA */
encrypt = CK_FALSE;
recover = CK_FALSE;
wrap = CK_FALSE;
break;
#endif /* NSS_ENABLE_ECC */
default:
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/* make sure the required fields exist */
crv = sftk_defaultAttribute(object,CKA_SUBJECT,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_ENCRYPT,&encrypt,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_VERIFY,&verify,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_VERIFY_RECOVER,
&recover,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_WRAP,&wrap,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
object->objectInfo = sftk_GetPubKey(object,key_type, &crv);
if (object->objectInfo == NULL) {
return crv;
}
object->infoFree = (SFTKFree) nsslowkey_DestroyPublicKey;
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
NSSLOWKEYPrivateKey *priv;
SECItem pubKey;
NSSLOWKEYDBHandle *keyHandle = NULL;
crv = sftk_Attribute2SSecItem(NULL,&pubKey,object,pubKeyAttr);
if (crv != CKR_OK) return crv;
PORT_Assert(pubKey.data);
keyHandle = sftk_getKeyDB(slot);
if (keyHandle == NULL) {
PORT_Free(pubKey.data);
return CKR_TOKEN_WRITE_PROTECTED;
}
if (keyHandle->version != 3) {
unsigned char buf[SHA1_LENGTH];
SHA1_HashBuf(buf,pubKey.data,pubKey.len);
PORT_Memcpy(pubKey.data,buf,sizeof(buf));
pubKey.len = sizeof(buf);
}
/* make sure the associated private key already exists */
/* only works if we are logged in */
priv = nsslowkey_FindKeyByPublicKey(keyHandle, &pubKey, slot->password);
sftk_freeKeyDB(keyHandle);
if (priv == NULL) {
PORT_Free(pubKey.data);
return crv;
}
nsslowkey_DestroyPrivateKey(priv);
object->handle = sftk_mkHandle(slot, &pubKey, SFTK_TOKEN_TYPE_PUB);
PORT_Free(pubKey.data);
}
return CKR_OK;
}
static NSSLOWKEYPrivateKey *
sftk_mkPrivKey(SFTKObject *object,CK_KEY_TYPE key, CK_RV *rvp);
/*
* check the consistancy and initialize a Private Key Object
*/
static CK_RV
sftk_handlePrivateKeyObject(SFTKSession *session,SFTKObject *object,CK_KEY_TYPE key_type)
{
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL encrypt = CK_TRUE;
CK_BBOOL sign = CK_FALSE;
CK_BBOOL recover = CK_TRUE;
CK_BBOOL wrap = CK_TRUE;
CK_BBOOL derive = CK_FALSE;
CK_BBOOL ckfalse = CK_FALSE;
SECItem mod;
CK_RV crv;
switch (key_type) {
case CKK_RSA:
if ( !sftk_hasAttribute(object, CKA_MODULUS)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_PUBLIC_EXPONENT)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_PRIVATE_EXPONENT)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_PRIME_1)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_PRIME_2)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_EXPONENT_1)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_EXPONENT_2)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_COEFFICIENT)) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* make sure Netscape DB attribute is set correctly */
crv = sftk_Attribute2SSecItem(NULL, &mod, object, CKA_MODULUS);
if (crv != CKR_OK) return crv;
crv = sftk_forceAttribute(object, CKA_NETSCAPE_DB,
sftk_item_expand(&mod));
if (mod.data) PORT_Free(mod.data);
if (crv != CKR_OK) return crv;
sign = CK_TRUE;
break;
case CKK_DSA:
if ( !sftk_hasAttribute(object, CKA_SUBPRIME)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if (sftk_isTrue(object,CKA_TOKEN) &&
!sftk_hasAttribute(object, CKA_NETSCAPE_DB)) {
return CKR_TEMPLATE_INCOMPLETE;
}
sign = CK_TRUE;
/* fall through */
case CKK_DH:
if ( !sftk_hasAttribute(object, CKA_PRIME)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_BASE)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_VALUE)) {
return CKR_TEMPLATE_INCOMPLETE;
}
encrypt = CK_FALSE;
recover = CK_FALSE;
wrap = CK_FALSE;
break;
#ifdef NSS_ENABLE_ECC
case CKK_EC:
if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if ( !sftk_hasAttribute(object, CKA_VALUE)) {
return CKR_TEMPLATE_INCOMPLETE;
}
if (sftk_isTrue(object,CKA_TOKEN) &&
!sftk_hasAttribute(object, CKA_NETSCAPE_DB)) {
return CKR_TEMPLATE_INCOMPLETE;
}
encrypt = CK_FALSE;
sign = CK_TRUE;
recover = CK_FALSE;
wrap = CK_FALSE;
derive = CK_TRUE;
break;
#endif /* NSS_ENABLE_ECC */
default:
return CKR_ATTRIBUTE_VALUE_INVALID;
}
crv = sftk_defaultAttribute(object,CKA_SUBJECT,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_SENSITIVE,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_DECRYPT,&encrypt,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_SIGN,&sign,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_SIGN_RECOVER,&recover,
sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_UNWRAP,&wrap,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* the next two bits get modified only in the key gen and token cases */
crv = sftk_forceAttribute(object,CKA_ALWAYS_SENSITIVE,
&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_forceAttribute(object,CKA_NEVER_EXTRACTABLE,
&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* should we check the non-token RSA private keys? */
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
NSSLOWKEYPrivateKey *privKey;
char *label;
SECStatus rv = SECSuccess;
CK_RV crv = CKR_DEVICE_ERROR;
SECItem pubKey;
NSSLOWKEYDBHandle *keyHandle = sftk_getKeyDB(slot);
if (keyHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
privKey=sftk_mkPrivKey(object,key_type,&crv);
if (privKey == NULL) return crv;
label = sftk_getString(object,CKA_LABEL);
crv = sftk_Attribute2SSecItem(NULL,&pubKey,object,CKA_NETSCAPE_DB);
if (crv != CKR_OK) {
crv = CKR_TEMPLATE_INCOMPLETE;
rv = SECFailure;
goto fail;
}
if (keyHandle->version != 3) {
unsigned char buf[SHA1_LENGTH];
SHA1_HashBuf(buf,pubKey.data,pubKey.len);
PORT_Memcpy(pubKey.data,buf,sizeof(buf));
pubKey.len = sizeof(buf);
}
if (key_type == CKK_RSA) {
rv = RSA_PrivateKeyCheck(&privKey->u.rsa);
if (rv == SECFailure) {
goto fail;
}
}
rv = nsslowkey_StoreKeyByPublicKey(keyHandle, privKey, &pubKey,
label, slot->password);
fail:
sftk_freeKeyDB(keyHandle);
if (label) PORT_Free(label);
object->handle = sftk_mkHandle(slot,&pubKey,SFTK_TOKEN_TYPE_PRIV);
if (pubKey.data) PORT_Free(pubKey.data);
nsslowkey_DestroyPrivateKey(privKey);
if (rv != SECSuccess) return crv;
} else {
object->objectInfo = sftk_mkPrivKey(object,key_type,&crv);
if (object->objectInfo == NULL) return crv;
object->infoFree = (SFTKFree) nsslowkey_DestroyPrivateKey;
/* now NULL out the sensitive attributes */
/* remove nulled out attributes for session objects. these only
* applied to rsa private keys anyway (other private keys did not
* get their attributes NULL'ed out */
}
return CKR_OK;
}
/* forward declare the DES formating function for handleSecretKey */
void sftk_FormatDESKey(unsigned char *key, int length);
static NSSLOWKEYPrivateKey *sftk_mkSecretKeyRep(SFTKObject *object);
/* Validate secret key data, and set defaults */
static CK_RV
validateSecretKey(SFTKSession *session, SFTKObject *object,
CK_KEY_TYPE key_type, PRBool isFIPS)
{
CK_RV crv;
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
SFTKAttribute *attribute = NULL;
unsigned long requiredLen;
crv = sftk_defaultAttribute(object,CKA_SENSITIVE,
isFIPS?&cktrue:&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_EXTRACTABLE,
&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_ENCRYPT,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_DECRYPT,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_SIGN,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_VERIFY,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_WRAP,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_UNWRAP,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
if ( !sftk_hasAttribute(object, CKA_VALUE)) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* the next two bits get modified only in the key gen and token cases */
crv = sftk_forceAttribute(object,CKA_ALWAYS_SENSITIVE,
&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_forceAttribute(object,CKA_NEVER_EXTRACTABLE,
&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* some types of keys have a value length */
crv = CKR_OK;
switch (key_type) {
/* force CKA_VALUE_LEN to be set */
case CKK_GENERIC_SECRET:
case CKK_RC2:
case CKK_RC4:
#if NSS_SOFTOKEN_DOES_RC5
case CKK_RC5:
#endif
#ifdef NSS_SOFTOKEN_DOES_CAST
case CKK_CAST:
case CKK_CAST3:
case CKK_CAST5:
#endif
#if NSS_SOFTOKEN_DOES_IDEA
case CKK_IDEA:
#endif
attribute = sftk_FindAttribute(object,CKA_VALUE);
/* shouldn't happen */
if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE;
crv = sftk_forceAttribute(object, CKA_VALUE_LEN,
&attribute->attrib.ulValueLen, sizeof(CK_ULONG));
sftk_FreeAttribute(attribute);
break;
/* force the value to have the correct parity */
case CKK_DES:
case CKK_DES2:
case CKK_DES3:
case CKK_CDMF:
attribute = sftk_FindAttribute(object,CKA_VALUE);
/* shouldn't happen */
if (attribute == NULL)
return CKR_TEMPLATE_INCOMPLETE;
requiredLen = sftk_MapKeySize(key_type);
if (attribute->attrib.ulValueLen != requiredLen) {
sftk_FreeAttribute(attribute);
return CKR_KEY_SIZE_RANGE;
}
sftk_FormatDESKey((unsigned char*)attribute->attrib.pValue,
attribute->attrib.ulValueLen);
sftk_FreeAttribute(attribute);
break;
default:
break;
}
return crv;
}
#define SFTK_KEY_MAX_RETRIES 10 /* don't hang if we are having problems with the rng */
#define SFTK_KEY_ID_SIZE 18 /* don't use either SHA1 or MD5 sizes */
/*
* Secret keys must have a CKA_ID value to be stored in the database. This code
* will generate one if there wasn't one already.
*/
static CK_RV
sftk_GenerateSecretCKA_ID(NSSLOWKEYDBHandle *handle, SECItem *id, char *label)
{
unsigned int retries;
SECStatus rv = SECSuccess;
CK_RV crv = CKR_OK;
id->data = NULL;
if (label) {
id->data = (unsigned char *)PORT_Strdup(label);
if (id->data == NULL) {
return CKR_HOST_MEMORY;
}
id->len = PORT_Strlen(label)+1;
if (!nsslowkey_KeyForIDExists(handle,id)) {
return CKR_OK;
}
PORT_Free(id->data);
id->data = NULL;
id->len = 0;
}
id->data = (unsigned char *)PORT_Alloc(SFTK_KEY_ID_SIZE);
if (id->data == NULL) {
return CKR_HOST_MEMORY;
}
id->len = SFTK_KEY_ID_SIZE;
retries = 0;
do {
rv = RNG_GenerateGlobalRandomBytes(id->data,id->len);
} while (rv == SECSuccess && nsslowkey_KeyForIDExists(handle,id) &&
(++retries <= SFTK_KEY_MAX_RETRIES));
if ((rv != SECSuccess) || (retries > SFTK_KEY_MAX_RETRIES)) {
if (rv != SECSuccess) {
sftk_fatalError = PR_TRUE;
}
crv = CKR_DEVICE_ERROR; /* random number generator is bad */
PORT_Free(id->data);
id->data = NULL;
id->len = 0;
}
return crv;
}
/*
* check the consistancy and initialize a Secret Key Object
*/
static CK_RV
sftk_handleSecretKeyObject(SFTKSession *session,SFTKObject *object,
CK_KEY_TYPE key_type, PRBool isFIPS)
{
CK_RV crv;
NSSLOWKEYPrivateKey *privKey = NULL;
NSSLOWKEYDBHandle *keyHandle = NULL;
SECItem pubKey;
char *label = NULL;
pubKey.data = 0;
/* First validate and set defaults */
crv = validateSecretKey(session, object, key_type, isFIPS);
if (crv != CKR_OK) goto loser;
/* If the object is a TOKEN object, store in the database */
if (sftk_isTrue(object,CKA_TOKEN)) {
SFTKSlot *slot = session->slot;
SECStatus rv = SECSuccess;
keyHandle = sftk_getKeyDB(slot);
if (keyHandle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
label = sftk_getString(object,CKA_LABEL);
crv = sftk_Attribute2SecItem(NULL, &pubKey, object, CKA_ID);
/* Should this be ID? */
if (crv != CKR_OK) goto loser;
/* if we don't have an ID, generate one */
if (pubKey.len == 0) {
if (pubKey.data) {
PORT_Free(pubKey.data);
pubKey.data = NULL;
}
crv = sftk_GenerateSecretCKA_ID(keyHandle, &pubKey, label);
if (crv != CKR_OK) goto loser;
crv = sftk_forceAttribute(object, CKA_ID, pubKey.data, pubKey.len);
if (crv != CKR_OK) goto loser;
}
privKey = sftk_mkSecretKeyRep(object);
if (privKey == NULL) {
crv = CKR_HOST_MEMORY;
goto loser;
}
rv = nsslowkey_StoreKeyByPublicKey(keyHandle,
privKey, &pubKey, label, slot->password);
if (rv != SECSuccess) {
crv = CKR_DEVICE_ERROR;
goto loser;
}
object->handle = sftk_mkHandle(slot,&pubKey,SFTK_TOKEN_TYPE_KEY);
}
loser:
if (keyHandle) sftk_freeKeyDB(keyHandle);
if (label) PORT_Free(label);
if (privKey) nsslowkey_DestroyPrivateKey(privKey);
if (pubKey.data) PORT_Free(pubKey.data);
return crv;
}
/*
* check the consistancy and initialize a Key Object
*/
static CK_RV
sftk_handleKeyObject(SFTKSession *session, SFTKObject *object)
{
SFTKAttribute *attribute;
CK_KEY_TYPE key_type;
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_RV crv;
/* verify the required fields */
if ( !sftk_hasAttribute(object,CKA_KEY_TYPE) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* now verify the common fields */
crv = sftk_defaultAttribute(object,CKA_ID,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_START_DATE,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_END_DATE,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* get the key type */
attribute = sftk_FindAttribute(object,CKA_KEY_TYPE);
if (!attribute) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
sftk_FreeAttribute(attribute);
switch (object->objclass) {
case CKO_PUBLIC_KEY:
return sftk_handlePublicKeyObject(session,object,key_type);
case CKO_PRIVATE_KEY:
return sftk_handlePrivateKeyObject(session,object,key_type);
case CKO_SECRET_KEY:
/* make sure the required fields exist */
return sftk_handleSecretKeyObject(session,object,key_type,
(PRBool)(session->slot->slotID == FIPS_SLOT_ID));
default:
break;
}
return CKR_ATTRIBUTE_VALUE_INVALID;
}
/*
* check the consistancy and Verify a DSA Parameter Object
*/
static CK_RV
sftk_handleDSAParameterObject(SFTKSession *session, SFTKObject *object)
{
SFTKAttribute *primeAttr = NULL;
SFTKAttribute *subPrimeAttr = NULL;
SFTKAttribute *baseAttr = NULL;
SFTKAttribute *seedAttr = NULL;
SFTKAttribute *hAttr = NULL;
SFTKAttribute *attribute;
CK_RV crv = CKR_TEMPLATE_INCOMPLETE;
PQGParams params;
PQGVerify vfy, *verify = NULL;
SECStatus result,rv;
primeAttr = sftk_FindAttribute(object,CKA_PRIME);
if (primeAttr == NULL) goto loser;
params.prime.data = primeAttr->attrib.pValue;
params.prime.len = primeAttr->attrib.ulValueLen;
subPrimeAttr = sftk_FindAttribute(object,CKA_SUBPRIME);
if (subPrimeAttr == NULL) goto loser;
params.subPrime.data = subPrimeAttr->attrib.pValue;
params.subPrime.len = subPrimeAttr->attrib.ulValueLen;
baseAttr = sftk_FindAttribute(object,CKA_BASE);
if (baseAttr == NULL) goto loser;
params.base.data = baseAttr->attrib.pValue;
params.base.len = baseAttr->attrib.ulValueLen;
attribute = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_COUNTER);
if (attribute != NULL) {
vfy.counter = *(CK_ULONG *) attribute->attrib.pValue;
sftk_FreeAttribute(attribute);
seedAttr = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_SEED);
if (seedAttr == NULL) goto loser;
vfy.seed.data = seedAttr->attrib.pValue;
vfy.seed.len = seedAttr->attrib.ulValueLen;
hAttr = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_H);
if (hAttr == NULL) goto loser;
vfy.h.data = hAttr->attrib.pValue;
vfy.h.len = hAttr->attrib.ulValueLen;
verify = &vfy;
}
crv = CKR_FUNCTION_FAILED;
rv = PQG_VerifyParams(¶ms,verify,&result);
if (rv == SECSuccess) {
crv = (result== SECSuccess) ? CKR_OK : CKR_ATTRIBUTE_VALUE_INVALID;
}
loser:
if (hAttr) sftk_FreeAttribute(hAttr);
if (seedAttr) sftk_FreeAttribute(seedAttr);
if (baseAttr) sftk_FreeAttribute(baseAttr);
if (subPrimeAttr) sftk_FreeAttribute(subPrimeAttr);
if (primeAttr) sftk_FreeAttribute(primeAttr);
return crv;
}
/*
* check the consistancy and initialize a Key Parameter Object
*/
static CK_RV
sftk_handleKeyParameterObject(SFTKSession *session, SFTKObject *object)
{
SFTKAttribute *attribute;
CK_KEY_TYPE key_type;
CK_BBOOL ckfalse = CK_FALSE;
CK_RV crv;
/* verify the required fields */
if ( !sftk_hasAttribute(object,CKA_KEY_TYPE) ) {
return CKR_TEMPLATE_INCOMPLETE;
}
/* now verify the common fields */
crv = sftk_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* get the key type */
attribute = sftk_FindAttribute(object,CKA_KEY_TYPE);
if (!attribute) {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue;
sftk_FreeAttribute(attribute);
switch (key_type) {
case CKK_DSA:
return sftk_handleDSAParameterObject(session,object);
default:
break;
}
return CKR_KEY_TYPE_INCONSISTENT;
}
/*
* Handle Object does all the object consistancy checks, automatic attribute
* generation, attribute defaulting, etc. If handleObject succeeds, the object
* will be assigned an object handle, and the object installed in the session
* or stored in the DB.
*/
CK_RV
sftk_handleObject(SFTKObject *object, SFTKSession *session)
{
SFTKSlot *slot = session->slot;
SFTKAttribute *attribute;
SFTKObject *duplicateObject = NULL;
CK_OBJECT_HANDLE handle;
CK_BBOOL ckfalse = CK_FALSE;
CK_BBOOL cktrue = CK_TRUE;
CK_RV crv;
/* make sure all the base object types are defined. If not set the
* defaults */
crv = sftk_defaultAttribute(object,CKA_TOKEN,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_PRIVATE,&ckfalse,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_LABEL,NULL,0);
if (crv != CKR_OK) return crv;
crv = sftk_defaultAttribute(object,CKA_MODIFIABLE,&cktrue,sizeof(CK_BBOOL));
if (crv != CKR_OK) return crv;
/* don't create a private object if we aren't logged in */
if ((!slot->isLoggedIn) && (slot->needLogin) &&
(sftk_isTrue(object,CKA_PRIVATE))) {
return CKR_USER_NOT_LOGGED_IN;
}
if (((session->info.flags & CKF_RW_SESSION) == 0) &&
(sftk_isTrue(object,CKA_TOKEN))) {
return CKR_SESSION_READ_ONLY;
}
/* Assign a unique SESSION object handle to every new object,
* whether it is a session object or a token object.
* At this point, all new objects are structured as session objects.
* Objects with the CKA_TOKEN attribute true will be turned into
* token objects and will have a token object handle assigned to
* them by a call to sftk_mkHandle in the handler for each object
* class, invoked below.
*
* It may be helpful to note/remember that
* sftk_narrowToXxxObject uses sftk_isToken,
* sftk_isToken examines the sign bit of the object's handle, but
* sftk_isTrue(...,CKA_TOKEN) examines the CKA_TOKEN attribute.
*/
do {
PRUint32 wrappedAround;
duplicateObject = NULL;
PZ_Lock(slot->objectLock);
wrappedAround = slot->sessionObjectHandleCount & SFTK_TOKEN_MASK;
handle = slot->sessionObjectHandleCount & ~SFTK_TOKEN_MASK;
if (!handle) /* don't allow zero handle */
handle = minSessionObjectHandle;
slot->sessionObjectHandleCount = (handle + 1U) | wrappedAround;
/* Is there already a session object with this handle? */
if (wrappedAround) {
sftkqueue_find(duplicateObject, handle, slot->sessObjHashTable, \
slot->sessObjHashSize);
}
PZ_Unlock(slot->objectLock);
} while (duplicateObject != NULL);
object->handle = handle;
/* get the object class */
attribute = sftk_FindAttribute(object,CKA_CLASS);
if (attribute == NULL) {
return CKR_TEMPLATE_INCOMPLETE;
}
object->objclass = *(CK_OBJECT_CLASS *)attribute->attrib.pValue;
sftk_FreeAttribute(attribute);
/* Now handle the specific object class.
* At this point, all objects are session objects, and the session
* number must be passed to the object class handlers.
*/
switch (object->objclass) {
case CKO_DATA:
crv = sftk_handleDataObject(session,object);
break;
case CKO_CERTIFICATE:
crv = sftk_handleCertObject(session,object);
break;
case CKO_NETSCAPE_TRUST:
crv = sftk_handleTrustObject(session,object);
break;
case CKO_NETSCAPE_CRL:
crv = sftk_handleCrlObject(session,object);
break;
case CKO_NETSCAPE_SMIME:
crv = sftk_handleSMimeObject(session,object);
break;
case CKO_PRIVATE_KEY:
case CKO_PUBLIC_KEY:
case CKO_SECRET_KEY:
crv = sftk_handleKeyObject(session,object);
break;
case CKO_KG_PARAMETERS:
crv = sftk_handleKeyParameterObject(session,object);
break;
default:
crv = CKR_ATTRIBUTE_VALUE_INVALID;
break;
}
/* can't fail from here on out unless the pk_handlXXX functions have
* failed the request */
if (crv != CKR_OK) {
return crv;
}
/* Now link the object into the slot and session structures.
* If the object has a true CKA_TOKEN attribute, the above object
* class handlers will have set the sign bit in the object handle,
* causing the following test to be true.
*/
if (sftk_isToken(object->handle)) {
sftk_convertSessionToToken(object);
} else {
object->slot = slot;
sftk_AddObject(session,object);
}
return CKR_OK;
}
/*
* ******************** Public Key Utilities ***************************
*/
/* Generate a low public key structure from an object */
NSSLOWKEYPublicKey *sftk_GetPubKey(SFTKObject *object,CK_KEY_TYPE key_type,
CK_RV *crvp)
{
NSSLOWKEYPublicKey *pubKey;
PLArenaPool *arena;
CK_RV crv;
if (object->objclass != CKO_PUBLIC_KEY) {
*crvp = CKR_KEY_TYPE_INCONSISTENT;
return NULL;
}
if (sftk_isToken(object->handle)) {
/* ferret out the token object handle */
}
/* If we already have a key, use it */
if (object->objectInfo) {
*crvp = CKR_OK;
return (NSSLOWKEYPublicKey *)object->objectInfo;
}
/* allocate the structure */
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
*crvp = CKR_HOST_MEMORY;
return NULL;
}
pubKey = (NSSLOWKEYPublicKey *)
PORT_ArenaAlloc(arena,sizeof(NSSLOWKEYPublicKey));
if (pubKey == NULL) {
PORT_FreeArena(arena,PR_FALSE);
*crvp = CKR_HOST_MEMORY;
return NULL;
}
/* fill in the structure */
pubKey->arena = arena;
switch (key_type) {
case CKK_RSA:
pubKey->keyType = NSSLOWKEYRSAKey;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.rsa.modulus,
object,CKA_MODULUS);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.rsa.publicExponent,
object,CKA_PUBLIC_EXPONENT);
break;
case CKK_DSA:
pubKey->keyType = NSSLOWKEYDSAKey;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.prime,
object,CKA_PRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.subPrime,
object,CKA_SUBPRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.base,
object,CKA_BASE);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.publicValue,
object,CKA_VALUE);
break;
case CKK_DH:
pubKey->keyType = NSSLOWKEYDHKey;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.prime,
object,CKA_PRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.base,
object,CKA_BASE);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.publicValue,
object,CKA_VALUE);
break;
#ifdef NSS_ENABLE_ECC
case CKK_EC:
pubKey->keyType = NSSLOWKEYECKey;
crv = sftk_Attribute2SSecItem(arena,
&pubKey->u.ec.ecParams.DEREncoding,
object,CKA_EC_PARAMS);
if (crv != CKR_OK) break;
/* Fill out the rest of the ecParams structure
* based on the encoded params
*/
if (EC_FillParams(arena, &pubKey->u.ec.ecParams.DEREncoding,
&pubKey->u.ec.ecParams) != SECSuccess) {
crv = CKR_DOMAIN_PARAMS_INVALID;
break;
}
crv = sftk_Attribute2SSecItem(arena,&pubKey->u.ec.publicValue,
object,CKA_EC_POINT);
break;
#endif /* NSS_ENABLE_ECC */
default:
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
*crvp = crv;
if (crv != CKR_OK) {
PORT_FreeArena(arena,PR_FALSE);
return NULL;
}
object->objectInfo = pubKey;
object->infoFree = (SFTKFree) nsslowkey_DestroyPublicKey;
return pubKey;
}
/* make a private key from a verified object */
static NSSLOWKEYPrivateKey *
sftk_mkPrivKey(SFTKObject *object, CK_KEY_TYPE key_type, CK_RV *crvp)
{
NSSLOWKEYPrivateKey *privKey;
PLArenaPool *arena;
CK_RV crv = CKR_OK;
SECStatus rv;
PORT_Assert(!sftk_isToken(object->handle));
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) {
*crvp = CKR_HOST_MEMORY;
return NULL;
}
privKey = (NSSLOWKEYPrivateKey *)
PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey));
if (privKey == NULL) {
PORT_FreeArena(arena,PR_FALSE);
*crvp = CKR_HOST_MEMORY;
return NULL;
}
/* in future this would be a switch on key_type */
privKey->arena = arena;
switch (key_type) {
case CKK_RSA:
privKey->keyType = NSSLOWKEYRSAKey;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.modulus,
object,CKA_MODULUS);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.publicExponent,object,
CKA_PUBLIC_EXPONENT);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.privateExponent,object,
CKA_PRIVATE_EXPONENT);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.prime1,object,
CKA_PRIME_1);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.prime2,object,
CKA_PRIME_2);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.exponent1,
object, CKA_EXPONENT_1);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.exponent2,
object, CKA_EXPONENT_2);
if (crv != CKR_OK) break;
crv=sftk_Attribute2SSecItem(arena,&privKey->u.rsa.coefficient,object,
CKA_COEFFICIENT);
if (crv != CKR_OK) break;
rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version,
NSSLOWKEY_VERSION);
if (rv != SECSuccess) crv = CKR_HOST_MEMORY;
break;
case CKK_DSA:
privKey->keyType = NSSLOWKEYDSAKey;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dsa.params.prime,
object,CKA_PRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dsa.params.subPrime,
object,CKA_SUBPRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dsa.params.base,
object,CKA_BASE);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dsa.privateValue,
object,CKA_VALUE);
if (crv != CKR_OK) break;
if (sftk_hasAttribute(object,CKA_NETSCAPE_DB)) {
crv = sftk_Attribute2SSecItem(arena, &privKey->u.dsa.publicValue,
object,CKA_NETSCAPE_DB);
/* privKey was zero'd so public value is already set to NULL, 0
* if we don't set it explicitly */
}
break;
case CKK_DH:
privKey->keyType = NSSLOWKEYDHKey;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dh.prime,
object,CKA_PRIME);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dh.base,
object,CKA_BASE);
if (crv != CKR_OK) break;
crv = sftk_Attribute2SSecItem(arena,&privKey->u.dh.privateValue,
object,CKA_VALUE);
if (crv != CKR_OK) break;
if (sftk_hasAttribute(object,CKA_NETSCAPE_DB)) {
crv = sftk_Attribute2SSecItem(arena, &privKey->u.dh.publicValue,
object,CKA_NETSCAPE_DB);
/* privKey was zero'd so public value is already set to NULL, 0
* if we don't set it explicitly */
}
break;
#ifdef NSS_ENABLE_ECC
case CKK_EC:
privKey->keyType = NSSLOWKEYECKey;
crv = sftk_Attribute2SSecItem(arena,
&privKey->u.ec.ecParams.DEREncoding,
object,CKA_EC_PARAMS);
if (crv != CKR_OK) break;
/* Fill out the rest of the ecParams structure
* based on the encoded params
*/
if (EC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding,
&privKey->u.ec.ecParams) != SECSuccess) {
crv = CKR_DOMAIN_PARAMS_INVALID;
break;
}
crv = sftk_Attribute2SSecItem(arena,&privKey->u.ec.privateValue,
object,CKA_VALUE);
if (crv != CKR_OK) break;
if (sftk_hasAttribute(object,CKA_NETSCAPE_DB)) {
crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.publicValue,
object,CKA_NETSCAPE_DB);
if (crv != CKR_OK) break;
/* privKey was zero'd so public value is already set to NULL, 0
* if we don't set it explicitly */
}
rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version,
NSSLOWKEY_EC_PRIVATE_KEY_VERSION);
if (rv != SECSuccess) crv = CKR_HOST_MEMORY;
break;
#endif /* NSS_ENABLE_ECC */
default:
crv = CKR_KEY_TYPE_INCONSISTENT;
break;
}
*crvp = crv;
if (crv != CKR_OK) {
PORT_FreeArena(arena,PR_FALSE);
return NULL;
}
return privKey;
}
/* Generate a low private key structure from an object */
NSSLOWKEYPrivateKey *
sftk_GetPrivKey(SFTKObject *object,CK_KEY_TYPE key_type, CK_RV *crvp)
{
NSSLOWKEYPrivateKey *priv = NULL;
if (object->objclass != CKO_PRIVATE_KEY) {
*crvp = CKR_KEY_TYPE_INCONSISTENT;
return NULL;
}
if (object->objectInfo) {
*crvp = CKR_OK;
return (NSSLOWKEYPrivateKey *)object->objectInfo;
}
if (sftk_isToken(object->handle)) {
/* grab it from the data base */
SFTKTokenObject *to = sftk_narrowToTokenObject(object);
PORT_Assert(to);
priv = sftk_FindKeyByPublicKey(object->slot, &to->dbKey);
*crvp = (priv == NULL) ? CKR_DEVICE_ERROR : CKR_OK;
} else {
priv = sftk_mkPrivKey(object, key_type, crvp);
}
object->objectInfo = priv;
object->infoFree = (SFTKFree) nsslowkey_DestroyPrivateKey;
return priv;
}
/*
**************************** Symetric Key utils ************************
*/
/*
* set the DES key with parity bits correctly
*/
void
sftk_FormatDESKey(unsigned char *key, int length)
{
int i;
/* format the des key */
for (i=0; i < length; i++) {
key[i] = parityTable[key[i]>>1];
}
}
/*
* check a des key (des2 or des3 subkey) for weak keys.
*/
PRBool
sftk_CheckDESKey(unsigned char *key)
{
int i;
/* format the des key with parity */
sftk_FormatDESKey(key, 8);
for (i=0; i < sftk_desWeakTableSize; i++) {
if (PORT_Memcmp(key,sftk_desWeakTable[i],8) == 0) {
return PR_TRUE;
}
}
return PR_FALSE;
}
/*
* check if a des or triple des key is weak.
*/
PRBool
sftk_IsWeakKey(unsigned char *key,CK_KEY_TYPE key_type)
{
switch(key_type) {
case CKK_DES:
return sftk_CheckDESKey(key);
case CKM_DES2_KEY_GEN:
if (sftk_CheckDESKey(key)) return PR_TRUE;
return sftk_CheckDESKey(&key[8]);
case CKM_DES3_KEY_GEN:
if (sftk_CheckDESKey(key)) return PR_TRUE;
if (sftk_CheckDESKey(&key[8])) return PR_TRUE;
return sftk_CheckDESKey(&key[16]);
default:
break;
}
return PR_FALSE;
}
/* make a fake private key representing a symmetric key */
static NSSLOWKEYPrivateKey *
sftk_mkSecretKeyRep(SFTKObject *object)
{
NSSLOWKEYPrivateKey *privKey = 0;
PLArenaPool *arena = 0;
CK_KEY_TYPE keyType;
PRUint32 keyTypeStorage;
SECItem keyTypeItem;
CK_RV crv;
SECStatus rv;
static unsigned char derZero[1] = { 0 };
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (arena == NULL) { crv = CKR_HOST_MEMORY; goto loser; }
privKey = (NSSLOWKEYPrivateKey *)
PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey));
if (privKey == NULL) { crv = CKR_HOST_MEMORY; goto loser; }
privKey->arena = arena;
/* Secret keys are represented in the database as "fake" RSA keys. The RSA key
* is marked as a secret key representation by setting the public exponent field
* to 0, which is an invalid RSA exponent. The other fields are set as follows:
* modulus - CKA_ID value for the secret key
* private exponent - CKA_VALUE (the key itself)
* coefficient - CKA_KEY_TYPE, which indicates what encryption algorithm
* is used for the key.
* all others - set to integer 0
*/
privKey->keyType = NSSLOWKEYRSAKey;
/* The modulus is set to the key id of the symmetric key */
crv=sftk_Attribute2SecItem(arena,&privKey->u.rsa.modulus,object,CKA_ID);
if (crv != CKR_OK) goto loser;
/* The public exponent is set to 0 length to indicate a special key */
privKey->u.rsa.publicExponent.len = sizeof derZero;
privKey->u.rsa.publicExponent.data = derZero;
/* The private exponent is the actual key value */
crv=sftk_Attribute2SecItem(arena,&privKey->u.rsa.privateExponent,object,CKA_VALUE);
if (crv != CKR_OK) goto loser;
/* All other fields empty - needs testing */
privKey->u.rsa.prime1.len = sizeof derZero;
privKey->u.rsa.prime1.data = derZero;
privKey->u.rsa.prime2.len = sizeof derZero;
privKey->u.rsa.prime2.data = derZero;
privKey->u.rsa.exponent1.len = sizeof derZero;
privKey->u.rsa.exponent1.data = derZero;
privKey->u.rsa.exponent2.len = sizeof derZero;
privKey->u.rsa.exponent2.data = derZero;
/* Coeficient set to KEY_TYPE */
crv = sftk_GetULongAttribute(object, CKA_KEY_TYPE, &keyType);
if (crv != CKR_OK) goto loser;
/* on 64 bit platforms, we still want to store 32 bits of keyType (This is
* safe since the PKCS #11 defines for all types are 32 bits or less). */
keyTypeStorage = (PRUint32) keyType;
keyTypeStorage = PR_htonl(keyTypeStorage);
keyTypeItem.data = (unsigned char *)&keyTypeStorage;
keyTypeItem.len = sizeof (keyTypeStorage);
rv = SECITEM_CopyItem(arena, &privKey->u.rsa.coefficient, &keyTypeItem);
if (rv != SECSuccess) {
crv = CKR_HOST_MEMORY;
goto loser;
}
/* Private key version field set normally for compatibility */
rv = DER_SetUInteger(privKey->arena,
&privKey->u.rsa.version, NSSLOWKEY_VERSION);
if (rv != SECSuccess) { crv = CKR_HOST_MEMORY; goto loser; }
loser:
if (crv != CKR_OK) {
PORT_FreeArena(arena,PR_FALSE);
privKey = 0;
}
return privKey;
}
static PRBool
isSecretKey(NSSLOWKEYPrivateKey *privKey)
{
if (privKey->keyType == NSSLOWKEYRSAKey &&
privKey->u.rsa.publicExponent.len == 1 &&
privKey->u.rsa.publicExponent.data[0] == 0)
return PR_TRUE;
return PR_FALSE;
}
/**********************************************************************
*
* Start of PKCS 11 functions
*
**********************************************************************/
/* return the function list */
CK_RV NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList)
{
*pFunctionList = (CK_FUNCTION_LIST_PTR) &sftk_funcList;
return CKR_OK;
}
/* return the function list */
CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList)
{
return NSC_GetFunctionList(pFunctionList);
}
static PLHashNumber
sftk_HashNumber(const void *key)
{
return (PLHashNumber) key;
}
/*
* eventually I'd like to expunge all occurances of XXX_SLOT_ID and
* just go with the info in the slot. This is one place, however,
* where it might be a little difficult.
*/
const char *
sftk_getDefTokName(CK_SLOT_ID slotID)
{
static char buf[33];
switch (slotID) {
case NETSCAPE_SLOT_ID:
return "NSS Generic Crypto Services ";
case PRIVATE_KEY_SLOT_ID:
return "NSS Certificate DB ";
case FIPS_SLOT_ID:
return "NSS FIPS 140-2 Certificate DB ";
default:
break;
}
sprintf(buf,"NSS Application Token %08x ",(unsigned int) slotID);
return buf;
}
const char *
sftk_getDefSlotName(CK_SLOT_ID slotID)
{
static char buf[65];
switch (slotID) {
case NETSCAPE_SLOT_ID:
return
"NSS Internal Cryptographic Services ";
case PRIVATE_KEY_SLOT_ID:
return
"NSS User Private Key and Certificate Services ";
case FIPS_SLOT_ID:
return
"NSS FIPS 140-2 User Private Key Services ";
default:
break;
}
sprintf(buf,
"NSS Application Slot %08x ",
(unsigned int) slotID);
return buf;
}
static CK_ULONG nscSlotCount[2] = {0 , 0};
static CK_SLOT_ID_PTR nscSlotList[2] = {NULL, NULL};
static CK_ULONG nscSlotListSize[2] = {0, 0};
static PLHashTable *nscSlotHashTable[2] = {NULL, NULL};
static int
sftk_GetModuleIndex(CK_SLOT_ID slotID)
{
if ((slotID == FIPS_SLOT_ID) || (slotID >= SFTK_MIN_FIPS_USER_SLOT_ID)) {
return NSC_FIPS_MODULE;
}
return NSC_NON_FIPS_MODULE;
}
/* look up a slot structure from the ID (used to be a macro when we only
* had two slots) */
/* if all is true, return the slot even if it has been 'unloaded' */
/* if all is false, only return the slots which are present */
SFTKSlot *
sftk_SlotFromID(CK_SLOT_ID slotID, PRBool all)
{
SFTKSlot *slot;
int index = sftk_GetModuleIndex(slotID);
if (nscSlotHashTable[index] == NULL) return NULL;
slot = (SFTKSlot *)PL_HashTableLookupConst(nscSlotHashTable[index],
(void *)slotID);
/* cleared slots shouldn't 'show up' */
if (slot && !all && !slot->present) slot = NULL;
return slot;
}
SFTKSlot *
sftk_SlotFromSessionHandle(CK_SESSION_HANDLE handle)
{
CK_ULONG slotIDIndex = (handle >> 24) & 0x7f;
CK_ULONG moduleIndex = (handle >> 31) & 1;
if (slotIDIndex >= nscSlotCount[moduleIndex]) {
return NULL;
}
return sftk_SlotFromID(nscSlotList[moduleIndex][slotIDIndex], PR_FALSE);
}
static CK_RV
sftk_RegisterSlot(SFTKSlot *slot, int moduleIndex)
{
PLHashEntry *entry;
int index;
index = sftk_GetModuleIndex(slot->slotID);
/* make sure the slotID for this module is valid */
if (moduleIndex != index) {
return CKR_SLOT_ID_INVALID;
}
if (nscSlotList[index] == NULL) {
nscSlotListSize[index] = NSC_SLOT_LIST_BLOCK_SIZE;
nscSlotList[index] = (CK_SLOT_ID *)
PORT_ZAlloc(nscSlotListSize[index]*sizeof(CK_SLOT_ID));
if (nscSlotList[index] == NULL) {
return CKR_HOST_MEMORY;
}
}
if (nscSlotCount[index] >= nscSlotListSize[index]) {
CK_SLOT_ID* oldNscSlotList = nscSlotList[index];
CK_ULONG oldNscSlotListSize = nscSlotListSize[index];
nscSlotListSize[index] += NSC_SLOT_LIST_BLOCK_SIZE;
nscSlotList[index] = (CK_SLOT_ID *) PORT_Realloc(oldNscSlotList,
nscSlotListSize[index]*sizeof(CK_SLOT_ID));
if (nscSlotList[index] == NULL) {
nscSlotList[index] = oldNscSlotList;
nscSlotListSize[index] = oldNscSlotListSize;
return CKR_HOST_MEMORY;
}
}
if (nscSlotHashTable[index] == NULL) {
nscSlotHashTable[index] = PL_NewHashTable(64,sftk_HashNumber,
PL_CompareValues, PL_CompareValues, NULL, 0);
if (nscSlotHashTable[index] == NULL) {
return CKR_HOST_MEMORY;
}
}
entry = PL_HashTableAdd(nscSlotHashTable[index],(void *)slot->slotID,slot);
if (entry == NULL) {
return CKR_HOST_MEMORY;
}
slot->index = (nscSlotCount[index] & 0x7f) | ((index << 7) & 0x80);
nscSlotList[index][nscSlotCount[index]++] = slot->slotID;
return CKR_OK;
}
typedef struct sftk_DBsStr {
NSSLOWCERTCertDBHandle *certHandle;
NSSLOWKEYDBHandle *keyHandle;
} sftkDBs;
static SECStatus
sftk_set_user(NSSLOWCERTCertificate *cert, SECItem *dummy, void *arg)
{
sftkDBs *param = (sftkDBs *)arg;
NSSLOWCERTCertTrust trust = *cert->trust;
if (param->keyHandle &&
nsslowkey_KeyForCertExists(param->keyHandle,cert)) {
trust.sslFlags |= CERTDB_USER;
trust.emailFlags |= CERTDB_USER;
trust.objectSigningFlags |= CERTDB_USER;
} else {
trust.sslFlags &= ~CERTDB_USER;
trust.emailFlags &= ~CERTDB_USER;
trust.objectSigningFlags &= ~CERTDB_USER;
}
if (PORT_Memcmp(&trust,cert->trust, sizeof (trust)) != 0) {
nsslowcert_ChangeCertTrust(param->certHandle, cert, &trust);
}
/* should check for email address and make sure we have an s/mime profile */
return SECSuccess;
}
/*
* this function fixes up old databases that may not have the CERTDB_USER
* flags set correctly. it expects the owner already has references to
* the cert and key handles.
*/
static void
sftk_DBVerify(NSSLOWCERTCertDBHandle *certHandle, NSSLOWKEYDBHandle *keyHandle)
{
/* walk through all the certs and check to see if there are any
* user certs, and make sure there are s/mime profiles for all certs with
* email addresses */
sftkDBs param;
param.certHandle = certHandle;
param.keyHandle = keyHandle;
nsslowcert_TraversePermCerts(certHandle, sftk_set_user, ¶m);
return;
}
/*
* ths function has all the common initialization that happens whenever we
* create a new slot or repurpose an old slot (only valid for slotID's 4
* and greater).
*
* things that are not reinitialized are:
* slotID (can't change)
* slotDescription (can't change once defined)
* the locks and hash tables (difficult to change in running code, and
* unnecessary. hash tables and list are cleared on shutdown, but they
* are cleared in a 'friendly' way).
* session and object ID counters -- so any old sessions and objects in the
* application will get properly notified that the world has changed.
*
* things that are reinitialized:
* database (otherwise what would the point be;).
* state variables related to databases.
* session count stat info.
* tokenDescription.
*
* NOTE: slotID's 4 and greater show up as removable devices.
*
*/
CK_RV
SFTK_SlotReInit(SFTKSlot *slot,
char *configdir,sftk_token_parameters *params, int moduleIndex)
{
PRBool needLogin = !params->noKeyDB;
CK_RV crv;
slot->hasTokens = PR_FALSE;
slot->sessionIDConflict = 0;
slot->sessionCount = 0;
slot->rwSessionCount = 0;
slot->needLogin = PR_FALSE;
slot->isLoggedIn = PR_FALSE;
slot->ssoLoggedIn = PR_FALSE;
slot->DB_loaded = PR_FALSE;
slot->certDB = NULL;
slot->keyDB = NULL;
slot->minimumPinLen = 0;
slot->readOnly = params->readOnly;
sftk_setStringName(params->tokdes ? params->tokdes :
sftk_getDefTokName(slot->slotID), slot->tokDescription,
sizeof(slot->tokDescription));
if ((!params->noCertDB) || (!params->noKeyDB)) {
NSSLOWCERTCertDBHandle * certHandle = NULL;
NSSLOWKEYDBHandle *keyHandle = NULL;
crv = sftk_DBInit(params->configdir ? params->configdir : configdir,
params->certPrefix, params->keyPrefix, params->readOnly,
params->noCertDB, params->noKeyDB, params->forceOpen,
&certHandle, &keyHandle);
if (crv != CKR_OK) {
goto loser;
}
if (nsslowcert_needDBVerify(certHandle)) {
sftk_DBVerify(certHandle, keyHandle);
}
slot->certDB = certHandle;
slot->keyDB = keyHandle;
}
if (needLogin) {
/* if the data base is initialized with a null password,remember that */
slot->needLogin =
(PRBool)!sftk_hasNullPassword(slot->keyDB,&slot->password);
if ((params->minPW >= 0) && (params->minPW <= SFTK_MAX_PIN)) {
slot->minimumPinLen = params->minPW;
}
if ((slot->minimumPinLen == 0) && (params->pwRequired)) {
slot->minimumPinLen = 1;
}
if ((moduleIndex == NSC_FIPS_MODULE) &&
(slot->minimumPinLen < FIPS_MIN_PIN)) {
slot->minimumPinLen = FIPS_MIN_PIN;
}
}
slot->present = PR_TRUE;
return CKR_OK;
loser:
SFTK_ShutdownSlot(slot);
return crv;
}
/*
* initialize one of the slot structures. figure out which by the ID
*/
CK_RV
SFTK_SlotInit(char *configdir,sftk_token_parameters *params, int moduleIndex)
{
unsigned int i;
CK_SLOT_ID slotID = params->slotID;
SFTKSlot *slot;
CK_RV crv = CKR_HOST_MEMORY;
/*
* first we initialize everything that is 'permanent' with this slot.
* that is everything we aren't going to shutdown if we close this slot
* and open it up again with different databases */
slot = PORT_ZNew(SFTKSlot);
if (slot == NULL) {
return CKR_HOST_MEMORY;
}
slot->optimizeSpace = params->optimizeSpace;
if (slot->optimizeSpace) {
slot->sessObjHashSize = SPACE_SESSION_OBJECT_HASH_SIZE;
slot->sessHashSize = SPACE_SESSION_HASH_SIZE;
slot->numSessionLocks = 1;
} else {
slot->sessObjHashSize = TIME_SESSION_OBJECT_HASH_SIZE;
slot->sessHashSize = TIME_SESSION_HASH_SIZE;
slot->numSessionLocks = slot->sessHashSize/BUCKETS_PER_SESSION_LOCK;
}
slot->sessionLockMask = slot->numSessionLocks-1;
slot->slotLock = PZ_NewLock(nssILockSession);
if (slot->slotLock == NULL)
goto mem_loser;
slot->sessionLock = PORT_ZNewArray(PZLock *, slot->numSessionLocks);
if (slot->sessionLock == NULL)
goto mem_loser;
for (i=0; i < slot->numSessionLocks; i++) {
slot->sessionLock[i] = PZ_NewLock(nssILockSession);
if (slot->sessionLock[i] == NULL)
goto mem_loser;
}
slot->objectLock = PZ_NewLock(nssILockObject);
if (slot->objectLock == NULL)
goto mem_loser;
slot->pwCheckLock = PR_NewLock();
if (slot->pwCheckLock == NULL)
goto mem_loser;
slot->head = PORT_ZNewArray(SFTKSession *, slot->sessHashSize);
if (slot->head == NULL)
goto mem_loser;
slot->sessObjHashTable = PORT_ZNewArray(SFTKObject *, slot->sessObjHashSize);
if (slot->sessObjHashTable == NULL)
goto mem_loser;
slot->tokObjHashTable = PL_NewHashTable(64,sftk_HashNumber,PL_CompareValues,
SECITEM_HashCompare, NULL, 0);
if (slot->tokObjHashTable == NULL)
goto mem_loser;
slot->sessionIDCount = 0;
slot->sessionObjectHandleCount = minSessionObjectHandle;
slot->slotID = slotID;
sftk_setStringName(params->slotdes ? params->slotdes :
sftk_getDefSlotName(slotID), slot->slotDescription,
sizeof(slot->slotDescription));
/* call the reinit code to set everything that changes between token
* init calls */
crv = SFTK_SlotReInit(slot, configdir, params, moduleIndex);
if (crv != CKR_OK) {
goto loser;
}
crv = sftk_RegisterSlot(slot, moduleIndex);
if (crv != CKR_OK) {
goto loser;
}
return CKR_OK;
mem_loser:
crv = CKR_HOST_MEMORY;
loser:
SFTK_DestroySlotData(slot);
return crv;
}
static CK_RV sft_CloseAllSession(SFTKSlot *slot)
{
SECItem *pw = NULL;
SFTKSession *session;
unsigned int i;
/* first log out the card */
PZ_Lock(slot->slotLock);
pw = slot->password;
slot->isLoggedIn = PR_FALSE;
slot->password = NULL;
PZ_Unlock(slot->slotLock);
if (pw) SECITEM_ZfreeItem(pw, PR_TRUE);
/* now close all the current sessions */
/* NOTE: If you try to open new sessions before NSC_CloseAllSessions
* completes, some of those new sessions may or may not be closed by
* NSC_CloseAllSessions... but any session running when this code starts
* will guarrenteed be close, and no session will be partially closed */
for (i=0; i < slot->sessHashSize; i++) {
PZLock *lock = SFTK_SESSION_LOCK(slot,i);
do {
PZ_Lock(lock);
session = slot->head[i];
/* hand deque */
/* this duplicates function of NSC_close session functions, but
* because we know that we are freeing all the sessions, we can
* do more efficient processing */
if (session) {
slot->head[i] = session->next;
if (session->next) session->next->prev = NULL;
session->next = session->prev = NULL;
PZ_Unlock(lock);
PZ_Lock(slot->slotLock);
--slot->sessionCount;
PZ_Unlock(slot->slotLock);
if (session->info.flags & CKF_RW_SESSION) {
PR_AtomicDecrement(&slot->rwSessionCount);
}
} else {
PZ_Unlock(lock);
}
if (session) sftk_FreeSession(session);
} while (session != NULL);
}
return CKR_OK;
}
/*
* shut down the databases.
* we get the slot lock (which also protects slot->certDB and slot->keyDB)
* and clear the values so the new users will not find the databases.
* once things are clear, we can release our references to the databases.
* The databases will close when the last reference is released.
*
* We use reference counts so that we don't crash if someone shuts down
* a token that another thread is actively using.
*/
static void
sftk_DBShutdown(SFTKSlot *slot)
{
NSSLOWCERTCertDBHandle *certHandle;
NSSLOWKEYDBHandle *keyHandle;
PZ_Lock(slot->slotLock);
certHandle = slot->certDB;
slot->certDB = NULL;
keyHandle = slot->keyDB;
slot->keyDB = NULL;
PZ_Unlock(slot->slotLock);
if (certHandle) {
PORT_Assert(certHandle->ref == 1 || slot->slotID > FIPS_SLOT_ID);
sftk_freeCertDB(certHandle);
}
if (keyHandle) {
PORT_Assert(keyHandle->ref == 1 || slot->slotID > FIPS_SLOT_ID);
sftk_freeKeyDB(keyHandle);
}
}
CK_RV
SFTK_ShutdownSlot(SFTKSlot *slot)
{
/* make sure no new PK11 calls work except C_GetSlotInfo */
slot->present = PR_FALSE;
/* close all outstanding sessions
* the sessHashSize variable guarentees we have all the session
* mechanism set up */
if (slot->head) {
sft_CloseAllSession(slot);
}
/* clear all objects.. session objects are cleared as a result of
* closing all the sessions. We just need to clear the token object
* cache. slot->tokObjHashTable guarentees we have the token
* infrastructure set up. */
if (slot->tokObjHashTable) {
SFTK_ClearTokenKeyHashTable(slot);
}
/* clear the slot description for the next guy */
PORT_Memset(slot->tokDescription, 0, sizeof(slot->tokDescription));
/* now shut down the databases. */
sftk_DBShutdown(slot);
return CKR_OK;
}
/*
* initialize one of the slot structures. figure out which by the ID
*/
CK_RV
SFTK_DestroySlotData(SFTKSlot *slot)
{
unsigned int i;
SFTK_ShutdownSlot(slot);
if (slot->tokObjHashTable) {
PL_HashTableDestroy(slot->tokObjHashTable);
slot->tokObjHashTable = NULL;
}
if (slot->sessObjHashTable) {
PORT_Free(slot->sessObjHashTable);
slot->sessObjHashTable = NULL;
}
slot->sessObjHashSize = 0;
if (slot->head) {
PORT_Free(slot->head);
slot->head = NULL;
}
slot->sessHashSize = 0;
/* OK everything has been disassembled, now we can finally get rid
* of the locks */
if (slot->slotLock) {
PZ_DestroyLock(slot->slotLock);
slot->slotLock = NULL;
}
if (slot->sessionLock) {
for (i=0; i < slot->numSessionLocks; i++) {
if (slot->sessionLock[i]) {
PZ_DestroyLock(slot->sessionLock[i]);
slot->sessionLock[i] = NULL;
}
}
PORT_Free(slot->sessionLock);
slot->sessionLock = NULL;
}
if (slot->objectLock) {
PZ_DestroyLock(slot->objectLock);
slot->objectLock = NULL;
}
if (slot->pwCheckLock) {
PR_DestroyLock(slot->pwCheckLock);
slot->pwCheckLock = NULL;
}
PORT_Free(slot);
return CKR_OK;
}
/*
* handle the SECMOD.db
*/
char **
NSC_ModuleDBFunc(unsigned long function,char *parameters, void *args)
{
char *secmod = NULL;
char *appName = NULL;
char *filename = NULL;
PRBool rw;
static char *success="Success";
char **rvstr = NULL;
secmod = secmod_getSecmodName(parameters,&appName,&filename, &rw);
switch (function) {
case SECMOD_MODULE_DB_FUNCTION_FIND:
rvstr = secmod_ReadPermDB(appName,filename,secmod,(char *)parameters,rw);
break;
case SECMOD_MODULE_DB_FUNCTION_ADD:
rvstr = (secmod_AddPermDB(appName,filename,secmod,(char *)args,rw)
== SECSuccess) ? &success: NULL;
break;
case SECMOD_MODULE_DB_FUNCTION_DEL:
rvstr = (secmod_DeletePermDB(appName,filename,secmod,(char *)args,rw)
== SECSuccess) ? &success: NULL;
break;
case SECMOD_MODULE_DB_FUNCTION_RELEASE:
rvstr = (secmod_ReleasePermDBData(appName,filename,secmod,
(char **)args,rw) == SECSuccess) ? &success: NULL;
break;
}
if (secmod) PR_smprintf_free(secmod);
if (appName) PORT_Free(appName);
if (filename) PORT_Free(filename);
return rvstr;
}
static void nscFreeAllSlots(int moduleIndex)
{
/* free all the slots */
SFTKSlot *slot = NULL;
CK_SLOT_ID slotID;
int i;
if (nscSlotList[moduleIndex]) {
CK_ULONG tmpSlotCount = nscSlotCount[moduleIndex];
CK_SLOT_ID_PTR tmpSlotList = nscSlotList[moduleIndex];
PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex];
/* first close all the session */
for (i=0; i < (int) tmpSlotCount; i++) {
slotID = tmpSlotList[i];
(void) NSC_CloseAllSessions(slotID);
}
/* now clear out the statics */
nscSlotList[moduleIndex] = NULL;
nscSlotCount[moduleIndex] = 0;
nscSlotHashTable[moduleIndex] = NULL;
nscSlotListSize[moduleIndex] = 0;
for (i=0; i < (int) tmpSlotCount; i++) {
slotID = tmpSlotList[i];
slot = (SFTKSlot *)
PL_HashTableLookup(tmpSlotHashTable, (void *)slotID);
PORT_Assert(slot);
if (!slot) continue;
SFTK_DestroySlotData(slot);
PL_HashTableRemove(tmpSlotHashTable, (void *)slotID);
}
PORT_Free(tmpSlotList);
PL_HashTableDestroy(tmpSlotHashTable);
}
}
static void
sftk_closePeer(PRBool isFIPS)
{
CK_SLOT_ID slotID = isFIPS ? PRIVATE_KEY_SLOT_ID: FIPS_SLOT_ID;
SFTKSlot *slot;
int moduleIndex = isFIPS? NSC_NON_FIPS_MODULE : NSC_FIPS_MODULE;
PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex];
slot = (SFTKSlot *) PL_HashTableLookup(tmpSlotHashTable, (void *)slotID);
if (slot == NULL) {
return;
}
sftk_DBShutdown(slot);
return;
}
static PRBool nsc_init = PR_FALSE;
extern SECStatus secoid_Init(void);
/* NSC_Initialize initializes the Cryptoki library. */
CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS)
{
CK_RV crv = CKR_OK;
SECStatus rv;
CK_C_INITIALIZE_ARGS *init_args = (CK_C_INITIALIZE_ARGS *) pReserved;
int i;
int moduleIndex = isFIPS? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE;
if (isFIPS) {
loginWaitTime = PR_SecondsToInterval(1);
}
rv = secoid_Init();
if (rv != SECSuccess) {
crv = CKR_DEVICE_ERROR;
return crv;
}
rv = RNG_RNGInit(); /* initialize random number generator */
if (rv != SECSuccess) {
crv = CKR_DEVICE_ERROR;
return crv;
}
RNG_SystemInfoForRNG();
rv = nsslowcert_InitLocks();
if (rv != SECSuccess) {
crv = CKR_DEVICE_ERROR;
return crv;
}
/* NOTE:
* we should be getting out mutexes from this list, not statically binding
* them from NSPR. This should happen before we allow the internal to split
* off from the rest on NSS.
*/
/* initialize the key and cert db's */
nsslowkey_SetDefaultKeyDBAlg
(SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC);
if (init_args && (!(init_args->flags & CKF_OS_LOCKING_OK))) {
if (init_args->CreateMutex && init_args->DestroyMutex &&
init_args->LockMutex && init_args->UnlockMutex) {
/* softoken always uses NSPR (ie. OS locking), and doesn't know how
* to use the lock functions provided by the application.
*/
crv = CKR_CANT_LOCK;
return crv;
}
if (init_args->CreateMutex || init_args->DestroyMutex ||
init_args->LockMutex || init_args->UnlockMutex) {
/* only some of the lock functions were provided by the
* application. This is invalid per PKCS#11 spec.
*/
crv = CKR_ARGUMENTS_BAD;
return crv;
}
}
crv = CKR_ARGUMENTS_BAD;
if ((init_args && init_args->LibraryParameters)) {
sftk_parameters paramStrings;
crv = secmod_parseParameters
((char *)init_args->LibraryParameters, ¶mStrings, isFIPS);
if (crv != CKR_OK) {
return crv;
}
crv = sftk_configure(paramStrings.man, paramStrings.libdes);
if (crv != CKR_OK) {
goto loser;
}
/* if we have a peer already open, have him close his DB's so we
* don't clobber each other. */
if ((isFIPS && nsc_init) || (!isFIPS && nsf_init)) {
sftk_closePeer(isFIPS);
if (sftk_audit_enabled) {
if (isFIPS && nsc_init) {
sftk_LogAuditMessage(NSS_AUDIT_INFO, "enabled FIPS mode");
} else {
sftk_LogAuditMessage(NSS_AUDIT_INFO, "disabled FIPS mode");
}
}
}
for (i=0; i < paramStrings.token_count; i++) {
crv = SFTK_SlotInit(paramStrings.configdir,
¶mStrings.tokens[i],
moduleIndex);
if (crv != CKR_OK) {
nscFreeAllSlots(moduleIndex);
break;
}
}
loser:
secmod_freeParams(¶mStrings);
}
if (CKR_OK == crv) {
sftk_InitFreeLists();
}
return crv;
}
CK_RV NSC_Initialize(CK_VOID_PTR pReserved)
{
CK_RV crv;
if (nsc_init) {
return CKR_CRYPTOKI_ALREADY_INITIALIZED;
}
crv = nsc_CommonInitialize(pReserved,PR_FALSE);
nsc_init = (PRBool) (crv == CKR_OK);
return crv;
}
extern SECStatus SECOID_Shutdown(void);
/* NSC_Finalize indicates that an application is done with the
* Cryptoki library.*/
CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS)
{
nscFreeAllSlots(isFIPS ? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE);
/* don't muck with the globals is our peer is still initialized */
if (isFIPS && nsc_init) {
return CKR_OK;
}
if (!isFIPS && nsf_init) {
return CKR_OK;
}
sftk_CleanupFreeLists();
nsslowcert_DestroyFreeLists();
nsslowcert_DestroyGlobalLocks();
/* This function does not discard all our previously aquired entropy. */
RNG_RNGShutdown();
/* tell freeBL to clean up after itself */
BL_Cleanup();
/* unload freeBL shared library from memory */
BL_Unload();
/* clean up the default OID table */
SECOID_Shutdown();
nsc_init = PR_FALSE;
return CKR_OK;
}
/* NSC_Finalize indicates that an application is done with the
* Cryptoki library.*/
CK_RV NSC_Finalize (CK_VOID_PTR pReserved)
{
CK_RV crv;
if (!nsc_init) {
return CKR_OK;
}
crv = nsc_CommonFinalize (pReserved, PR_FALSE);
nsc_init = (PRBool) !(crv == CKR_OK);
return crv;
}
extern const char __nss_softokn_rcsid[];
extern const char __nss_softokn_sccsid[];
/* NSC_GetInfo returns general information about Cryptoki. */
CK_RV NSC_GetInfo(CK_INFO_PTR pInfo)
{
volatile char c; /* force a reference that won't get optimized away */
c = __nss_softokn_rcsid[0] + __nss_softokn_sccsid[0];
pInfo->cryptokiVersion.major = 2;
pInfo->cryptokiVersion.minor = 20;
PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32);
pInfo->libraryVersion.major = SOFTOKEN_VMAJOR;
pInfo->libraryVersion.minor = SOFTOKEN_VMINOR;
PORT_Memcpy(pInfo->libraryDescription,libraryDescription,32);
pInfo->flags = 0;
return CKR_OK;
}
/* NSC_GetSlotList obtains a list of slots in the system. */
CK_RV nsc_CommonGetSlotList(CK_BBOOL tokenPresent,
CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex)
{
*pulCount = nscSlotCount[moduleIndex];
if (pSlotList != NULL) {
PORT_Memcpy(pSlotList,nscSlotList[moduleIndex],
nscSlotCount[moduleIndex]*sizeof(CK_SLOT_ID));
}
return CKR_OK;
}
/* NSC_GetSlotList obtains a list of slots in the system. */
CK_RV NSC_GetSlotList(CK_BBOOL tokenPresent,
CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount)
{
return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount,
NSC_NON_FIPS_MODULE);
}
/* NSC_GetSlotInfo obtains information about a particular slot in the system. */
CK_RV NSC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo)
{
SFTKSlot *slot = sftk_SlotFromID(slotID, PR_TRUE);
if (slot == NULL) return CKR_SLOT_ID_INVALID;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 0;
PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32);
PORT_Memcpy(pInfo->slotDescription,slot->slotDescription,64);
pInfo->flags = (slot->present) ? CKF_TOKEN_PRESENT : 0;
/* all user defined slots are defined as removable */
if (slotID >= SFTK_MIN_USER_SLOT_ID) {
pInfo->flags |= CKF_REMOVABLE_DEVICE;
}
/* ok we really should read it out of the keydb file. */
/* pInfo->hardwareVersion.major = NSSLOWKEY_DB_FILE_VERSION; */
pInfo->hardwareVersion.major = SOFTOKEN_VMAJOR;
pInfo->hardwareVersion.minor = SOFTOKEN_VMINOR;
return CKR_OK;
}
/*
* check the current state of the 'needLogin' flag in case the database has
* been changed underneath us.
*/
static PRBool
sftk_checkNeedLogin(SFTKSlot *slot, NSSLOWKEYDBHandle *keyHandle)
{
if (slot->password) {
SECStatus rv;
rv = nsslowkey_CheckKeyDBPassword(keyHandle,slot->password);
if ( rv == SECSuccess) {
return slot->needLogin;
} else {
SECITEM_FreeItem(slot->password, PR_TRUE);
slot->password = NULL;
slot->isLoggedIn = PR_FALSE;
}
}
slot->needLogin =
(PRBool)!sftk_hasNullPassword(keyHandle,&slot->password);
return (slot->needLogin);
}
/* NSC_GetTokenInfo obtains information about a particular token in
* the system. */
CK_RV NSC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo)
{
SFTKSlot *slot;
NSSLOWKEYDBHandle *handle;
if (!nsc_init && !nsf_init) return CKR_CRYPTOKI_NOT_INITIALIZED;
slot = sftk_SlotFromID(slotID, PR_FALSE);
if (slot == NULL) return CKR_SLOT_ID_INVALID;
PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32);
PORT_Memcpy(pInfo->model,"NSS 3 ",16);
PORT_Memcpy(pInfo->serialNumber,"0000000000000000",16);
PORT_Memcpy(pInfo->utcTime,"0000000000000000",16);
pInfo->ulMaxSessionCount = 0; /* arbitrarily large */
pInfo->ulSessionCount = slot->sessionCount;
pInfo->ulMaxRwSessionCount = 0; /* arbitarily large */
pInfo->ulRwSessionCount = slot->rwSessionCount;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 0;
PORT_Memcpy(pInfo->label,slot->tokDescription,32);
handle = sftk_getKeyDB(slot);
pInfo->flags = CKF_RNG | CKF_DUAL_CRYPTO_OPERATIONS;
if (handle == NULL) {
pInfo->flags |= CKF_WRITE_PROTECTED;
pInfo->ulMaxPinLen = 0;
pInfo->ulMinPinLen = 0;
pInfo->ulTotalPublicMemory = 0;
pInfo->ulFreePublicMemory = 0;
pInfo->ulTotalPrivateMemory = 0;
pInfo->ulFreePrivateMemory = 0;
pInfo->hardwareVersion.major = 4;
pInfo->hardwareVersion.minor = 0;
} else {
/*
* we have three possible states which we may be in:
* (1) No DB password has been initialized. This also means we
* have no keys in the key db.
* (2) Password initialized to NULL. This means we have keys, but
* the user has chosen not use a password.
* (3) Finally we have an initialized password whicn is not NULL, and
* we will need to prompt for it.
*/
if (nsslowkey_HasKeyDBPassword(handle) == SECFailure) {
pInfo->flags |= CKF_LOGIN_REQUIRED;
} else if (!sftk_checkNeedLogin(slot,handle)) {
pInfo->flags |= CKF_USER_PIN_INITIALIZED;
} else {
pInfo->flags |= CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED;
}
pInfo->ulMaxPinLen = SFTK_MAX_PIN;
pInfo->ulMinPinLen = (CK_ULONG)slot->minimumPinLen;
pInfo->ulTotalPublicMemory = 1;
pInfo->ulFreePublicMemory = 1;
pInfo->ulTotalPrivateMemory = 1;
pInfo->ulFreePrivateMemory = 1;
pInfo->hardwareVersion.major = CERT_DB_FILE_VERSION;
pInfo->hardwareVersion.minor = handle->version;
sftk_freeKeyDB(handle);
}
/*
* CKF_LOGIN_REQUIRED CKF_USER_PIN_INITIALIZED how CKF_TOKEN_INITIALIZED
* should be set
* 0 0 1
* 1 0 0
* 0 1 1
* 1 1 1
*/
if (!(pInfo->flags & CKF_LOGIN_REQUIRED) ||
(pInfo->flags & CKF_USER_PIN_INITIALIZED)) {
pInfo->flags |= CKF_TOKEN_INITIALIZED;
}
return CKR_OK;
}
/* NSC_GetMechanismList obtains a list of mechanism types
* supported by a token. */
CK_RV NSC_GetMechanismList(CK_SLOT_ID slotID,
CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount)
{
CK_ULONG i;
switch (slotID) {
/* default: */
case NETSCAPE_SLOT_ID:
*pulCount = mechanismCount;
if (pMechanismList != NULL) {
for (i=0; i < mechanismCount; i++) {
pMechanismList[i] = mechanisms[i].type;
}
}
break;
default:
*pulCount = 0;
for (i=0; i < mechanismCount; i++) {
if (mechanisms[i].privkey) {
(*pulCount)++;
if (pMechanismList != NULL) {
*pMechanismList++ = mechanisms[i].type;
}
}
}
break;
}
return CKR_OK;
}
/* NSC_GetMechanismInfo obtains information about a particular mechanism
* possibly supported by a token. */
CK_RV NSC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
CK_MECHANISM_INFO_PTR pInfo)
{
PRBool isPrivateKey;
CK_ULONG i;
switch (slotID) {
case NETSCAPE_SLOT_ID:
isPrivateKey = PR_FALSE;
break;
default:
isPrivateKey = PR_TRUE;
break;
}
for (i=0; i < mechanismCount; i++) {
if (type == mechanisms[i].type) {
if (isPrivateKey && !mechanisms[i].privkey) {
return CKR_MECHANISM_INVALID;
}
PORT_Memcpy(pInfo,&mechanisms[i].info, sizeof(CK_MECHANISM_INFO));
return CKR_OK;
}
}
return CKR_MECHANISM_INVALID;
}
CK_RV sftk_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op)
{
CK_ULONG i;
CK_FLAGS flags;
switch (op) {
case CKA_ENCRYPT: flags = CKF_ENCRYPT; break;
case CKA_DECRYPT: flags = CKF_DECRYPT; break;
case CKA_WRAP: flags = CKF_WRAP; break;
case CKA_UNWRAP: flags = CKF_UNWRAP; break;
case CKA_SIGN: flags = CKF_SIGN; break;
case CKA_SIGN_RECOVER: flags = CKF_SIGN_RECOVER; break;
case CKA_VERIFY: flags = CKF_VERIFY; break;
case CKA_VERIFY_RECOVER: flags = CKF_VERIFY_RECOVER; break;
case CKA_DERIVE: flags = CKF_DERIVE; break;
default:
return CKR_ARGUMENTS_BAD;
}
for (i=0; i < mechanismCount; i++) {
if (type == mechanisms[i].type) {
return (flags & mechanisms[i].info.flags) ? CKR_OK
: CKR_MECHANISM_INVALID;
}
}
return CKR_MECHANISM_INVALID;
}
static SECStatus
sftk_TurnOffUser(NSSLOWCERTCertificate *cert, SECItem *k, void *arg)
{
NSSLOWCERTCertTrust trust;
SECStatus rv;
rv = nsslowcert_GetCertTrust(cert,&trust);
if (rv == SECSuccess && ((trust.emailFlags & CERTDB_USER) ||
(trust.sslFlags & CERTDB_USER) ||
(trust.objectSigningFlags & CERTDB_USER))) {
trust.emailFlags &= ~CERTDB_USER;
trust.sslFlags &= ~CERTDB_USER;
trust.objectSigningFlags &= ~CERTDB_USER;
nsslowcert_ChangeCertTrust(cert->dbhandle,cert,&trust);
}
return SECSuccess;
}
/* NSC_InitToken initializes a token. */
CK_RV NSC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin,
CK_ULONG ulPinLen,CK_CHAR_PTR pLabel) {
SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE);
NSSLOWKEYDBHandle *handle;
NSSLOWCERTCertDBHandle *certHandle;
SECStatus rv;
unsigned int i;
SFTKObject *object;
if (slot == NULL) return CKR_SLOT_ID_INVALID;
/* don't initialize the database if we aren't talking to a token
* that uses the key database.
*/
if (slotID == NETSCAPE_SLOT_ID) {
return CKR_TOKEN_WRITE_PROTECTED;
}
/* first, delete all our loaded key and cert objects from our
* internal list. */
PZ_Lock(slot->objectLock);
for (i=0; i < slot->sessObjHashSize; i++) {
do {
object = slot->sessObjHashTable[i];
/* hand deque */
/* this duplicates function of NSC_close session functions, but
* because we know that we are freeing all the sessions, we can
* do more efficient processing */
if (object) {
slot->sessObjHashTable[i] = object->next;
if (object->next) object->next->prev = NULL;
object->next = object->prev = NULL;
}
if (object) sftk_FreeObject(object);
} while (object != NULL);
}
slot->DB_loaded = PR_FALSE;
PZ_Unlock(slot->objectLock);
/* then clear out the key database */
handle = sftk_getKeyDB(slot);
if (handle == NULL) {
return CKR_TOKEN_WRITE_PROTECTED;
}
rv = nsslowkey_ResetKeyDB(handle);
sftk_freeKeyDB(handle);
if (rv != SECSuccess) {
return CKR_DEVICE_ERROR;
}
/* finally mark all the user certs as non-user certs */
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) return CKR_OK;
nsslowcert_TraversePermCerts(certHandle,sftk_TurnOffUser, NULL);
sftk_freeCertDB(certHandle);
return CKR_OK; /*is this the right function for not implemented*/
}
/* NSC_InitPIN initializes the normal user's PIN. */
CK_RV NSC_InitPIN(CK_SESSION_HANDLE hSession,
CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
{
SFTKSession *sp = NULL;
SFTKSlot *slot;
NSSLOWKEYDBHandle *handle = NULL;
SECItem *newPin;
char newPinStr[SFTK_MAX_PIN+1];
SECStatus rv;
CK_RV crv = CKR_SESSION_HANDLE_INVALID;
sp = sftk_SessionFromHandle(hSession);
if (sp == NULL) {
goto loser;
}
slot = sftk_SlotFromSession(sp);
if (slot == NULL) {
goto loser;
}
handle = sftk_getKeyDB(slot);
if (handle == NULL) {
crv = CKR_PIN_LEN_RANGE;
goto loser;
}
if (sp->info.state != CKS_RW_SO_FUNCTIONS) {
crv = CKR_USER_NOT_LOGGED_IN;
goto loser;
}
sftk_FreeSession(sp);
sp = NULL;
/* make sure the pins aren't too long */
if (ulPinLen > SFTK_MAX_PIN) {
crv = CKR_PIN_LEN_RANGE;
goto loser;
}
if (ulPinLen < (CK_ULONG)slot->minimumPinLen) {
crv = CKR_PIN_LEN_RANGE;
goto loser;
}
if (nsslowkey_HasKeyDBPassword(handle) != SECFailure) {
crv = CKR_DEVICE_ERROR;
goto loser;
}
/* convert to null terminated string */
PORT_Memcpy(newPinStr,pPin,ulPinLen);
newPinStr[ulPinLen] = 0;
/* build the hashed pins which we pass around */
newPin = nsslowkey_HashPassword(newPinStr,handle->global_salt);
PORT_Memset(newPinStr,0,sizeof(newPinStr));
/* change the data base */
rv = nsslowkey_SetKeyDBPassword(handle,newPin);
sftk_freeKeyDB(handle);
handle = NULL;
/* Now update our local copy of the pin */
if (rv == SECSuccess) {
if (slot->password) {
SECITEM_ZfreeItem(slot->password, PR_TRUE);
}
slot->password = newPin;
if (ulPinLen == 0) slot->needLogin = PR_FALSE;
return CKR_OK;
}
SECITEM_ZfreeItem(newPin, PR_TRUE);
crv = CKR_PIN_INCORRECT;
loser:
if (sp) {
sftk_FreeSession(sp);
}
if (handle) {
sftk_freeKeyDB(handle);
}
return crv;
}
/* NSC_SetPIN modifies the PIN of user that is currently logged in. */
/* NOTE: This is only valid for the PRIVATE_KEY_SLOT */
CK_RV NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin,
CK_ULONG ulOldLen, CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen)
{
SFTKSession *sp = NULL;
SFTKSlot *slot;
NSSLOWKEYDBHandle *handle = NULL;
SECItem *newPin;
SECItem *oldPin;
char newPinStr[SFTK_MAX_PIN+1],oldPinStr[SFTK_MAX_PIN+1];
SECStatus rv;
CK_RV crv = CKR_SESSION_HANDLE_INVALID;
sp = sftk_SessionFromHandle(hSession);
if (sp == NULL) {
goto loser;
}
slot = sftk_SlotFromSession(sp);
if (!slot) {
goto loser;
}
handle = sftk_getKeyDB(slot);
if (handle == NULL) {
sftk_FreeSession(sp);
return CKR_PIN_LEN_RANGE; /* XXX FIXME wrong return value */
}
if (slot->needLogin && sp->info.state != CKS_RW_USER_FUNCTIONS) {
crv = CKR_USER_NOT_LOGGED_IN;
goto loser;
}
sftk_FreeSession(sp);
sp = NULL;
/* make sure the pins aren't too long */
if ((ulNewLen > SFTK_MAX_PIN) || (ulOldLen > SFTK_MAX_PIN)) {
crv = CKR_PIN_LEN_RANGE;
goto loser;
}
if (ulNewLen < (CK_ULONG)slot->minimumPinLen) {
crv = CKR_PIN_LEN_RANGE;
goto loser;
}
/* convert to null terminated string */
PORT_Memcpy(newPinStr,pNewPin,ulNewLen);
newPinStr[ulNewLen] = 0;
PORT_Memcpy(oldPinStr,pOldPin,ulOldLen);
oldPinStr[ulOldLen] = 0;
/* build the hashed pins which we pass around */
newPin = nsslowkey_HashPassword(newPinStr,handle->global_salt);
oldPin = nsslowkey_HashPassword(oldPinStr,handle->global_salt);
PORT_Memset(newPinStr,0,sizeof(newPinStr));
PORT_Memset(oldPinStr,0,sizeof(oldPinStr));
/* change the data base password */
PR_Lock(slot->pwCheckLock);
rv = nsslowkey_ChangeKeyDBPassword(handle,oldPin,newPin);
sftk_freeKeyDB(handle);
handle = NULL;
if ((rv != SECSuccess) && (slot->slotID == FIPS_SLOT_ID)) {
PR_Sleep(loginWaitTime);
}
PR_Unlock(slot->pwCheckLock);
/* Now update our local copy of the pin */
SECITEM_ZfreeItem(oldPin, PR_TRUE);
if (rv == SECSuccess) {
if (slot->password) {
SECITEM_ZfreeItem(slot->password, PR_TRUE);
}
slot->password = newPin;
slot->needLogin = (PRBool)(ulNewLen != 0);
return CKR_OK;
}
SECITEM_ZfreeItem(newPin, PR_TRUE);
crv = CKR_PIN_INCORRECT;
loser:
if (sp) {
sftk_FreeSession(sp);
}
if (handle) {
sftk_freeKeyDB(handle);
}
return crv;
}
/* NSC_OpenSession opens a session between an application and a token. */
CK_RV NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags,
CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession)
{
SFTKSlot *slot;
CK_SESSION_HANDLE sessionID;
SFTKSession *session;
SFTKSession *sameID;
slot = sftk_SlotFromID(slotID, PR_FALSE);
if (slot == NULL) return CKR_SLOT_ID_INVALID;
/* new session (we only have serial sessions) */
session = sftk_NewSession(slotID, Notify, pApplication,
flags | CKF_SERIAL_SESSION);
if (session == NULL) return CKR_HOST_MEMORY;
if (slot->readOnly && (flags & CKF_RW_SESSION)) {
/* NETSCAPE_SLOT_ID is Read ONLY */
session->info.flags &= ~CKF_RW_SESSION;
}
PZ_Lock(slot->slotLock);
++slot->sessionCount;
PZ_Unlock(slot->slotLock);
if (session->info.flags & CKF_RW_SESSION) {
PR_AtomicIncrement(&slot->rwSessionCount);
}
do {
PZLock *lock;
do {
sessionID = (PR_AtomicIncrement(&slot->sessionIDCount) & 0xffffff)
| (slot->index << 24);
} while (sessionID == CK_INVALID_HANDLE);
lock = SFTK_SESSION_LOCK(slot,sessionID);
PZ_Lock(lock);
sftkqueue_find(sameID, sessionID, slot->head, slot->sessHashSize);
if (sameID == NULL) {
session->handle = sessionID;
sftk_update_state(slot, session);
sftkqueue_add(session, sessionID, slot->head,slot->sessHashSize);
} else {
slot->sessionIDConflict++; /* for debugging */
}
PZ_Unlock(lock);
} while (sameID != NULL);
*phSession = sessionID;
return CKR_OK;
}
/* NSC_CloseSession closes a session between an application and a token. */
CK_RV NSC_CloseSession(CK_SESSION_HANDLE hSession)
{
SFTKSlot *slot;
SFTKSession *session;
SECItem *pw = NULL;
PRBool sessionFound;
PZLock *lock;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
slot = sftk_SlotFromSession(session);
sessionFound = PR_FALSE;
/* lock */
lock = SFTK_SESSION_LOCK(slot,hSession);
PZ_Lock(lock);
if (sftkqueue_is_queued(session,hSession,slot->head,slot->sessHashSize)) {
sessionFound = PR_TRUE;
sftkqueue_delete(session,hSession,slot->head,slot->sessHashSize);
session->refCount--; /* can't go to zero while we hold the reference */
PORT_Assert(session->refCount > 0);
}
PZ_Unlock(lock);
if (sessionFound) {
PZ_Lock(slot->slotLock);
if (--slot->sessionCount == 0) {
pw = slot->password;
slot->isLoggedIn = PR_FALSE;
slot->password = NULL;
}
PZ_Unlock(slot->slotLock);
if (session->info.flags & CKF_RW_SESSION) {
PR_AtomicDecrement(&slot->rwSessionCount);
}
}
sftk_FreeSession(session);
if (pw) SECITEM_ZfreeItem(pw, PR_TRUE);
return CKR_OK;
}
/* NSC_CloseAllSessions closes all sessions with a token. */
CK_RV NSC_CloseAllSessions (CK_SLOT_ID slotID)
{
SFTKSlot *slot;
slot = sftk_SlotFromID(slotID, PR_FALSE);
if (slot == NULL) return CKR_SLOT_ID_INVALID;
return sft_CloseAllSession(slot);
}
/* NSC_GetSessionInfo obtains information about the session. */
CK_RV NSC_GetSessionInfo(CK_SESSION_HANDLE hSession,
CK_SESSION_INFO_PTR pInfo)
{
SFTKSession *session;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
PORT_Memcpy(pInfo,&session->info,sizeof(CK_SESSION_INFO));
sftk_FreeSession(session);
return CKR_OK;
}
/* NSC_Login logs a user into a token. */
CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType,
CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
{
SFTKSlot *slot;
SFTKSession *session;
NSSLOWKEYDBHandle *handle;
CK_FLAGS sessionFlags;
SECStatus rv;
CK_RV crv;
SECItem *pin;
char pinStr[SFTK_MAX_PIN+1];
/* get the slot */
slot = sftk_SlotFromSessionHandle(hSession);
/* make sure the session is valid */
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
sessionFlags = session->info.flags;
sftk_FreeSession(session);
session = NULL;
/* can't log into the Netscape Slot */
if (slot->slotID == NETSCAPE_SLOT_ID) {
return CKR_USER_TYPE_INVALID;
}
if (slot->isLoggedIn) return CKR_USER_ALREADY_LOGGED_IN;
slot->ssoLoggedIn = PR_FALSE;
if (ulPinLen > SFTK_MAX_PIN) return CKR_PIN_LEN_RANGE;
/* convert to null terminated string */
PORT_Memcpy(pinStr,pPin,ulPinLen);
pinStr[ulPinLen] = 0;
handle = sftk_getKeyDB(slot);
if (handle == NULL) {
return CKR_USER_TYPE_INVALID;
}
/*
* Deal with bootstrap. We allow the SSO to login in with a NULL
* password if and only if we haven't initialized the KEY DB yet.
* We only allow this on a RW session.
*/
rv = nsslowkey_HasKeyDBPassword(handle);
if (rv == SECFailure) {
/* allow SSO's to log in only if there is not password on the
* key database */
if (((userType == CKU_SO) && (sessionFlags & CKF_RW_SESSION))
/* fips always needs to authenticate, even if there isn't a db */
|| (slot->slotID == FIPS_SLOT_ID)) {
/* should this be a fixed password? */
if (ulPinLen == 0) {
SECItem *pw;
PZ_Lock(slot->slotLock);
pw = slot->password;
slot->password = NULL;
slot->isLoggedIn = PR_TRUE;
slot->ssoLoggedIn = (PRBool)(userType == CKU_SO);
PZ_Unlock(slot->slotLock);
sftk_update_all_states(slot);
SECITEM_ZfreeItem(pw,PR_TRUE);
crv = CKR_OK;
goto done;
}
crv = CKR_PIN_INCORRECT;
goto done;
}
crv = CKR_USER_TYPE_INVALID;
goto done;
}
/* don't allow the SSO to log in if the user is already initialized */
if (userType != CKU_USER) {
crv = CKR_USER_TYPE_INVALID;
goto done;
}
/* build the hashed pins which we pass around */
pin = nsslowkey_HashPassword(pinStr,handle->global_salt);
if (pin == NULL) {
crv = CKR_HOST_MEMORY;
goto done;
}
PR_Lock(slot->pwCheckLock);
rv = nsslowkey_CheckKeyDBPassword(handle,pin);
sftk_freeKeyDB(handle);
handle = NULL;
if ((rv != SECSuccess) && (slot->slotID == FIPS_SLOT_ID)) {
PR_Sleep(loginWaitTime);
}
PR_Unlock(slot->pwCheckLock);
if (rv == SECSuccess) {
SECItem *tmp;
PZ_Lock(slot->slotLock);
tmp = slot->password;
slot->isLoggedIn = PR_TRUE;
slot->password = pin;
PZ_Unlock(slot->slotLock);
if (tmp) SECITEM_ZfreeItem(tmp, PR_TRUE);
/* update all sessions */
sftk_update_all_states(slot);
return CKR_OK;
}
SECITEM_ZfreeItem(pin, PR_TRUE);
crv = CKR_PIN_INCORRECT;
done:
if (handle) {
sftk_freeKeyDB(handle);
}
return crv;
}
/* NSC_Logout logs a user out from a token. */
CK_RV NSC_Logout(CK_SESSION_HANDLE hSession)
{
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
SFTKSession *session;
SECItem *pw = NULL;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
sftk_FreeSession(session);
session = NULL;
if (!slot->isLoggedIn) return CKR_USER_NOT_LOGGED_IN;
PZ_Lock(slot->slotLock);
pw = slot->password;
slot->isLoggedIn = PR_FALSE;
slot->ssoLoggedIn = PR_FALSE;
slot->password = NULL;
PZ_Unlock(slot->slotLock);
if (pw) SECITEM_ZfreeItem(pw, PR_TRUE);
sftk_update_all_states(slot);
return CKR_OK;
}
/*
* Create a new slot on the fly. The slot that is passed in is the
* slot the request came from. Only the crypto or FIPS slots can
* be used. The resulting slot will live in the same module as
* the slot the request was passed to. object is the creation object
* that specifies the module spec for the new slot.
*/
static CK_RV sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class,
SFTKObject *object)
{
CK_SLOT_ID idMin, idMax;
PRBool isFIPS = PR_FALSE;
unsigned long moduleIndex;
SFTKAttribute *attribute;
sftk_parameters paramStrings;
char *paramString;
CK_SLOT_ID slotID = 0;
SFTKSlot *newSlot = NULL;
CK_RV crv = CKR_OK;
/* only the crypto or FIPS slots can create new slot objects */
if (slot->slotID == NETSCAPE_SLOT_ID) {
idMin = SFTK_MIN_USER_SLOT_ID;
idMax = SFTK_MAX_USER_SLOT_ID;
moduleIndex = NSC_NON_FIPS_MODULE;
isFIPS = PR_FALSE;
} else if (slot->slotID == FIPS_SLOT_ID) {
idMin = SFTK_MIN_FIPS_USER_SLOT_ID;
idMax = SFTK_MAX_FIPS_USER_SLOT_ID;
moduleIndex = NSC_FIPS_MODULE;
isFIPS = PR_TRUE;
} else {
return CKR_ATTRIBUTE_VALUE_INVALID;
}
attribute = sftk_FindAttribute(object,CKA_NETSCAPE_MODULE_SPEC);
if (attribute == NULL) {
return CKR_TEMPLATE_INCOMPLETE;
}
paramString = (char *)attribute->attrib.pValue;
crv = secmod_parseParameters(paramString, ¶mStrings, isFIPS);
if (crv != CKR_OK) {
goto loser;
}
/* enforce only one at a time */
if (paramStrings.token_count != 1) {
crv = CKR_ATTRIBUTE_VALUE_INVALID;
goto loser;
}
slotID = paramStrings.tokens[0].slotID;
/* stay within the valid ID space */
if ((slotID < idMin) || (slotID > idMax)) {
crv = CKR_ATTRIBUTE_VALUE_INVALID;
goto loser;
}
/* unload any existing slot at this id */
newSlot = sftk_SlotFromID(slotID, PR_TRUE);
if (newSlot && newSlot->present) {
crv = SFTK_ShutdownSlot(newSlot);
if (crv != CKR_OK) {
goto loser;
}
}
/* if we were just planning on deleting the slot, then do so now */
if (class == CKO_NETSCAPE_DELSLOT) {
/* sort of a unconventional use of this error code, be we are
* overusing CKR_ATTRIBUTE_VALUE_INVALID, and it does apply */
crv = newSlot ? CKR_OK : CKR_SLOT_ID_INVALID;
goto loser; /* really exit */
}
if (newSlot) {
crv = SFTK_SlotReInit(newSlot, paramStrings.configdir,
¶mStrings.tokens[0], moduleIndex);
} else {
crv = SFTK_SlotInit(paramStrings.configdir,
¶mStrings.tokens[0], moduleIndex);
}
if (crv != CKR_OK) {
goto loser;
}
loser:
secmod_freeParams(¶mStrings);
sftk_FreeAttribute(attribute);
return crv;
}
/* NSC_CreateObject creates a new object. */
CK_RV NSC_CreateObject(CK_SESSION_HANDLE hSession,
CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR phObject)
{
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
SFTKSession *session;
SFTKObject *object;
/* make sure class isn't randomly CKO_NETSCAPE_NEWSLOT or
* CKO_NETSCPE_DELSLOT. */
CK_OBJECT_CLASS class = CKO_VENDOR_DEFINED;
CK_RV crv;
int i;
*phObject = CK_INVALID_HANDLE;
/*
* now lets create an object to hang the attributes off of
*/
object = sftk_NewObject(slot); /* fill in the handle later */
if (object == NULL) {
return CKR_HOST_MEMORY;
}
/*
* load the template values into the object
*/
for (i=0; i < (int) ulCount; i++) {
crv = sftk_AddAttributeType(object,sftk_attr_expand(&pTemplate[i]));
if (crv != CKR_OK) {
sftk_FreeObject(object);
return crv;
}
if ((pTemplate[i].type == CKA_CLASS) && pTemplate[i].pValue) {
class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue;
}
}
/* get the session */
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
sftk_FreeObject(object);
return CKR_SESSION_HANDLE_INVALID;
}
/*
* handle pseudo objects (CKO_NEWSLOT)
*/
if ((class == CKO_NETSCAPE_NEWSLOT) || (class == CKO_NETSCAPE_DELSLOT)) {
crv = sftk_CreateNewSlot(slot, class, object);
goto done;
}
/*
* handle the base object stuff
*/
crv = sftk_handleObject(object,session);
*phObject = object->handle;
done:
sftk_FreeSession(session);
sftk_FreeObject(object);
return crv;
}
/* NSC_CopyObject copies an object, creating a new object for the copy. */
CK_RV NSC_CopyObject(CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR phNewObject)
{
SFTKObject *destObject,*srcObject;
SFTKSession *session;
CK_RV crv = CKR_OK;
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
int i;
/* Get srcObject so we can find the class */
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
srcObject = sftk_ObjectFromHandle(hObject,session);
if (srcObject == NULL) {
sftk_FreeSession(session);
return CKR_OBJECT_HANDLE_INVALID;
}
/*
* create an object to hang the attributes off of
*/
destObject = sftk_NewObject(slot); /* fill in the handle later */
if (destObject == NULL) {
sftk_FreeSession(session);
sftk_FreeObject(srcObject);
return CKR_HOST_MEMORY;
}
/*
* load the template values into the object
*/
for (i=0; i < (int) ulCount; i++) {
if (sftk_modifyType(pTemplate[i].type,srcObject->objclass) == SFTK_NEVER) {
crv = CKR_ATTRIBUTE_READ_ONLY;
break;
}
crv = sftk_AddAttributeType(destObject,sftk_attr_expand(&pTemplate[i]));
if (crv != CKR_OK) { break; }
}
if (crv != CKR_OK) {
sftk_FreeSession(session);
sftk_FreeObject(srcObject);
sftk_FreeObject(destObject);
return crv;
}
/* sensitive can only be changed to CK_TRUE */
if (sftk_hasAttribute(destObject,CKA_SENSITIVE)) {
if (!sftk_isTrue(destObject,CKA_SENSITIVE)) {
sftk_FreeSession(session);
sftk_FreeObject(srcObject);
sftk_FreeObject(destObject);
return CKR_ATTRIBUTE_READ_ONLY;
}
}
/*
* now copy the old attributes from the new attributes
*/
/* don't create a token object if we aren't in a rw session */
/* we need to hold the lock to copy a consistant version of
* the object. */
crv = sftk_CopyObject(destObject,srcObject);
destObject->objclass = srcObject->objclass;
sftk_FreeObject(srcObject);
if (crv != CKR_OK) {
sftk_FreeObject(destObject);
sftk_FreeSession(session);
return crv;
}
crv = sftk_handleObject(destObject,session);
*phNewObject = destObject->handle;
sftk_FreeSession(session);
sftk_FreeObject(destObject);
return crv;
}
/* NSC_GetObjectSize gets the size of an object in bytes. */
CK_RV NSC_GetObjectSize(CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) {
*pulSize = 0;
return CKR_OK;
}
/* NSC_GetAttributeValue obtains the value of one or more object attributes. */
CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) {
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
SFTKSession *session;
SFTKObject *object;
SFTKAttribute *attribute;
PRBool sensitive;
CK_RV crv;
int i;
/*
* make sure we're allowed
*/
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
object = sftk_ObjectFromHandle(hObject,session);
sftk_FreeSession(session);
if (object == NULL) {
return CKR_OBJECT_HANDLE_INVALID;
}
/* don't read a private object if we aren't logged in */
if ((!slot->isLoggedIn) && (slot->needLogin) &&
(sftk_isTrue(object,CKA_PRIVATE))) {
sftk_FreeObject(object);
return CKR_USER_NOT_LOGGED_IN;
}
crv = CKR_OK;
sensitive = sftk_isTrue(object,CKA_SENSITIVE);
for (i=0; i < (int) ulCount; i++) {
/* Make sure that this attribute is retrievable */
if (sensitive && sftk_isSensitive(pTemplate[i].type,object->objclass)) {
crv = CKR_ATTRIBUTE_SENSITIVE;
pTemplate[i].ulValueLen = -1;
continue;
}
attribute = sftk_FindAttribute(object,pTemplate[i].type);
if (attribute == NULL) {
crv = CKR_ATTRIBUTE_TYPE_INVALID;
pTemplate[i].ulValueLen = -1;
continue;
}
if (pTemplate[i].pValue != NULL) {
PORT_Memcpy(pTemplate[i].pValue,attribute->attrib.pValue,
attribute->attrib.ulValueLen);
}
pTemplate[i].ulValueLen = attribute->attrib.ulValueLen;
sftk_FreeAttribute(attribute);
}
sftk_FreeObject(object);
return crv;
}
/* NSC_SetAttributeValue modifies the value of one or more object attributes */
CK_RV NSC_SetAttributeValue (CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) {
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
SFTKSession *session;
SFTKAttribute *attribute;
SFTKObject *object;
PRBool isToken;
CK_RV crv = CKR_OK;
CK_BBOOL legal;
int i;
/*
* make sure we're allowed
*/
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
return CKR_SESSION_HANDLE_INVALID;
}
object = sftk_ObjectFromHandle(hObject,session);
if (object == NULL) {
sftk_FreeSession(session);
return CKR_OBJECT_HANDLE_INVALID;
}
/* don't modify a private object if we aren't logged in */
if ((!slot->isLoggedIn) && (slot->needLogin) &&
(sftk_isTrue(object,CKA_PRIVATE))) {
sftk_FreeSession(session);
sftk_FreeObject(object);
return CKR_USER_NOT_LOGGED_IN;
}
/* don't modify a token object if we aren't in a rw session */
isToken = sftk_isTrue(object,CKA_TOKEN);
if (((session->info.flags & CKF_RW_SESSION) == 0) && isToken) {
sftk_FreeSession(session);
sftk_FreeObject(object);
return CKR_SESSION_READ_ONLY;
}
sftk_FreeSession(session);
/* only change modifiable objects */
if (!sftk_isTrue(object,CKA_MODIFIABLE)) {
sftk_FreeObject(object);
return CKR_ATTRIBUTE_READ_ONLY;
}
for (i=0; i < (int) ulCount; i++) {
/* Make sure that this attribute is changeable */
switch (sftk_modifyType(pTemplate[i].type,object->objclass)) {
case SFTK_NEVER:
case SFTK_ONCOPY:
default:
crv = CKR_ATTRIBUTE_READ_ONLY;
break;
case SFTK_SENSITIVE:
legal = (pTemplate[i].type == CKA_EXTRACTABLE) ? CK_FALSE : CK_TRUE;
if ((*(CK_BBOOL *)pTemplate[i].pValue) != legal) {
crv = CKR_ATTRIBUTE_READ_ONLY;
}
break;
case SFTK_ALWAYS:
break;
}
if (crv != CKR_OK) break;
/* find the old attribute */
attribute = sftk_FindAttribute(object,pTemplate[i].type);
if (attribute == NULL) {
crv =CKR_ATTRIBUTE_TYPE_INVALID;
break;
}
sftk_FreeAttribute(attribute);
crv = sftk_forceAttribute(object,sftk_attr_expand(&pTemplate[i]));
if (crv != CKR_OK) break;
}
sftk_FreeObject(object);
return crv;
}
/*
* find any certs that may match the template and load them.
*/
#define NSC_CERT 0x00000001
#define NSC_TRUST 0x00000002
#define NSC_CRL 0x00000004
#define NSC_SMIME 0x00000008
#define NSC_PRIVATE 0x00000010
#define NSC_PUBLIC 0x00000020
#define NSC_KEY 0x00000040
/*
* structure to collect key handles.
*/
typedef struct sftkCrlDataStr {
SFTKSlot *slot;
SFTKSearchResults *searchHandles;
CK_ATTRIBUTE *template;
CK_ULONG templ_count;
} sftkCrlData;
static SECStatus
sftk_crl_collect(SECItem *data, SECItem *key, certDBEntryType type, void *arg)
{
sftkCrlData *crlData;
CK_OBJECT_HANDLE class_handle;
SFTKSlot *slot;
crlData = (sftkCrlData *)arg;
slot = crlData->slot;
class_handle = (type == certDBEntryTypeRevocation) ? SFTK_TOKEN_TYPE_CRL :
SFTK_TOKEN_KRL_HANDLE;
if (sftk_tokenMatch(slot, key, class_handle,
crlData->template, crlData->templ_count)) {
sftk_addHandle(crlData->searchHandles,
sftk_mkHandle(slot,key,class_handle));
}
return(SECSuccess);
}
static void
sftk_searchCrls(SFTKSlot *slot, SECItem *derSubject, PRBool isKrl,
unsigned long classFlags, SFTKSearchResults *search,
CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount)
{
NSSLOWCERTCertDBHandle *certHandle = NULL;
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) {
return;
}
if (derSubject->data != NULL) {
certDBEntryRevocation *crl =
nsslowcert_FindCrlByKey(certHandle, derSubject, isKrl);
if (crl != NULL) {
sftk_addHandle(search, sftk_mkHandle(slot, derSubject,
isKrl ? SFTK_TOKEN_KRL_HANDLE : SFTK_TOKEN_TYPE_CRL));
nsslowcert_DestroyDBEntry((certDBEntry *)crl);
}
} else {
sftkCrlData crlData;
/* traverse */
crlData.slot = slot;
crlData.searchHandles = search;
crlData.template = pTemplate;
crlData.templ_count = ulCount;
nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeRevocation,
sftk_crl_collect, (void *)&crlData);
nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeKeyRevocation,
sftk_crl_collect, (void *)&crlData);
}
sftk_freeCertDB(certHandle);
}
/*
* structure to collect key handles.
*/
typedef struct sftkKeyDataStr {
SFTKSlot *slot;
NSSLOWKEYDBHandle *keyHandle;
SFTKSearchResults *searchHandles;
SECItem *id;
CK_ATTRIBUTE *template;
CK_ULONG templ_count;
unsigned long classFlags;
PRBool isLoggedIn;
PRBool strict;
} sftkKeyData;
static SECStatus
sftk_key_collect(DBT *key, DBT *data, void *arg)
{
sftkKeyData *keyData;
NSSLOWKEYPrivateKey *privKey = NULL;
SECItem tmpDBKey;
SFTKSlot *slot;
keyData = (sftkKeyData *)arg;
slot = keyData->slot;
tmpDBKey.data = key->data;
tmpDBKey.len = key->size;
tmpDBKey.type = siBuffer;
PORT_Assert(keyData->keyHandle);
if (!keyData->strict && keyData->id && keyData->id->data) {
SECItem result;
PRBool haveMatch= PR_FALSE;
unsigned char hashKey[SHA1_LENGTH];
result.data = hashKey;
result.len = sizeof(hashKey);
if (keyData->id->len == 0) {
/* Make sure this isn't a NSC_KEY */
privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle,
&tmpDBKey, keyData->slot->password);
if (privKey) {
haveMatch = isSecretKey(privKey) ?
(PRBool)(keyData->classFlags & NSC_KEY) != 0:
(PRBool)(keyData->classFlags &
(NSC_PRIVATE|NSC_PUBLIC)) != 0;
nsslowkey_DestroyPrivateKey(privKey);
}
} else {
SHA1_HashBuf( hashKey, key->data, key->size ); /* match id */
haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result);
if (!haveMatch && ((unsigned char *)key->data)[0] == 0) {
/* This is a fix for backwards compatibility. The key
* database indexes private keys by the public key, and
* versions of NSS prior to 3.4 stored the public key as
* a signed integer. The public key is now treated as an
* unsigned integer, with no leading zero. In order to
* correctly compute the hash of an old key, it is necessary
* to fallback and detect the leading zero.
*/
SHA1_HashBuf(hashKey,
(unsigned char *)key->data + 1, key->size - 1);
haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result);
}
}
if (haveMatch) {
if (keyData->classFlags & NSC_PRIVATE) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(slot,&tmpDBKey,SFTK_TOKEN_TYPE_PRIV));
}
if (keyData->classFlags & NSC_PUBLIC) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(slot,&tmpDBKey,SFTK_TOKEN_TYPE_PUB));
}
if (keyData->classFlags & NSC_KEY) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(slot,&tmpDBKey,SFTK_TOKEN_TYPE_KEY));
}
}
return SECSuccess;
}
privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle, &tmpDBKey,
keyData->slot->password);
if ( privKey == NULL ) {
goto loser;
}
if (isSecretKey(privKey)) {
if ((keyData->classFlags & NSC_KEY) &&
sftk_tokenMatch(keyData->slot, &tmpDBKey, SFTK_TOKEN_TYPE_KEY,
keyData->template, keyData->templ_count)) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(keyData->slot, &tmpDBKey, SFTK_TOKEN_TYPE_KEY));
}
} else {
if ((keyData->classFlags & NSC_PRIVATE) &&
sftk_tokenMatch(keyData->slot, &tmpDBKey, SFTK_TOKEN_TYPE_PRIV,
keyData->template, keyData->templ_count)) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(keyData->slot,&tmpDBKey,SFTK_TOKEN_TYPE_PRIV));
}
if ((keyData->classFlags & NSC_PUBLIC) &&
sftk_tokenMatch(keyData->slot, &tmpDBKey, SFTK_TOKEN_TYPE_PUB,
keyData->template, keyData->templ_count)) {
sftk_addHandle(keyData->searchHandles,
sftk_mkHandle(keyData->slot, &tmpDBKey,SFTK_TOKEN_TYPE_PUB));
}
}
loser:
if ( privKey ) {
nsslowkey_DestroyPrivateKey(privKey);
}
return(SECSuccess);
}
static void
sftk_searchKeys(SFTKSlot *slot, SECItem *key_id, PRBool isLoggedIn,
unsigned long classFlags, SFTKSearchResults *search, PRBool mustStrict,
CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount)
{
NSSLOWKEYDBHandle *keyHandle = NULL;
NSSLOWKEYPrivateKey *privKey;
sftkKeyData keyData;
PRBool found = PR_FALSE;
keyHandle = sftk_getKeyDB(slot);
if (keyHandle == NULL) {
return;
}
if (key_id->data) {
privKey = nsslowkey_FindKeyByPublicKey(keyHandle, key_id, slot->password);
if (privKey) {
if ((classFlags & NSC_KEY) && isSecretKey(privKey)) {
sftk_addHandle(search,
sftk_mkHandle(slot,key_id,SFTK_TOKEN_TYPE_KEY));
found = PR_TRUE;
}
if ((classFlags & NSC_PRIVATE) && !isSecretKey(privKey)) {
sftk_addHandle(search,
sftk_mkHandle(slot,key_id,SFTK_TOKEN_TYPE_PRIV));
found = PR_TRUE;
}
if ((classFlags & NSC_PUBLIC) && !isSecretKey(privKey)) {
sftk_addHandle(search,
sftk_mkHandle(slot,key_id,SFTK_TOKEN_TYPE_PUB));
found = PR_TRUE;
}
nsslowkey_DestroyPrivateKey(privKey);
}
/* don't do the traversal if we have an up to date db */
if (keyHandle->version != 3) {
goto loser;
}
/* don't do the traversal if it can't possibly be the correct id */
/* all soft token id's are SHA1_HASH_LEN's */
if (key_id->len != SHA1_LENGTH) {
goto loser;
}
if (found) {
/* if we already found some keys, don't do the traversal */
goto loser;
}
}
keyData.slot = slot;
keyData.keyHandle = keyHandle;
keyData.searchHandles = search;
keyData.id = key_id;
keyData.template = pTemplate;
keyData.templ_count = ulCount;
keyData.isLoggedIn = isLoggedIn;
keyData.classFlags = classFlags;
keyData.strict = mustStrict ? mustStrict : NSC_STRICT;
nsslowkey_TraverseKeys(keyHandle, sftk_key_collect, &keyData);
loser:
sftk_freeKeyDB(keyHandle);
}
/*
* structure to collect certs into
*/
typedef struct sftkCertDataStr {
SFTKSlot *slot;
int cert_count;
int max_cert_count;
NSSLOWCERTCertificate **certs;
CK_ATTRIBUTE *template;
CK_ULONG templ_count;
unsigned long classFlags;
PRBool strict;
} sftkCertData;
/*
* collect all the certs from the traverse call.
*/
static SECStatus
sftk_cert_collect(NSSLOWCERTCertificate *cert,void *arg)
{
sftkCertData *cd = (sftkCertData *)arg;
if (cert == NULL) {
return SECSuccess;
}
if (cd->certs == NULL) {
return SECFailure;
}
if (cd->strict) {
if ((cd->classFlags & NSC_CERT) && !sftk_tokenMatch(cd->slot,
&cert->certKey, SFTK_TOKEN_TYPE_CERT, cd->template,cd->templ_count)) {
return SECSuccess;
}
if ((cd->classFlags & NSC_TRUST) && !sftk_tokenMatch(cd->slot,
&cert->certKey, SFTK_TOKEN_TYPE_TRUST,
cd->template, cd->templ_count)) {
return SECSuccess;
}
}
/* allocate more space if we need it. This should only happen in
* the general traversal case */
if (cd->cert_count >= cd->max_cert_count) {
int size;
cd->max_cert_count += NSC_CERT_BLOCK_SIZE;
size = cd->max_cert_count * sizeof (NSSLOWCERTCertificate *);
cd->certs = (NSSLOWCERTCertificate **)PORT_Realloc(cd->certs,size);
if (cd->certs == NULL) {
return SECFailure;
}
}
cd->certs[cd->cert_count++] = nsslowcert_DupCertificate(cert);
return SECSuccess;
}
/* provide impedence matching ... */
static SECStatus
sftk_cert_collect2(NSSLOWCERTCertificate *cert, SECItem *dymmy, void *arg)
{
return sftk_cert_collect(cert, arg);
}
static void
sftk_searchSingleCert(sftkCertData *certData,NSSLOWCERTCertificate *cert)
{
if (cert == NULL) {
return;
}
if (certData->strict &&
!sftk_tokenMatch(certData->slot, &cert->certKey, SFTK_TOKEN_TYPE_CERT,
certData->template,certData->templ_count)) {
nsslowcert_DestroyCertificate(cert);
return;
}
certData->certs = (NSSLOWCERTCertificate **)
PORT_Alloc(sizeof (NSSLOWCERTCertificate *));
if (certData->certs == NULL) {
nsslowcert_DestroyCertificate(cert);
return;
}
certData->certs[0] = cert;
certData->cert_count = 1;
}
static void
sftk_CertSetupData(sftkCertData *certData,int count)
{
certData->max_cert_count = count;
if (certData->max_cert_count <= 0) {
return;
}
certData->certs = (NSSLOWCERTCertificate **)
PORT_Alloc( count * sizeof(NSSLOWCERTCertificate *));
return;
}
static void
sftk_searchCertsAndTrust(SFTKSlot *slot, SECItem *derCert, SECItem *name,
SECItem *derSubject, NSSLOWCERTIssuerAndSN *issuerSN,
SECItem *email,
unsigned long classFlags, SFTKSearchResults *handles,
CK_ATTRIBUTE *pTemplate, CK_LONG ulCount)
{
NSSLOWCERTCertDBHandle *certHandle = NULL;
sftkCertData certData;
int i;
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) return;
certData.slot = slot;
certData.max_cert_count = 0;
certData.certs = NULL;
certData.cert_count = 0;
certData.template = pTemplate;
certData.templ_count = ulCount;
certData.classFlags = classFlags;
certData.strict = NSC_STRICT;
/*
* Find the Cert.
*/
if (derCert->data != NULL) {
NSSLOWCERTCertificate *cert =
nsslowcert_FindCertByDERCert(certHandle,derCert);
sftk_searchSingleCert(&certData,cert);
} else if (name->data != NULL) {
char *tmp_name = (char*)PORT_Alloc(name->len+1);
int count;
if (tmp_name == NULL) {
return;
}
PORT_Memcpy(tmp_name,name->data,name->len);
tmp_name[name->len] = 0;
count= nsslowcert_NumPermCertsForNickname(certHandle,tmp_name);
sftk_CertSetupData(&certData,count);
nsslowcert_TraversePermCertsForNickname(certHandle,tmp_name,
sftk_cert_collect, &certData);
PORT_Free(tmp_name);
} else if (derSubject->data != NULL) {
int count;
count = nsslowcert_NumPermCertsForSubject(certHandle,derSubject);
sftk_CertSetupData(&certData,count);
nsslowcert_TraversePermCertsForSubject(certHandle,derSubject,
sftk_cert_collect, &certData);
} else if ((issuerSN->derIssuer.data != NULL) &&
(issuerSN->serialNumber.data != NULL)) {
if (classFlags & NSC_CERT) {
NSSLOWCERTCertificate *cert =
nsslowcert_FindCertByIssuerAndSN(certHandle,issuerSN);
sftk_searchSingleCert(&certData,cert);
}
if (classFlags & NSC_TRUST) {
NSSLOWCERTTrust *trust =
nsslowcert_FindTrustByIssuerAndSN(certHandle, issuerSN);
if (trust) {
sftk_addHandle(handles,
sftk_mkHandle(slot,&trust->dbKey,SFTK_TOKEN_TYPE_TRUST));
nsslowcert_DestroyTrust(trust);
}
}
} else if (email->data != NULL) {
char *tmp_name = (char*)PORT_Alloc(email->len+1);
certDBEntrySMime *entry = NULL;
if (tmp_name == NULL) {
return;
}
PORT_Memcpy(tmp_name,email->data,email->len);
tmp_name[email->len] = 0;
entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name);
if (entry) {
int count;
SECItem *subjectName = &entry->subjectName;
count = nsslowcert_NumPermCertsForSubject(certHandle, subjectName);
sftk_CertSetupData(&certData,count);
nsslowcert_TraversePermCertsForSubject(certHandle, subjectName,
sftk_cert_collect, &certData);
nsslowcert_DestroyDBEntry((certDBEntry *)entry);
}
PORT_Free(tmp_name);
} else {
/* we aren't filtering the certs, we are working on all, so turn
* on the strict filters. */
certData.strict = PR_TRUE;
sftk_CertSetupData(&certData,NSC_CERT_BLOCK_SIZE);
nsslowcert_TraversePermCerts(certHandle, sftk_cert_collect2, &certData);
}
sftk_freeCertDB(certHandle);
/*
* build the handles
*/
for (i=0 ; i < certData.cert_count ; i++) {
NSSLOWCERTCertificate *cert = certData.certs[i];
/* if we filtered it would have been on the stuff above */
if (classFlags & NSC_CERT) {
sftk_addHandle(handles,
sftk_mkHandle(slot,&cert->certKey,SFTK_TOKEN_TYPE_CERT));
}
if ((classFlags & NSC_TRUST) && nsslowcert_hasTrust(cert->trust)) {
sftk_addHandle(handles,
sftk_mkHandle(slot,&cert->certKey,SFTK_TOKEN_TYPE_TRUST));
}
nsslowcert_DestroyCertificate(cert);
}
if (certData.certs) PORT_Free(certData.certs);
return;
}
static void
sftk_searchSMime(SFTKSlot *slot, SECItem *email, SFTKSearchResults *handles,
CK_ATTRIBUTE *pTemplate, CK_LONG ulCount)
{
NSSLOWCERTCertDBHandle *certHandle = NULL;
certDBEntrySMime *entry;
certHandle = sftk_getCertDB(slot);
if (certHandle == NULL) return;
if (email->data != NULL) {
char *tmp_name = (char*)PORT_Alloc(email->len+1);
if (tmp_name == NULL) {
sftk_freeCertDB(certHandle);
return;
}
PORT_Memcpy(tmp_name,email->data,email->len);
tmp_name[email->len] = 0;
entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name);
if (entry) {
SECItem emailKey;
emailKey.data = (unsigned char *)tmp_name;
emailKey.len = PORT_Strlen(tmp_name)+1;
emailKey.type = 0;
sftk_addHandle(handles,
sftk_mkHandle(slot,&emailKey,SFTK_TOKEN_TYPE_SMIME));
nsslowcert_DestroyDBEntry((certDBEntry *)entry);
}
PORT_Free(tmp_name);
}
sftk_freeCertDB(certHandle);
return;
}
static CK_RV
sftk_searchTokenList(SFTKSlot *slot, SFTKSearchResults *search,
CK_ATTRIBUTE *pTemplate, CK_LONG ulCount,
PRBool *tokenOnly, PRBool isLoggedIn)
{
int i;
PRBool isKrl = PR_FALSE;
SECItem derCert = { siBuffer, NULL, 0 };
SECItem derSubject = { siBuffer, NULL, 0 };
SECItem name = { siBuffer, NULL, 0 };
SECItem email = { siBuffer, NULL, 0 };
SECItem key_id = { siBuffer, NULL, 0 };
SECItem cert_sha1_hash = { siBuffer, NULL, 0 };
SECItem cert_md5_hash = { siBuffer, NULL, 0 };
NSSLOWCERTIssuerAndSN issuerSN = {
{ siBuffer, NULL, 0 },
{ siBuffer, NULL, 0 }
};
SECItem *copy = NULL;
unsigned long classFlags =
NSC_CERT|NSC_TRUST|NSC_PRIVATE|NSC_PUBLIC|NSC_KEY|NSC_SMIME|NSC_CRL;
/* if we aren't logged in, don't look for private or secret keys */
if (!isLoggedIn) {
classFlags &= ~(NSC_PRIVATE|NSC_KEY);
}
/*
* look for things to search on token objects for. If the right options
* are specified, we can use them as direct indeces into the database
* (rather than using linear searches. We can also use the attributes to
* limit the kinds of objects we are searching for. Later we can use this
* array to filter the remaining objects more finely.
*/
for (i=0 ;classFlags && i < (int)ulCount; i++) {
switch (pTemplate[i].type) {
case CKA_SUBJECT:
copy = &derSubject;
classFlags &= (NSC_CERT|NSC_PRIVATE|NSC_PUBLIC|NSC_SMIME|NSC_CRL);
break;
case CKA_ISSUER:
copy = &issuerSN.derIssuer;
classFlags &= (NSC_CERT|NSC_TRUST);
break;
case CKA_SERIAL_NUMBER:
copy = &issuerSN.serialNumber;
classFlags &= (NSC_CERT|NSC_TRUST);
break;
case CKA_VALUE:
copy = &derCert;
classFlags &= (NSC_CERT|NSC_CRL|NSC_SMIME);
break;
case CKA_LABEL:
copy = &name;
break;
case CKA_NETSCAPE_EMAIL:
copy = &email;
classFlags &= NSC_SMIME|NSC_CERT;
break;
case CKA_NETSCAPE_SMIME_TIMESTAMP:
classFlags &= NSC_SMIME;
break;
case CKA_CLASS:
if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) {
classFlags = 0;
break;;
}
switch (*((CK_OBJECT_CLASS *)pTemplate[i].pValue)) {
case CKO_CERTIFICATE:
classFlags &= NSC_CERT;
break;
case CKO_NETSCAPE_TRUST:
classFlags &= NSC_TRUST;
break;
case CKO_NETSCAPE_CRL:
classFlags &= NSC_CRL;
break;
case CKO_NETSCAPE_SMIME:
classFlags &= NSC_SMIME;
break;
case CKO_PRIVATE_KEY:
classFlags &= NSC_PRIVATE;
break;
case CKO_PUBLIC_KEY:
classFlags &= NSC_PUBLIC;
break;
case CKO_SECRET_KEY:
classFlags &= NSC_KEY;
break;
default:
classFlags = 0;
break;
}
break;
case CKA_PRIVATE:
if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) {
classFlags = 0;
}
if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) {
classFlags &= (NSC_PRIVATE|NSC_KEY);
} else {
classFlags &= ~(NSC_PRIVATE|NSC_KEY);
}
break;
case CKA_SENSITIVE:
if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) {
classFlags = 0;
}
if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) {
classFlags &= (NSC_PRIVATE|NSC_KEY);
} else {
classFlags = 0;
}
break;
case CKA_TOKEN:
if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) {
classFlags = 0;
}
if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) {
*tokenOnly = PR_TRUE;
} else {
classFlags = 0;
}
break;
case CKA_CERT_SHA1_HASH:
classFlags &= NSC_TRUST;
copy = &cert_sha1_hash; break;
case CKA_CERT_MD5_HASH:
classFlags &= NSC_TRUST;
copy = &cert_md5_hash; break;
case CKA_CERTIFICATE_TYPE:
if (pTemplate[i].ulValueLen != sizeof(CK_CERTIFICATE_TYPE)) {
classFlags = 0;
}
classFlags &= NSC_CERT;
if (*((CK_CERTIFICATE_TYPE *)pTemplate[i].pValue) != CKC_X_509) {
classFlags = 0;
}
break;
case CKA_ID:
copy = &key_id;
classFlags &= (NSC_CERT|NSC_PRIVATE|NSC_KEY|NSC_PUBLIC);
break;
case CKA_NETSCAPE_KRL:
if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) {
classFlags = 0;
}
classFlags &= NSC_CRL;
isKrl = (PRBool)(*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE);
break;
case CKA_MODIFIABLE:
break;
case CKA_KEY_TYPE:
case CKA_DERIVE:
classFlags &= NSC_PUBLIC|NSC_PRIVATE|NSC_KEY;
break;
case CKA_VERIFY_RECOVER:
classFlags &= NSC_PUBLIC;
break;
case CKA_SIGN_RECOVER:
classFlags &= NSC_PRIVATE;
break;
case CKA_ENCRYPT:
case CKA_VERIFY:
case CKA_WRAP:
classFlags &= NSC_PUBLIC|NSC_KEY;
break;
case CKA_DECRYPT:
case CKA_SIGN:
case CKA_UNWRAP:
case CKA_ALWAYS_SENSITIVE:
case CKA_EXTRACTABLE:
case CKA_NEVER_EXTRACTABLE:
classFlags &= NSC_PRIVATE|NSC_KEY;
break;
/* can't be a certificate if it doesn't match one of the above
* attributes */
default:
classFlags = 0;
break;
}
if (copy) {
copy->data = (unsigned char*)pTemplate[i].pValue;
copy->len = pTemplate[i].ulValueLen;
}
copy = NULL;
}
/* certs */
if (classFlags & (NSC_CERT|NSC_TRUST)) {
sftk_searchCertsAndTrust(slot,&derCert,&name,&derSubject,
&issuerSN, &email,classFlags,search,
pTemplate, ulCount);
}
/* keys */
if (classFlags & (NSC_PRIVATE|NSC_PUBLIC|NSC_KEY)) {
PRBool mustStrict = (name.len != 0);
sftk_searchKeys(slot, &key_id, isLoggedIn, classFlags, search,
mustStrict, pTemplate, ulCount);
}
/* crl's */
if (classFlags & NSC_CRL) {
sftk_searchCrls(slot, &derSubject, isKrl, classFlags, search,
pTemplate, ulCount);
}
/* Add S/MIME entry stuff */
if (classFlags & NSC_SMIME) {
sftk_searchSMime(slot, &email, search, pTemplate, ulCount);
}
return CKR_OK;
}
/* NSC_FindObjectsInit initializes a search for token and session objects
* that match a template. */
CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession,
CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount)
{
SFTKSearchResults *search = NULL, *freeSearch = NULL;
SFTKSession *session = NULL;
SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
PRBool tokenOnly = PR_FALSE;
CK_RV crv = CKR_OK;
PRBool isLoggedIn;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) {
crv = CKR_SESSION_HANDLE_INVALID;
goto loser;
}
search = (SFTKSearchResults *)PORT_Alloc(sizeof(SFTKSearchResults));
if (search == NULL) {
crv = CKR_HOST_MEMORY;
goto loser;
}
search->handles = (CK_OBJECT_HANDLE *)
PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE);
if (search->handles == NULL) {
crv = CKR_HOST_MEMORY;
goto loser;
}
search->index = 0;
search->size = 0;
search->array_size = NSC_SEARCH_BLOCK_SIZE;
isLoggedIn = (PRBool)((!slot->needLogin) || slot->isLoggedIn);
crv = sftk_searchTokenList(slot, search, pTemplate, ulCount, &tokenOnly,
isLoggedIn);
if (crv != CKR_OK) {
goto loser;
}
/* build list of found objects in the session */
if (!tokenOnly) {
crv = sftk_searchObjectList(search, slot->sessObjHashTable,
slot->sessObjHashSize, slot->objectLock,
pTemplate, ulCount, isLoggedIn);
}
if (crv != CKR_OK) {
goto loser;
}
if ((freeSearch = session->search) != NULL) {
session->search = NULL;
sftk_FreeSearch(freeSearch);
}
session->search = search;
sftk_FreeSession(session);
return CKR_OK;
loser:
if (search) {
sftk_FreeSearch(search);
}
if (session) {
sftk_FreeSession(session);
}
return crv;
}
/* NSC_FindObjects continues a search for token and session objects
* that match a template, obtaining additional object handles. */
CK_RV NSC_FindObjects(CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE_PTR phObject,CK_ULONG ulMaxObjectCount,
CK_ULONG_PTR pulObjectCount)
{
SFTKSession *session;
SFTKSearchResults *search;
int transfer;
int left;
*pulObjectCount = 0;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
if (session->search == NULL) {
sftk_FreeSession(session);
return CKR_OK;
}
search = session->search;
left = session->search->size - session->search->index;
transfer = ((int)ulMaxObjectCount > left) ? left : ulMaxObjectCount;
if (transfer > 0) {
PORT_Memcpy(phObject,&search->handles[search->index],
transfer*sizeof(CK_OBJECT_HANDLE_PTR));
} else {
*phObject = CK_INVALID_HANDLE;
}
search->index += transfer;
if (search->index == search->size) {
session->search = NULL;
sftk_FreeSearch(search);
}
*pulObjectCount = transfer;
sftk_FreeSession(session);
return CKR_OK;
}
/* NSC_FindObjectsFinal finishes a search for token and session objects. */
CK_RV NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession)
{
SFTKSession *session;
SFTKSearchResults *search;
session = sftk_SessionFromHandle(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
search = session->search;
session->search = NULL;
sftk_FreeSession(session);
if (search != NULL) {
sftk_FreeSearch(search);
}
return CKR_OK;
}
CK_RV NSC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot,
CK_VOID_PTR pReserved)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
|