DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (409f3966645a)

VCS Links

Line Code
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
 * This file manages object type indepentent functions.
 */
#include "seccomon.h"
#include "secmod.h"
#include "secmodi.h"
#include "secmodti.h"
#include "pkcs11.h"
#include "pkcs11t.h"
#include "pk11func.h"
#include "key.h"
#include "secitem.h"
#include "secerr.h"
#include "sslerr.h"

#define PK11_SEARCH_CHUNKSIZE 10

/*
 * Build a block big enough to hold the data
 */
SECItem *
PK11_BlockData(SECItem *data, unsigned long size)
{
    SECItem *newData;

    if (size == 0u)
        return NULL;

    newData = (SECItem *)PORT_Alloc(sizeof(SECItem));
    if (newData == NULL)
        return NULL;

    newData->len = (data->len + (size - 1)) / size;
    newData->len *= size;

    newData->data = (unsigned char *)PORT_ZAlloc(newData->len);
    if (newData->data == NULL) {
        PORT_Free(newData);
        return NULL;
    }
    PORT_Memset(newData->data, newData->len - data->len, newData->len);
    PORT_Memcpy(newData->data, data->data, data->len);
    return newData;
}

SECStatus
PK11_DestroyObject(PK11SlotInfo *slot, CK_OBJECT_HANDLE object)
{
    CK_RV crv;

    PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_DestroyObject(slot->session, object);
    PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_DestroyTokenObject(PK11SlotInfo *slot, CK_OBJECT_HANDLE object)
{
    CK_RV crv;
    SECStatus rv = SECSuccess;
    CK_SESSION_HANDLE rwsession;

    rwsession = PK11_GetRWSession(slot);
    if (rwsession == CK_INVALID_SESSION) {
        PORT_SetError(SEC_ERROR_BAD_DATA);
        return SECFailure;
    }

    crv = PK11_GETTAB(slot)->C_DestroyObject(rwsession, object);
    if (crv != CKR_OK) {
        rv = SECFailure;
        PORT_SetError(PK11_MapError(crv));
    }
    PK11_RestoreROSession(slot, rwsession);
    return rv;
}

/*
 * Read in a single attribute into a SECItem. Allocate space for it with
 * PORT_Alloc unless an arena is supplied. In the latter case use the arena
 * to allocate the space.
 *
 * PK11_ReadAttribute sets the 'data' and 'len' fields of the SECItem but
 * does not modify its 'type' field.
 */
SECStatus
PK11_ReadAttribute(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
                   CK_ATTRIBUTE_TYPE type, PLArenaPool *arena, SECItem *result)
{
    CK_ATTRIBUTE attr = { 0, NULL, 0 };
    CK_RV crv;

    attr.type = type;

    PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, id, &attr, 1);
    if (crv != CKR_OK) {
        PK11_ExitSlotMonitor(slot);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    if (arena) {
        attr.pValue = PORT_ArenaAlloc(arena, attr.ulValueLen);
    } else {
        attr.pValue = PORT_Alloc(attr.ulValueLen);
    }
    if (attr.pValue == NULL) {
        PK11_ExitSlotMonitor(slot);
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, id, &attr, 1);
    PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        if (!arena)
            PORT_Free(attr.pValue);
        return SECFailure;
    }

    result->data = (unsigned char *)attr.pValue;
    result->len = attr.ulValueLen;

    return SECSuccess;
}

/*
 * Read in a single attribute into As a Ulong.
 */
CK_ULONG
PK11_ReadULongAttribute(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
                        CK_ATTRIBUTE_TYPE type)
{
    CK_ATTRIBUTE attr;
    CK_ULONG value = CK_UNAVAILABLE_INFORMATION;
    CK_RV crv;

    PK11_SETATTRS(&attr, type, &value, sizeof(value));

    PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, id, &attr, 1);
    PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
    }
    return value;
}

/*
 * check to see if a bool has been set.
 */
CK_BBOOL
pk11_HasAttributeSet_Lock(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
                          CK_ATTRIBUTE_TYPE type, PRBool haslock)
{
    CK_BBOOL ckvalue = CK_FALSE;
    CK_ATTRIBUTE theTemplate;
    CK_RV crv;

    /* Prepare to retrieve the attribute. */
    PK11_SETATTRS(&theTemplate, type, &ckvalue, sizeof(CK_BBOOL));

    /* Retrieve attribute value. */
    if (!haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, id,
                                                 &theTemplate, 1);
    if (!haslock)
        PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return CK_FALSE;
    }

    return ckvalue;
}

CK_BBOOL
PK11_HasAttributeSet(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
                     CK_ATTRIBUTE_TYPE type, PRBool haslock)
{
    PR_ASSERT(haslock == PR_FALSE);
    return pk11_HasAttributeSet_Lock(slot, id, type, PR_FALSE);
}

/*
 * returns a full list of attributes. Allocate space for them. If an arena is
 * provided, allocate space out of the arena.
 */
CK_RV
PK11_GetAttributes(PLArenaPool *arena, PK11SlotInfo *slot,
                   CK_OBJECT_HANDLE obj, CK_ATTRIBUTE *attr, int count)
{
    int i;
    /* make pedantic happy... note that it's only used arena != NULL */
    void *mark = NULL;
    CK_RV crv;
    if (slot->session == CK_INVALID_SESSION)
        return CKR_SESSION_HANDLE_INVALID;

    /*
     * first get all the lengths of the parameters.
     */
    PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, obj, attr, count);
    if (crv != CKR_OK) {
        PK11_ExitSlotMonitor(slot);
        return crv;
    }

    if (arena) {
        mark = PORT_ArenaMark(arena);
        if (mark == NULL)
            return CKR_HOST_MEMORY;
    }

    /*
     * now allocate space to store the results.
     */
    for (i = 0; i < count; i++) {
        if (attr[i].ulValueLen == 0)
            continue;
        if (arena) {
            attr[i].pValue = PORT_ArenaAlloc(arena, attr[i].ulValueLen);
            if (attr[i].pValue == NULL) {
                /* arena failures, just release the mark */
                PORT_ArenaRelease(arena, mark);
                PK11_ExitSlotMonitor(slot);
                return CKR_HOST_MEMORY;
            }
        } else {
            attr[i].pValue = PORT_Alloc(attr[i].ulValueLen);
            if (attr[i].pValue == NULL) {
                /* Separate malloc failures, loop to release what we have
                 * so far */
                int j;
                for (j = 0; j < i; j++) {
                    PORT_Free(attr[j].pValue);
                    /* don't give the caller pointers to freed memory */
                    attr[j].pValue = NULL;
                }
                PK11_ExitSlotMonitor(slot);
                return CKR_HOST_MEMORY;
            }
        }
    }

    /*
     * finally get the results.
     */
    crv = PK11_GETTAB(slot)->C_GetAttributeValue(slot->session, obj, attr, count);
    PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        if (arena) {
            PORT_ArenaRelease(arena, mark);
        } else {
            for (i = 0; i < count; i++) {
                PORT_Free(attr[i].pValue);
                /* don't give the caller pointers to freed memory */
                attr[i].pValue = NULL;
            }
        }
    } else if (arena && mark) {
        PORT_ArenaUnmark(arena, mark);
    }
    return crv;
}

PRBool
PK11_IsPermObject(PK11SlotInfo *slot, CK_OBJECT_HANDLE handle)
{
    return (PRBool)PK11_HasAttributeSet(slot, handle, CKA_TOKEN, PR_FALSE);
}

char *
PK11_GetObjectNickname(PK11SlotInfo *slot, CK_OBJECT_HANDLE id)
{
    char *nickname = NULL;
    SECItem result;
    SECStatus rv;

    rv = PK11_ReadAttribute(slot, id, CKA_LABEL, NULL, &result);
    if (rv != SECSuccess) {
        return NULL;
    }

    nickname = PORT_ZAlloc(result.len + 1);
    if (nickname == NULL) {
        PORT_Free(result.data);
        return NULL;
    }
    PORT_Memcpy(nickname, result.data, result.len);
    PORT_Free(result.data);
    return nickname;
}

SECStatus
PK11_SetObjectNickname(PK11SlotInfo *slot, CK_OBJECT_HANDLE id,
                       const char *nickname)
{
    int len = PORT_Strlen(nickname);
    CK_ATTRIBUTE setTemplate;
    CK_RV crv;
    CK_SESSION_HANDLE rwsession;

    if (len < 0) {
        return SECFailure;
    }

    PK11_SETATTRS(&setTemplate, CKA_LABEL, (CK_CHAR *)nickname, len);
    rwsession = PK11_GetRWSession(slot);
    if (rwsession == CK_INVALID_SESSION) {
        PORT_SetError(SEC_ERROR_BAD_DATA);
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_SetAttributeValue(rwsession, id,
                                                 &setTemplate, 1);
    PK11_RestoreROSession(slot, rwsession);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

/*
 * strip leading zero's from key material
 */
void
pk11_SignedToUnsigned(CK_ATTRIBUTE *attrib)
{
    char *ptr = (char *)attrib->pValue;
    unsigned long len = attrib->ulValueLen;

    while ((len > 1) && (*ptr == 0)) {
        len--;
        ptr++;
    }
    attrib->pValue = ptr;
    attrib->ulValueLen = len;
}

/*
 * get a new session on a slot. If we run out of session, use the slot's
 * 'exclusive' session. In this case owner becomes false.
 */
CK_SESSION_HANDLE
pk11_GetNewSession(PK11SlotInfo *slot, PRBool *owner)
{
    CK_SESSION_HANDLE session;
    *owner = PR_TRUE;
    if (!slot->isThreadSafe)
        PK11_EnterSlotMonitor(slot);
    if (PK11_GETTAB(slot)->C_OpenSession(slot->slotID, CKF_SERIAL_SESSION,
                                         slot, pk11_notify, &session) != CKR_OK) {
        *owner = PR_FALSE;
        session = slot->session;
    }
    if (!slot->isThreadSafe)
        PK11_ExitSlotMonitor(slot);

    return session;
}

void
pk11_CloseSession(PK11SlotInfo *slot, CK_SESSION_HANDLE session, PRBool owner)
{
    if (!owner)
        return;
    if (!slot->isThreadSafe)
        PK11_EnterSlotMonitor(slot);
    (void)PK11_GETTAB(slot)->C_CloseSession(session);
    if (!slot->isThreadSafe)
        PK11_ExitSlotMonitor(slot);
}

SECStatus
PK11_CreateNewObject(PK11SlotInfo *slot, CK_SESSION_HANDLE session,
                     const CK_ATTRIBUTE *theTemplate, int count,
                     PRBool token, CK_OBJECT_HANDLE *objectID)
{
    CK_SESSION_HANDLE rwsession;
    CK_RV crv;
    SECStatus rv = SECSuccess;

    rwsession = session;
    if (token) {
        rwsession = PK11_GetRWSession(slot);
    } else if (rwsession == CK_INVALID_SESSION) {
        rwsession = slot->session;
        if (rwsession != CK_INVALID_SESSION)
            PK11_EnterSlotMonitor(slot);
    }
    if (rwsession == CK_INVALID_SESSION) {
        PORT_SetError(SEC_ERROR_BAD_DATA);
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_CreateObject(rwsession,
                                            /* cast away const :-( */ (CK_ATTRIBUTE_PTR)theTemplate,
                                            count, objectID);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        rv = SECFailure;
    }
    if (token) {
        PK11_RestoreROSession(slot, rwsession);
    } else if (session == CK_INVALID_SESSION) {
        PK11_ExitSlotMonitor(slot);
    }

    return rv;
}

/* This function may add a maximum of 9 attributes. */
unsigned int
pk11_OpFlagsToAttributes(CK_FLAGS flags, CK_ATTRIBUTE *attrs, CK_BBOOL *ckTrue)
{

    const static CK_ATTRIBUTE_TYPE attrTypes[12] = {
        CKA_ENCRYPT, CKA_DECRYPT, 0 /* DIGEST */, CKA_SIGN,
        CKA_SIGN_RECOVER, CKA_VERIFY, CKA_VERIFY_RECOVER, 0 /* GEN */,
        0 /* GEN PAIR */, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE
    };

    const CK_ATTRIBUTE_TYPE *pType = attrTypes;
    CK_ATTRIBUTE *attr = attrs;
    CK_FLAGS test = CKF_ENCRYPT;

    PR_ASSERT(!(flags & ~CKF_KEY_OPERATION_FLAGS));
    flags &= CKF_KEY_OPERATION_FLAGS;

    for (; flags && test <= CKF_DERIVE; test <<= 1, ++pType) {
        if (test & flags) {
            flags ^= test;
            PR_ASSERT(*pType);
            PK11_SETATTRS(attr, *pType, ckTrue, sizeof *ckTrue);
            ++attr;
        }
    }
    return (attr - attrs);
}

/*
 * Check for conflicting flags, for example, if both PK11_ATTR_PRIVATE
 * and PK11_ATTR_PUBLIC are set.
 */
PRBool
pk11_BadAttrFlags(PK11AttrFlags attrFlags)
{
    PK11AttrFlags trueFlags = attrFlags & 0x55555555;
    PK11AttrFlags falseFlags = (attrFlags >> 1) & 0x55555555;
    return ((trueFlags & falseFlags) != 0);
}

/*
 * This function may add a maximum of 5 attributes.
 * The caller must make sure the attribute flags don't have conflicts.
 */
unsigned int
pk11_AttrFlagsToAttributes(PK11AttrFlags attrFlags, CK_ATTRIBUTE *attrs,
                           CK_BBOOL *ckTrue, CK_BBOOL *ckFalse)
{
    const static CK_ATTRIBUTE_TYPE attrTypes[5] = {
        CKA_TOKEN, CKA_PRIVATE, CKA_MODIFIABLE, CKA_SENSITIVE,
        CKA_EXTRACTABLE
    };

    const CK_ATTRIBUTE_TYPE *pType = attrTypes;
    CK_ATTRIBUTE *attr = attrs;
    PK11AttrFlags test = PK11_ATTR_TOKEN;

    PR_ASSERT(!pk11_BadAttrFlags(attrFlags));

    /* we test two related bitflags in each iteration */
    for (; attrFlags && test <= PK11_ATTR_EXTRACTABLE; test <<= 2, ++pType) {
        if (test & attrFlags) {
            attrFlags ^= test;
            PK11_SETATTRS(attr, *pType, ckTrue, sizeof *ckTrue);
            ++attr;
        } else if ((test << 1) & attrFlags) {
            attrFlags ^= (test << 1);
            PK11_SETATTRS(attr, *pType, ckFalse, sizeof *ckFalse);
            ++attr;
        }
    }
    return (attr - attrs);
}

/*
 * Some non-compliant PKCS #11 vendors do not give us the modulus, so actually
 * set up a signature to get the signaure length.
 */
static int
pk11_backupGetSignLength(SECKEYPrivateKey *key)
{
    PK11SlotInfo *slot = key->pkcs11Slot;
    CK_MECHANISM mech = { 0, NULL, 0 };
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    CK_ULONG len;
    CK_RV crv;
    unsigned char h_data[20] = { 0 };
    unsigned char buf[20]; /* obviously to small */
    CK_ULONG smallLen = sizeof(buf);

    mech.mechanism = PK11_MapSignKeyType(key->keyType);

    session = pk11_GetNewSession(slot, &owner);
    if (!owner || !(slot->isThreadSafe))
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_SignInit(session, &mech, key->pkcs11ID);
    if (crv != CKR_OK) {
        if (!owner || !(slot->isThreadSafe))
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return -1;
    }
    len = 0;
    crv = PK11_GETTAB(slot)->C_Sign(session, h_data, sizeof(h_data),
                                    NULL, &len);
    /* now call C_Sign with too small a buffer to clear the session state */
    (void)PK11_GETTAB(slot)->C_Sign(session, h_data, sizeof(h_data), buf, &smallLen);

    if (!owner || !(slot->isThreadSafe))
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return -1;
    }
    return len;
}

/*
 * get the length of a signature object based on the key
 */
int
PK11_SignatureLen(SECKEYPrivateKey *key)
{
    int val;
    SECItem attributeItem = { siBuffer, NULL, 0 };
    SECStatus rv;
    int length;

    switch (key->keyType) {
        case rsaKey:
            val = PK11_GetPrivateModulusLen(key);
            if (val == -1) {
                return pk11_backupGetSignLength(key);
            }
            return (unsigned long)val;

        case fortezzaKey:
            return 40;

        case dsaKey:
            rv = PK11_ReadAttribute(key->pkcs11Slot, key->pkcs11ID, CKA_SUBPRIME,
                                    NULL, &attributeItem);
            if (rv == SECSuccess) {
                length = attributeItem.len;
                if ((length > 0) && attributeItem.data[0] == 0) {
                    length--;
                }
                PORT_Free(attributeItem.data);
                return length * 2;
            }
            return pk11_backupGetSignLength(key);

        case ecKey:
            rv = PK11_ReadAttribute(key->pkcs11Slot, key->pkcs11ID, CKA_EC_PARAMS,
                                    NULL, &attributeItem);
            if (rv == SECSuccess) {
                length = SECKEY_ECParamsToBasePointOrderLen(&attributeItem);
                PORT_Free(attributeItem.data);
                if (length != 0) {
                    length = ((length + 7) / 8) * 2;
                    return length;
                }
            }
            return pk11_backupGetSignLength(key);
        default:
            break;
    }
    PORT_SetError(SEC_ERROR_INVALID_KEY);
    return 0;
}

/*
 * copy a key (or any other object) on a token
 */
CK_OBJECT_HANDLE
PK11_CopyKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE srcObject)
{
    CK_OBJECT_HANDLE destObject;
    CK_RV crv;

    PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_CopyObject(slot->session, srcObject, NULL, 0,
                                          &destObject);
    PK11_ExitSlotMonitor(slot);
    if (crv == CKR_OK)
        return destObject;
    PORT_SetError(PK11_MapError(crv));
    return CK_INVALID_HANDLE;
}

PRBool
pk11_FindAttrInTemplate(CK_ATTRIBUTE *attr, unsigned int numAttrs,
                        CK_ATTRIBUTE_TYPE target)
{
    for (; numAttrs > 0; ++attr, --numAttrs) {
        if (attr->type == target)
            return PR_TRUE;
    }
    return PR_FALSE;
}

/*
 * Recover the Signed data. We need this because our old verify can't
 * figure out which hash algorithm to use until we decryptted this.
 */
SECStatus
PK11_VerifyRecover(SECKEYPublicKey *key, const SECItem *sig,
                   SECItem *dsig, void *wincx)
{
    PK11SlotInfo *slot = key->pkcs11Slot;
    CK_OBJECT_HANDLE id = key->pkcs11ID;
    CK_MECHANISM mech = { 0, NULL, 0 };
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    CK_ULONG len;
    CK_RV crv;

    mech.mechanism = PK11_MapSignKeyType(key->keyType);

    if (slot == NULL) {
        slot = PK11_GetBestSlotWithAttributes(mech.mechanism,
                                              CKF_VERIFY_RECOVER, 0, wincx);
        if (slot == NULL) {
            PORT_SetError(SEC_ERROR_NO_MODULE);
            return SECFailure;
        }
        id = PK11_ImportPublicKey(slot, key, PR_FALSE);
    } else {
        PK11_ReferenceSlot(slot);
    }

    if (id == CK_INVALID_HANDLE) {
        PK11_FreeSlot(slot);
        PORT_SetError(SEC_ERROR_BAD_KEY);
        return SECFailure;
    }

    session = pk11_GetNewSession(slot, &owner);
    if (!owner || !(slot->isThreadSafe))
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_VerifyRecoverInit(session, &mech, id);
    if (crv != CKR_OK) {
        if (!owner || !(slot->isThreadSafe))
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        PK11_FreeSlot(slot);
        return SECFailure;
    }
    len = dsig->len;
    crv = PK11_GETTAB(slot)->C_VerifyRecover(session, sig->data,
                                             sig->len, dsig->data, &len);
    if (!owner || !(slot->isThreadSafe))
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    dsig->len = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        PK11_FreeSlot(slot);
        return SECFailure;
    }
    PK11_FreeSlot(slot);
    return SECSuccess;
}

/*
 * verify a signature from its hash.
 */
SECStatus
PK11_Verify(SECKEYPublicKey *key, const SECItem *sig, const SECItem *hash,
            void *wincx)
{
    CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
    return PK11_VerifyWithMechanism(key, mech, NULL, sig, hash, wincx);
}

/*
 * Verify a signature from its hash using the given algorithm.
 */
SECStatus
PK11_VerifyWithMechanism(SECKEYPublicKey *key, CK_MECHANISM_TYPE mechanism,
                         const SECItem *param, const SECItem *sig,
                         const SECItem *hash, void *wincx)
{
    PK11SlotInfo *slot = key->pkcs11Slot;
    CK_OBJECT_HANDLE id = key->pkcs11ID;
    CK_MECHANISM mech = { 0, NULL, 0 };
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    CK_RV crv;

    mech.mechanism = mechanism;
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }

    if (slot == NULL) {
        unsigned int length = 0;
        if ((mech.mechanism == CKM_DSA) &&
            /* 129 is 1024 bits translated to bytes and
             * padded with an optional '0' to maintain a
             * positive sign */
            (key->u.dsa.params.prime.len > 129)) {
            /* we need to get a slot that not only can do DSA, but can do DSA2
             * key lengths */
            length = key->u.dsa.params.prime.len;
            if (key->u.dsa.params.prime.data[0] == 0) {
                length--;
            }
            /* convert keysize to bits for slot lookup */
            length *= 8;
        }
        slot = PK11_GetBestSlotWithAttributes(mech.mechanism,
                                              CKF_VERIFY, length, wincx);
        if (slot == NULL) {
            PORT_SetError(SEC_ERROR_NO_MODULE);
            return SECFailure;
        }
        id = PK11_ImportPublicKey(slot, key, PR_FALSE);

    } else {
        PK11_ReferenceSlot(slot);
    }

    if (id == CK_INVALID_HANDLE) {
        PK11_FreeSlot(slot);
        PORT_SetError(SEC_ERROR_BAD_KEY);
        return SECFailure;
    }

    session = pk11_GetNewSession(slot, &owner);
    if (!owner || !(slot->isThreadSafe))
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_VerifyInit(session, &mech, id);
    if (crv != CKR_OK) {
        if (!owner || !(slot->isThreadSafe))
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PK11_FreeSlot(slot);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_Verify(session, hash->data,
                                      hash->len, sig->data, sig->len);
    if (!owner || !(slot->isThreadSafe))
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    PK11_FreeSlot(slot);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

/*
 * sign a hash. The algorithm is determined by the key.
 */
SECStatus
PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, const SECItem *hash)
{
    CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
    return PK11_SignWithMechanism(key, mech, NULL, sig, hash);
}

/*
 * Sign a hash using the given algorithm.
 */
SECStatus
PK11_SignWithMechanism(SECKEYPrivateKey *key, CK_MECHANISM_TYPE mechanism,
                       const SECItem *param, SECItem *sig, const SECItem *hash)
{
    PK11SlotInfo *slot = key->pkcs11Slot;
    CK_MECHANISM mech = { 0, NULL, 0 };
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    PRBool haslock = PR_FALSE;
    CK_ULONG len;
    CK_RV crv;

    mech.mechanism = mechanism;
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }

    if (SECKEY_HAS_ATTRIBUTE_SET(key, CKA_PRIVATE)) {
        PK11_HandlePasswordCheck(slot, key->wincx);
    }

    session = pk11_GetNewSession(slot, &owner);
    haslock = (!owner || !(slot->isThreadSafe));
    if (haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_SignInit(session, &mech, key->pkcs11ID);
    if (crv != CKR_OK) {
        if (haslock)
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }

    /* PKCS11 2.20 says if CKA_ALWAYS_AUTHENTICATE then
     * do C_Login with CKU_CONTEXT_SPECIFIC
     * between C_SignInit and C_Sign */
    if (SECKEY_HAS_ATTRIBUTE_SET_LOCK(key, CKA_ALWAYS_AUTHENTICATE, haslock)) {
        PK11_DoPassword(slot, session, PR_FALSE, key->wincx, haslock, PR_TRUE);
    }

    len = sig->len;
    crv = PK11_GETTAB(slot)->C_Sign(session, hash->data,
                                    hash->len, sig->data, &len);
    if (haslock)
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    sig->len = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

/*
 * sign data with a MAC key.
 */
SECStatus
PK11_SignWithSymKey(PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism,
                    SECItem *param, SECItem *sig, const SECItem *data)
{
    PK11SlotInfo *slot = symKey->slot;
    CK_MECHANISM mech = { 0, NULL, 0 };
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    PRBool haslock = PR_FALSE;
    CK_ULONG len;
    CK_RV crv;

    mech.mechanism = mechanism;
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }

    session = pk11_GetNewSession(slot, &owner);
    haslock = (!owner || !(slot->isThreadSafe));
    if (haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_SignInit(session, &mech, symKey->objectID);
    if (crv != CKR_OK) {
        if (haslock)
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }

    len = sig->len;
    crv = PK11_GETTAB(slot)->C_Sign(session, data->data,
                                    data->len, sig->data, &len);
    if (haslock)
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    sig->len = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_Decrypt(PK11SymKey *symKey,
             CK_MECHANISM_TYPE mechanism, SECItem *param,
             unsigned char *out, unsigned int *outLen,
             unsigned int maxLen,
             const unsigned char *enc, unsigned encLen)
{
    PK11SlotInfo *slot = symKey->slot;
    CK_MECHANISM mech = { 0, NULL, 0 };
    CK_ULONG len = maxLen;
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    PRBool haslock = PR_FALSE;
    CK_RV crv;

    mech.mechanism = mechanism;
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }

    session = pk11_GetNewSession(slot, &owner);
    haslock = (!owner || !slot->isThreadSafe);
    if (haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_DecryptInit(session, &mech, symKey->objectID);
    if (crv != CKR_OK) {
        if (haslock)
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }

    crv = PK11_GETTAB(slot)->C_Decrypt(session, (unsigned char *)enc, encLen,
                                       out, &len);
    if (haslock)
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    *outLen = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_Encrypt(PK11SymKey *symKey,
             CK_MECHANISM_TYPE mechanism, SECItem *param,
             unsigned char *out, unsigned int *outLen,
             unsigned int maxLen,
             const unsigned char *data, unsigned int dataLen)
{
    PK11SlotInfo *slot = symKey->slot;
    CK_MECHANISM mech = { 0, NULL, 0 };
    CK_ULONG len = maxLen;
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    PRBool haslock = PR_FALSE;
    CK_RV crv;

    mech.mechanism = mechanism;
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }

    session = pk11_GetNewSession(slot, &owner);
    haslock = (!owner || !slot->isThreadSafe);
    if (haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_EncryptInit(session, &mech, symKey->objectID);
    if (crv != CKR_OK) {
        if (haslock)
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_Encrypt(session, (unsigned char *)data,
                                       dataLen, out, &len);
    if (haslock)
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    *outLen = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

static SECStatus
pk11_PrivDecryptRaw(SECKEYPrivateKey *key,
                    unsigned char *data, unsigned *outLen, unsigned int maxLen,
                    const unsigned char *enc, unsigned encLen,
                    CK_MECHANISM_PTR mech)
{
    PK11SlotInfo *slot = key->pkcs11Slot;
    CK_ULONG out = maxLen;
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    PRBool haslock = PR_FALSE;
    CK_RV crv;

    if (key->keyType != rsaKey) {
        PORT_SetError(SEC_ERROR_INVALID_KEY);
        return SECFailure;
    }

    /* Why do we do a PK11_handle check here? for simple
     * decryption? .. because the user may have asked for 'ask always'
     * and this is a private key operation. In practice, thought, it's mute
     * since only servers wind up using this function */
    if (SECKEY_HAS_ATTRIBUTE_SET(key, CKA_PRIVATE)) {
        PK11_HandlePasswordCheck(slot, key->wincx);
    }
    session = pk11_GetNewSession(slot, &owner);
    haslock = (!owner || !(slot->isThreadSafe));
    if (haslock)
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_DecryptInit(session, mech, key->pkcs11ID);
    if (crv != CKR_OK) {
        if (haslock)
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }

    /* PKCS11 2.20 says if CKA_ALWAYS_AUTHENTICATE then
     * do C_Login with CKU_CONTEXT_SPECIFIC
     * between C_DecryptInit and C_Decrypt
     * ... But see note above about servers */
    if (SECKEY_HAS_ATTRIBUTE_SET_LOCK(key, CKA_ALWAYS_AUTHENTICATE, haslock)) {
        PK11_DoPassword(slot, session, PR_FALSE, key->wincx, haslock, PR_TRUE);
    }

    crv = PK11_GETTAB(slot)->C_Decrypt(session, (unsigned char *)enc, encLen,
                                       data, &out);
    if (haslock)
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    *outLen = out;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_PubDecryptRaw(SECKEYPrivateKey *key,
                   unsigned char *data, unsigned *outLen, unsigned int maxLen,
                   const unsigned char *enc, unsigned encLen)
{
    CK_MECHANISM mech = { CKM_RSA_X_509, NULL, 0 };
    return pk11_PrivDecryptRaw(key, data, outLen, maxLen, enc, encLen, &mech);
}

SECStatus
PK11_PrivDecryptPKCS1(SECKEYPrivateKey *key,
                      unsigned char *data, unsigned *outLen, unsigned int maxLen,
                      const unsigned char *enc, unsigned encLen)
{
    CK_MECHANISM mech = { CKM_RSA_PKCS, NULL, 0 };
    return pk11_PrivDecryptRaw(key, data, outLen, maxLen, enc, encLen, &mech);
}

static SECStatus
pk11_PubEncryptRaw(SECKEYPublicKey *key,
                   unsigned char *out, unsigned int *outLen,
                   unsigned int maxLen,
                   const unsigned char *data, unsigned dataLen,
                   CK_MECHANISM_PTR mech, void *wincx)
{
    PK11SlotInfo *slot;
    CK_OBJECT_HANDLE id;
    CK_ULONG len = maxLen;
    PRBool owner = PR_TRUE;
    CK_SESSION_HANDLE session;
    CK_RV crv;

    slot = PK11_GetBestSlotWithAttributes(mech->mechanism, CKF_ENCRYPT, 0, wincx);
    if (slot == NULL) {
        PORT_SetError(SEC_ERROR_NO_MODULE);
        return SECFailure;
    }

    id = PK11_ImportPublicKey(slot, key, PR_FALSE);

    if (id == CK_INVALID_HANDLE) {
        PK11_FreeSlot(slot);
        PORT_SetError(SEC_ERROR_BAD_KEY);
        return SECFailure;
    }

    session = pk11_GetNewSession(slot, &owner);
    if (!owner || !(slot->isThreadSafe))
        PK11_EnterSlotMonitor(slot);
    crv = PK11_GETTAB(slot)->C_EncryptInit(session, mech, id);
    if (crv != CKR_OK) {
        if (!owner || !(slot->isThreadSafe))
            PK11_ExitSlotMonitor(slot);
        pk11_CloseSession(slot, session, owner);
        PK11_FreeSlot(slot);
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_Encrypt(session, (unsigned char *)data, dataLen,
                                       out, &len);
    if (!owner || !(slot->isThreadSafe))
        PK11_ExitSlotMonitor(slot);
    pk11_CloseSession(slot, session, owner);
    PK11_FreeSlot(slot);
    *outLen = len;
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_PubEncryptRaw(SECKEYPublicKey *key,
                   unsigned char *enc,
                   const unsigned char *data, unsigned dataLen,
                   void *wincx)
{
    CK_MECHANISM mech = { CKM_RSA_X_509, NULL, 0 };
    unsigned int outLen;
    if (!key || key->keyType != rsaKey) {
        PORT_SetError(SEC_ERROR_BAD_KEY);
        return SECFailure;
    }
    outLen = SECKEY_PublicKeyStrength(key);
    return pk11_PubEncryptRaw(key, enc, &outLen, outLen, data, dataLen, &mech,
                              wincx);
}

SECStatus
PK11_PubEncryptPKCS1(SECKEYPublicKey *key,
                     unsigned char *enc,
                     const unsigned char *data, unsigned dataLen,
                     void *wincx)
{
    CK_MECHANISM mech = { CKM_RSA_PKCS, NULL, 0 };
    unsigned int outLen;
    if (!key || key->keyType != rsaKey) {
        PORT_SetError(SEC_ERROR_BAD_KEY);
        return SECFailure;
    }
    outLen = SECKEY_PublicKeyStrength(key);
    return pk11_PubEncryptRaw(key, enc, &outLen, outLen, data, dataLen, &mech,
                              wincx);
}

SECStatus
PK11_PrivDecrypt(SECKEYPrivateKey *key,
                 CK_MECHANISM_TYPE mechanism, SECItem *param,
                 unsigned char *out, unsigned int *outLen,
                 unsigned int maxLen,
                 const unsigned char *enc, unsigned encLen)
{
    CK_MECHANISM mech = { mechanism, NULL, 0 };
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }
    return pk11_PrivDecryptRaw(key, out, outLen, maxLen, enc, encLen, &mech);
}

SECStatus
PK11_PubEncrypt(SECKEYPublicKey *key,
                CK_MECHANISM_TYPE mechanism, SECItem *param,
                unsigned char *out, unsigned int *outLen,
                unsigned int maxLen,
                const unsigned char *data, unsigned dataLen,
                void *wincx)
{
    CK_MECHANISM mech = { mechanism, NULL, 0 };
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    }
    return pk11_PubEncryptRaw(key, out, outLen, maxLen, data, dataLen, &mech,
                              wincx);
}

SECKEYPrivateKey *
PK11_UnwrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
                   CK_MECHANISM_TYPE wrapType, SECItem *param,
                   SECItem *wrappedKey, SECItem *label,
                   SECItem *idValue, PRBool perm, PRBool sensitive,
                   CK_KEY_TYPE keyType, CK_ATTRIBUTE_TYPE *usage,
                   int usageCount, void *wincx)
{
    CK_BBOOL cktrue = CK_TRUE;
    CK_BBOOL ckfalse = CK_FALSE;
    CK_OBJECT_CLASS keyClass = CKO_PRIVATE_KEY;
    CK_ATTRIBUTE keyTemplate[15];
    int templateCount = 0;
    CK_OBJECT_HANDLE privKeyID;
    CK_MECHANISM mechanism;
    CK_ATTRIBUTE *attrs = keyTemplate;
    SECItem *param_free = NULL, *ck_id = NULL;
    CK_RV crv;
    CK_SESSION_HANDLE rwsession;
    PK11SymKey *newKey = NULL;
    int i;

    if (!slot || !wrappedKey || !idValue) {
        /* SET AN ERROR!!! */
        return NULL;
    }

    ck_id = PK11_MakeIDFromPubKey(idValue);
    if (!ck_id) {
        return NULL;
    }

    PK11_SETATTRS(attrs, CKA_TOKEN, perm ? &cktrue : &ckfalse,
                  sizeof(cktrue));
    attrs++;
    PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
    attrs++;
    PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
    attrs++;
    PK11_SETATTRS(attrs, CKA_PRIVATE, sensitive ? &cktrue : &ckfalse,
                  sizeof(cktrue));
    attrs++;
    PK11_SETATTRS(attrs, CKA_SENSITIVE, sensitive ? &cktrue : &ckfalse,
                  sizeof(cktrue));
    attrs++;
    if (label && label->data) {
        PK11_SETATTRS(attrs, CKA_LABEL, label->data, label->len);
        attrs++;
    }
    PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len);
    attrs++;
    for (i = 0; i < usageCount; i++) {
        PK11_SETATTRS(attrs, usage[i], &cktrue, sizeof(cktrue));
        attrs++;
    }

    if (PK11_IsInternal(slot)) {
        PK11_SETATTRS(attrs, CKA_NETSCAPE_DB, idValue->data,
                      idValue->len);
        attrs++;
    }

    templateCount = attrs - keyTemplate;
    PR_ASSERT(templateCount <= (sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)));

    mechanism.mechanism = wrapType;
    if (!param)
        param = param_free = PK11_ParamFromIV(wrapType, NULL);
    if (param) {
        mechanism.pParameter = param->data;
        mechanism.ulParameterLen = param->len;
    } else {
        mechanism.pParameter = NULL;
        mechanism.ulParameterLen = 0;
    }

    if (wrappingKey->slot != slot) {
        newKey = pk11_CopyToSlot(slot, wrapType, CKA_UNWRAP, wrappingKey);
    } else {
        newKey = PK11_ReferenceSymKey(wrappingKey);
    }

    if (newKey) {
        if (perm) {
            /* Get RW Session will either lock the monitor if necessary,
             *  or return a thread safe session handle, or fail. */
            rwsession = PK11_GetRWSession(slot);
        } else {
            rwsession = slot->session;
            if (rwsession != CK_INVALID_SESSION)
                PK11_EnterSlotMonitor(slot);
        }
        /* This is a lot a work to deal with fussy PKCS #11 modules
         * that can't bother to return BAD_DATA when presented with an
         * invalid session! */
        if (rwsession == CK_INVALID_SESSION) {
            PORT_SetError(SEC_ERROR_BAD_DATA);
            goto loser;
        }
        crv = PK11_GETTAB(slot)->C_UnwrapKey(rwsession, &mechanism,
                                             newKey->objectID,
                                             wrappedKey->data,
                                             wrappedKey->len, keyTemplate,
                                             templateCount, &privKeyID);

        if (perm) {
            PK11_RestoreROSession(slot, rwsession);
        } else {
            PK11_ExitSlotMonitor(slot);
        }
        PK11_FreeSymKey(newKey);
        newKey = NULL;
    } else {
        crv = CKR_FUNCTION_NOT_SUPPORTED;
    }

    SECITEM_FreeItem(ck_id, PR_TRUE);
    ck_id = NULL;

    if (crv != CKR_OK) {
        /* we couldn't unwrap the key, use the internal module to do the
         * unwrap, then load the new key into the token */
        PK11SlotInfo *int_slot = PK11_GetInternalSlot();

        if (int_slot && (slot != int_slot)) {
            SECKEYPrivateKey *privKey = PK11_UnwrapPrivKey(int_slot,
                                                           wrappingKey, wrapType, param, wrappedKey, label,
                                                           idValue, PR_FALSE, PR_FALSE,
                                                           keyType, usage, usageCount, wincx);
            if (privKey) {
                SECKEYPrivateKey *newPrivKey = PK11_LoadPrivKey(slot, privKey,
                                                                NULL, perm, sensitive);
                SECKEY_DestroyPrivateKey(privKey);
                PK11_FreeSlot(int_slot);
                return newPrivKey;
            }
        }
        if (int_slot)
            PK11_FreeSlot(int_slot);
        PORT_SetError(PK11_MapError(crv));
        return NULL;
    }
    return PK11_MakePrivKey(slot, nullKey, PR_FALSE, privKeyID, wincx);

loser:
    if (newKey) {
        PK11_FreeSymKey(newKey);
    }
    if (ck_id) {
        SECITEM_FreeItem(ck_id, PR_TRUE);
    }
    return NULL;
}

/*
 * Now we're going to wrap a SECKEYPrivateKey with a PK11SymKey
 * The strategy is to get both keys to reside in the same slot,
 * one that can perform the desired crypto mechanism and then
 * call C_WrapKey after all the setup has taken place.
 */
SECStatus
PK11_WrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
                 SECKEYPrivateKey *privKey, CK_MECHANISM_TYPE wrapType,
                 SECItem *param, SECItem *wrappedKey, void *wincx)
{
    PK11SlotInfo *privSlot = privKey->pkcs11Slot; /* The slot where
                                                   * the private key
                                                   * we are going to
                                                   * wrap lives.
                                                   */
    PK11SymKey *newSymKey = NULL;
    SECKEYPrivateKey *newPrivKey = NULL;
    SECItem *param_free = NULL;
    CK_ULONG len = wrappedKey->len;
    CK_MECHANISM mech;
    CK_RV crv;

    if (!privSlot || !PK11_DoesMechanism(privSlot, wrapType)) {
        /* Figure out a slot that does the mechanism and try to import
         * the private key onto that slot.
         */
        PK11SlotInfo *int_slot = PK11_GetInternalSlot();

        privSlot = int_slot; /* The private key has a new home */
        newPrivKey = PK11_LoadPrivKey(privSlot, privKey, NULL, PR_FALSE, PR_FALSE);
        /* newPrivKey has allocated its own reference to the slot, so it's
         * safe until we destroy newPrivkey.
         */
        PK11_FreeSlot(int_slot);
        if (newPrivKey == NULL) {
            return SECFailure;
        }
        privKey = newPrivKey;
    }

    if (privSlot != wrappingKey->slot) {
        newSymKey = pk11_CopyToSlot(privSlot, wrapType, CKA_WRAP,
                                    wrappingKey);
        wrappingKey = newSymKey;
    }

    if (wrappingKey == NULL) {
        if (newPrivKey) {
            SECKEY_DestroyPrivateKey(newPrivKey);
        }
        return SECFailure;
    }
    mech.mechanism = wrapType;
    if (!param) {
        param = param_free = PK11_ParamFromIV(wrapType, NULL);
    }
    if (param) {
        mech.pParameter = param->data;
        mech.ulParameterLen = param->len;
    } else {
        mech.pParameter = NULL;
        mech.ulParameterLen = 0;
    }

    PK11_EnterSlotMonitor(privSlot);
    crv = PK11_GETTAB(privSlot)->C_WrapKey(privSlot->session, &mech,
                                           wrappingKey->objectID,
                                           privKey->pkcs11ID,
                                           wrappedKey->data, &len);
    PK11_ExitSlotMonitor(privSlot);

    if (newSymKey) {
        PK11_FreeSymKey(newSymKey);
    }
    if (newPrivKey) {
        SECKEY_DestroyPrivateKey(newPrivKey);
    }
    if (param_free) {
        SECITEM_FreeItem(param_free, PR_TRUE);
    }

    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }

    wrappedKey->len = len;
    return SECSuccess;
}

#if 0
/*
 * Sample code relating to linked list returned by PK11_FindGenericObjects
 */

/*
 * You can walk the list with the following code:
 */
    firstObj = PK11_FindGenericObjects(slot, objClass);
    for (thisObj=firstObj;
         thisObj;
         thisObj=PK11_GetNextGenericObject(thisObj)) {
        /* operate on thisObj */
    }
/*
 * If you want a particular object from the list...
 */
    firstObj = PK11_FindGenericObjects(slot, objClass);
    for (thisObj=firstObj;
         thisObj;
         thisObj=PK11_GetNextGenericObject(thisObj)) {
      if (isMyObj(thisObj)) {
       if ( thisObj == firstObj) {
                /* NOTE: firstObj could be NULL at this point */
      firstObj = PK11_GetNextGenericObject(thsObj);
       }
       PK11_UnlinkGenericObject(thisObj);
            myObj = thisObj;
            break;
        }
    }

    PK11_DestroyGenericObjects(firstObj);

      /* use myObj */

    PK11_DestroyGenericObject(myObj);
#endif /* sample code */

/*
 * return a linked, non-circular list of generic objects.
 * If you are only interested
 * in one object, just use the first object in the list. To find the
 * rest of the list use PK11_GetNextGenericObject() to return the next object.
 */
PK11GenericObject *
PK11_FindGenericObjects(PK11SlotInfo *slot, CK_OBJECT_CLASS objClass)
{
    CK_ATTRIBUTE template[1];
    CK_ATTRIBUTE *attrs = template;
    CK_OBJECT_HANDLE *objectIDs = NULL;
    PK11GenericObject *lastObj = NULL, *obj;
    PK11GenericObject *firstObj = NULL;
    int i, count = 0;

    PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass));
    attrs++;

    objectIDs = pk11_FindObjectsByTemplate(slot, template, 1, &count);
    if (objectIDs == NULL) {
        return NULL;
    }

    /* where we connect our object once we've created it.. */
    for (i = 0; i < count; i++) {
        obj = PORT_New(PK11GenericObject);
        if (!obj) {
            if (firstObj) {
                PK11_DestroyGenericObjects(firstObj);
            }
            PORT_Free(objectIDs);
            return NULL;
        }
        /* initialize it */
        obj->slot = PK11_ReferenceSlot(slot);
        obj->objectID = objectIDs[i];
        obj->owner = PR_FALSE;
        obj->next = NULL;
        obj->prev = NULL;

        /* link it in */
        if (firstObj == NULL) {
            firstObj = obj;
        } else {
            PK11_LinkGenericObject(lastObj, obj);
        }
        lastObj = obj;
    }
    PORT_Free(objectIDs);
    return firstObj;
}

/*
 * get the Next Object in the list.
 */
PK11GenericObject *
PK11_GetNextGenericObject(PK11GenericObject *object)
{
    return object->next;
}

PK11GenericObject *
PK11_GetPrevGenericObject(PK11GenericObject *object)
{
    return object->prev;
}

/*
 * Link a single object into a new list.
 * if the object is already in another list, remove it first.
 */
SECStatus
PK11_LinkGenericObject(PK11GenericObject *list, PK11GenericObject *object)
{
    PK11_UnlinkGenericObject(object);
    object->prev = list;
    object->next = list->next;
    list->next = object;
    if (object->next != NULL) {
        object->next->prev = object;
    }
    return SECSuccess;
}

/*
 * remove an object from the list. If the object isn't already in
 * a list unlink becomes a noop.
 */
SECStatus
PK11_UnlinkGenericObject(PK11GenericObject *object)
{
    if (object->prev != NULL) {
        object->prev->next = object->next;
    }
    if (object->next != NULL) {
        object->next->prev = object->prev;
    }

    object->next = NULL;
    object->prev = NULL;
    return SECSuccess;
}

/*
 * This function removes a single object from the list and destroys it.
 * For an already unlinked object there is no difference between
 * PK11_DestroyGenericObject and PK11_DestroyGenericObjects
 */
SECStatus
PK11_DestroyGenericObject(PK11GenericObject *object)
{
    if (object == NULL) {
        return SECSuccess;
    }

    PK11_UnlinkGenericObject(object);
    if (object->slot) {
        if (object->owner) {
            PK11_DestroyObject(object->slot, object->objectID);
        }
        PK11_FreeSlot(object->slot);
    }
    PORT_Free(object);
    return SECSuccess;
}

/*
 * walk down a link list of generic objects destroying them.
 * This will destroy all objects in a list that the object is linked into.
 * (the list is traversed in both directions).
 */
SECStatus
PK11_DestroyGenericObjects(PK11GenericObject *objects)
{
    PK11GenericObject *nextObject;
    PK11GenericObject *prevObject;

    if (objects == NULL) {
        return SECSuccess;
    }

    nextObject = objects->next;
    prevObject = objects->prev;

    /* delete all the objects after it in the list */
    for (; objects; objects = nextObject) {
        nextObject = objects->next;
        PK11_DestroyGenericObject(objects);
    }
    /* delete all the objects before it in the list */
    for (objects = prevObject; objects; objects = prevObject) {
        prevObject = objects->prev;
        PK11_DestroyGenericObject(objects);
    }
    return SECSuccess;
}

/*
 * Hand Create a new object and return the Generic object for our new object.
 */
PK11GenericObject *
pk11_CreateGenericObjectHelper(PK11SlotInfo *slot,
                               const CK_ATTRIBUTE *pTemplate,
                               int count, PRBool token, PRBool owner)
{
    CK_OBJECT_HANDLE objectID;
    PK11GenericObject *obj;
    CK_RV crv;

    PK11_EnterSlotMonitor(slot);
    crv = PK11_CreateNewObject(slot, slot->session, pTemplate, count,
                               token, &objectID);
    PK11_ExitSlotMonitor(slot);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return NULL;
    }

    obj = PORT_New(PK11GenericObject);
    if (!obj) {
        /* error set by PORT_New */
        return NULL;
    }

    /* initialize it */
    obj->slot = PK11_ReferenceSlot(slot);
    obj->objectID = objectID;
    obj->owner = owner;
    obj->next = NULL;
    obj->prev = NULL;
    return obj;
}

/* This is the classic interface. Applications would call this function to
 * create new object that would not be destroyed later. This lead to resource
 * leaks (and thus memory leaks in the PKCS #11 module).  To solve this we have
 * a new interface that automatically marks objects created on the fly to be 
 * destroyed later. 
 * The old interface is preserved because applications like Mozilla purposefully
 * leak the reference to be found later with PK11_FindGenericObjects. New 
 * applications should use the new interface PK11_CreateManagedGenericObject */
PK11GenericObject *
PK11_CreateGenericObject(PK11SlotInfo *slot, const CK_ATTRIBUTE *pTemplate,
                         int count, PRBool token)
{
    return pk11_CreateGenericObjectHelper(slot, pTemplate, count, token,
                                          PR_FALSE);
}

/* Use this interface. It will automatically destroy any temporary objects 
 * (token = PR_FALSE) when the PK11GenericObject is freed. Permanent objects still 
 * need to be destroyed by hand with PK11_DestroyTokenObject.
 */
PK11GenericObject *
PK11_CreateManagedGenericObject(PK11SlotInfo *slot,
                                const CK_ATTRIBUTE *pTemplate, int count, PRBool token)
{
    return pk11_CreateGenericObjectHelper(slot, pTemplate, count, token,
                                          !token);
}

/*
 * Change an attribute on a raw object
 */
SECStatus
PK11_WriteRawAttribute(PK11ObjectType objType, void *objSpec,
                       CK_ATTRIBUTE_TYPE attrType, SECItem *item)
{
    PK11SlotInfo *slot = NULL;
    CK_OBJECT_HANDLE handle = 0;
    CK_ATTRIBUTE setTemplate;
    CK_RV crv;
    CK_SESSION_HANDLE rwsession;

    switch (objType) {
        case PK11_TypeGeneric:
            slot = ((PK11GenericObject *)objSpec)->slot;
            handle = ((PK11GenericObject *)objSpec)->objectID;
            break;
        case PK11_TypePrivKey:
            slot = ((SECKEYPrivateKey *)objSpec)->pkcs11Slot;
            handle = ((SECKEYPrivateKey *)objSpec)->pkcs11ID;
            break;
        case PK11_TypePubKey:
            slot = ((SECKEYPublicKey *)objSpec)->pkcs11Slot;
            handle = ((SECKEYPublicKey *)objSpec)->pkcs11ID;
            break;
        case PK11_TypeSymKey:
            slot = ((PK11SymKey *)objSpec)->slot;
            handle = ((PK11SymKey *)objSpec)->objectID;
            break;
        case PK11_TypeCert: /* don't handle cert case for now */
        default:
            break;
    }
    if (slot == NULL) {
        PORT_SetError(SEC_ERROR_UNKNOWN_OBJECT_TYPE);
        return SECFailure;
    }

    PK11_SETATTRS(&setTemplate, attrType, (CK_CHAR *)item->data, item->len);
    rwsession = PK11_GetRWSession(slot);
    if (rwsession == CK_INVALID_SESSION) {
        PORT_SetError(SEC_ERROR_BAD_DATA);
        return SECFailure;
    }
    crv = PK11_GETTAB(slot)->C_SetAttributeValue(rwsession, handle,
                                                 &setTemplate, 1);
    PK11_RestoreROSession(slot, rwsession);
    if (crv != CKR_OK) {
        PORT_SetError(PK11_MapError(crv));
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
PK11_ReadRawAttribute(PK11ObjectType objType, void *objSpec,
                      CK_ATTRIBUTE_TYPE attrType, SECItem *item)
{
    PK11SlotInfo *slot = NULL;
    CK_OBJECT_HANDLE handle = 0;

    switch (objType) {
        case PK11_TypeGeneric:
            slot = ((PK11GenericObject *)objSpec)->slot;
            handle = ((PK11GenericObject *)objSpec)->objectID;
            break;
        case PK11_TypePrivKey:
            slot = ((SECKEYPrivateKey *)objSpec)->pkcs11Slot;
            handle = ((SECKEYPrivateKey *)objSpec)->pkcs11ID;
            break;
        case PK11_TypePubKey:
            slot = ((SECKEYPublicKey *)objSpec)->pkcs11Slot;
            handle = ((SECKEYPublicKey *)objSpec)->pkcs11ID;
            break;
        case PK11_TypeSymKey:
            slot = ((PK11SymKey *)objSpec)->slot;
            handle = ((PK11SymKey *)objSpec)->objectID;
            break;
        case PK11_TypeCert: /* don't handle cert case for now */
        default:
            break;
    }
    if (slot == NULL) {
        PORT_SetError(SEC_ERROR_UNKNOWN_OBJECT_TYPE);
        return SECFailure;
    }

    return PK11_ReadAttribute(slot, handle, attrType, NULL, item);
}

/*
 * return the object handle that matches the template
 */
CK_OBJECT_HANDLE
pk11_FindObjectByTemplate(PK11SlotInfo *slot, CK_ATTRIBUTE *theTemplate, int tsize)
{
    CK_OBJECT_HANDLE object;
    CK_RV crv = CKR_SESSION_HANDLE_INVALID;
    CK_ULONG objectCount;

    /*
     * issue the find
     */
    PK11_EnterSlotMonitor(slot);
    if (slot->session != CK_INVALID_SESSION) {
        crv = PK11_GETTAB(slot)->C_FindObjectsInit(slot->session,
                                                   theTemplate, tsize);
    }
    if (crv != CKR_OK) {
        PK11_ExitSlotMonitor(slot);
        PORT_SetError(PK11_MapError(crv));
        return CK_INVALID_HANDLE;
    }

    crv = PK11_GETTAB(slot)->C_FindObjects(slot->session, &object, 1, &objectCount);
    PK11_GETTAB(slot)->C_FindObjectsFinal(slot->session);
    PK11_ExitSlotMonitor(slot);
    if ((crv != CKR_OK) || (objectCount < 1)) {
        /* shouldn't use SSL_ERROR... here */
        PORT_SetError(crv != CKR_OK ? PK11_MapError(crv) : SSL_ERROR_NO_CERTIFICATE);
        return CK_INVALID_HANDLE;
    }

    /* blow up if the PKCS #11 module returns us and invalid object handle */
    PORT_Assert(object != CK_INVALID_HANDLE);
    return object;
}

/*
 * return all the object handles that matches the template
 */
CK_OBJECT_HANDLE *
pk11_FindObjectsByTemplate(PK11SlotInfo *slot, CK_ATTRIBUTE *findTemplate,
                           int templCount, int *object_count)
{
    CK_OBJECT_HANDLE *objID = NULL;
    CK_ULONG returned_count = 0;
    CK_RV crv = CKR_SESSION_HANDLE_INVALID;

    PK11_EnterSlotMonitor(slot);
    if (slot->session != CK_INVALID_SESSION) {
        crv = PK11_GETTAB(slot)->C_FindObjectsInit(slot->session,
                                                   findTemplate, templCount);
    }
    if (crv != CKR_OK) {
        PK11_ExitSlotMonitor(slot);
        PORT_SetError(PK11_MapError(crv));
        *object_count = -1;
        return NULL;
    }

    /*
     * collect all the Matching Objects
     */
    do {
        CK_OBJECT_HANDLE *oldObjID = objID;

        if (objID == NULL) {
            objID = (CK_OBJECT_HANDLE *)PORT_Alloc(sizeof(CK_OBJECT_HANDLE) *
                                                   (*object_count + PK11_SEARCH_CHUNKSIZE));
        } else {
            objID = (CK_OBJECT_HANDLE *)PORT_Realloc(objID,
                                                     sizeof(CK_OBJECT_HANDLE) * (*object_count + PK11_SEARCH_CHUNKSIZE));
        }

        if (objID == NULL) {
            if (oldObjID)
                PORT_Free(oldObjID);
            break;
        }
        crv = PK11_GETTAB(slot)->C_FindObjects(slot->session,
                                               &objID[*object_count], PK11_SEARCH_CHUNKSIZE, &returned_count);
        if (crv != CKR_OK) {
            PORT_SetError(PK11_MapError(crv));
            PORT_Free(objID);
            objID = NULL;
            break;
        }
        *object_count += returned_count;
    } while (returned_count == PK11_SEARCH_CHUNKSIZE);

    PK11_GETTAB(slot)->C_FindObjectsFinal(slot->session);
    PK11_ExitSlotMonitor(slot);

    if (objID && (*object_count == 0)) {
        PORT_Free(objID);
        return NULL;
    }
    if (objID == NULL)
        *object_count = -1;
    return objID;
}
/*
 * given a PKCS #11 object, match it's peer based on the KeyID. searchID
 * is typically a privateKey or a certificate while the peer is the opposite
 */
CK_OBJECT_HANDLE
PK11_MatchItem(PK11SlotInfo *slot, CK_OBJECT_HANDLE searchID,
               CK_OBJECT_CLASS matchclass)
{
    CK_ATTRIBUTE theTemplate[] = {
        { CKA_ID, NULL, 0 },
        { CKA_CLASS, NULL, 0 }
    };
    /* if you change the array, change the variable below as well */
    CK_ATTRIBUTE *keyclass = &theTemplate[1];
    int tsize = sizeof(theTemplate) / sizeof(theTemplate[0]);
    /* if you change the array, change the variable below as well */
    CK_OBJECT_HANDLE peerID;
    PORTCheapArenaPool tmpArena;
    CK_RV crv;

    /* now we need to create space for the public key */
    PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE);

    crv = PK11_GetAttributes(&tmpArena.arena, slot, searchID, theTemplate, tsize);
    if (crv != CKR_OK) {
        PORT_DestroyCheapArena(&tmpArena);
        PORT_SetError(PK11_MapError(crv));
        return CK_INVALID_HANDLE;
    }

    if ((theTemplate[0].ulValueLen == 0) || (theTemplate[0].ulValueLen == -1)) {
        PORT_DestroyCheapArena(&tmpArena);
        if (matchclass == CKO_CERTIFICATE)
            PORT_SetError(SEC_ERROR_BAD_KEY);
        else
            PORT_SetError(SEC_ERROR_NO_KEY);
        return CK_INVALID_HANDLE;
    }

    /*
     * issue the find
     */
    *(CK_OBJECT_CLASS *)(keyclass->pValue) = matchclass;

    peerID = pk11_FindObjectByTemplate(slot, theTemplate, tsize);
    PORT_DestroyCheapArena(&tmpArena);

    return peerID;
}

/*
 * count the number of objects that match the template.
 */
int
PK11_NumberObjectsFor(PK11SlotInfo *slot, CK_ATTRIBUTE *findTemplate,
                      int templCount)
{
    CK_OBJECT_HANDLE objID[PK11_SEARCH_CHUNKSIZE];
    int object_count = 0;
    CK_ULONG returned_count = 0;
    CK_RV crv = CKR_SESSION_HANDLE_INVALID;

    PK11_EnterSlotMonitor(slot);
    if (slot->session != CK_INVALID_SESSION) {
        crv = PK11_GETTAB(slot)->C_FindObjectsInit(slot->session,
                                                   findTemplate, templCount);
    }
    if (crv != CKR_OK) {
        PK11_ExitSlotMonitor(slot);
        PORT_SetError(PK11_MapError(crv));
        return object_count;
    }

    /*
     * collect all the Matching Objects
     */
    do {
        crv = PK11_GETTAB(slot)->C_FindObjects(slot->session, objID,
                                               PK11_SEARCH_CHUNKSIZE,
                                               &returned_count);
        if (crv != CKR_OK) {
            PORT_SetError(PK11_MapError(crv));
            break;
        }
        object_count += returned_count;
    } while (returned_count == PK11_SEARCH_CHUNKSIZE);

    PK11_GETTAB(slot)->C_FindObjectsFinal(slot->session);
    PK11_ExitSlotMonitor(slot);
    return object_count;
}

/*
 * Traverse all the objects in a given slot.
 */
SECStatus
PK11_TraverseSlot(PK11SlotInfo *slot, void *arg)
{
    int i;
    CK_OBJECT_HANDLE *objID = NULL;
    int object_count = 0;
    pk11TraverseSlot *slotcb = (pk11TraverseSlot *)arg;

    objID = pk11_FindObjectsByTemplate(slot, slotcb->findTemplate,
                                       slotcb->templateCount, &object_count);

    /*Actually this isn't a failure... there just were no objs to be found*/
    if (object_count == 0) {
        return SECSuccess;
    }

    if (objID == NULL) {
        return SECFailure;
    }

    for (i = 0; i < object_count; i++) {
        (*slotcb->callback)(slot, objID[i], slotcb->callbackArg);
    }
    PORT_Free(objID);
    return SECSuccess;
}

/*
 * Traverse all the objects in all slots.
 */
SECStatus
pk11_TraverseAllSlots(SECStatus (*callback)(PK11SlotInfo *, void *),
                      void *arg, PRBool forceLogin, void *wincx)
{
    PK11SlotList *list;
    PK11SlotListElement *le;
    SECStatus rv;

    /* get them all! */
    list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, wincx);
    if (list == NULL)
        return SECFailure;

    /* look at each slot and authenticate as necessary */
    for (le = list->head; le; le = le->next) {
        if (forceLogin) {
            rv = pk11_AuthenticateUnfriendly(le->slot, PR_FALSE, wincx);
            if (rv != SECSuccess) {
                continue;
            }
        }
        if (callback) {
            (*callback)(le->slot, arg);
        }
    }

    PK11_FreeSlotList(list);

    return SECSuccess;
}

CK_OBJECT_HANDLE *
PK11_FindObjectsFromNickname(char *nickname, PK11SlotInfo **slotptr,
                             CK_OBJECT_CLASS objclass, int *returnCount, void *wincx)
{
    char *tokenName;
    char *delimit;
    PK11SlotInfo *slot;
    CK_OBJECT_HANDLE *objID;
    CK_ATTRIBUTE findTemplate[] = {
        { CKA_LABEL, NULL, 0 },
        { CKA_CLASS, NULL, 0 },
    };
    int findCount = sizeof(findTemplate) / sizeof(findTemplate[0]);
    SECStatus rv;
    PK11_SETATTRS(&findTemplate[1], CKA_CLASS, &objclass, sizeof(objclass));

    *slotptr = slot = NULL;
    *returnCount = 0;
    /* first find the slot associated with this nickname */
    if ((delimit = PORT_Strchr(nickname, ':')) != NULL) {
        int len = delimit - nickname;
        tokenName = (char *)PORT_Alloc(len + 1);
        if (!tokenName) {
            return CK_INVALID_HANDLE;
        }
        PORT_Memcpy(tokenName, nickname, len);
        tokenName[len] = 0;

        slot = *slotptr = PK11_FindSlotByName(tokenName);
        PORT_Free(tokenName);
        /* if we couldn't find a slot, assume the nickname is an internal cert
         * with no proceding slot name */
        if (slot == NULL) {
            slot = *slotptr = PK11_GetInternalKeySlot();
        } else {
            nickname = delimit + 1;
        }
    } else {
        *slotptr = slot = PK11_GetInternalKeySlot();
    }
    if (slot == NULL) {
        return CK_INVALID_HANDLE;
    }

    rv = pk11_AuthenticateUnfriendly(slot, PR_TRUE, wincx);
    if (rv != SECSuccess) {
        PK11_FreeSlot(slot);
        *slotptr = NULL;
        return CK_INVALID_HANDLE;
    }

    findTemplate[0].pValue = nickname;
    findTemplate[0].ulValueLen = PORT_Strlen(nickname);
    objID = pk11_FindObjectsByTemplate(slot, findTemplate, findCount, returnCount);
    if (objID == NULL) {
        /* PKCS #11 isn't clear on whether or not the NULL is
         * stored in the template.... try the find again with the
         * full null terminated string. */
        findTemplate[0].ulValueLen += 1;
        objID = pk11_FindObjectsByTemplate(slot, findTemplate, findCount,
                                           returnCount);
        if (objID == NULL) {
            /* Well that's the best we can do. It's just not here */
            /* what about faked nicknames? */
            PK11_FreeSlot(slot);
            *slotptr = NULL;
            *returnCount = 0;
        }
    }

    return objID;
}

SECItem *
pk11_GetLowLevelKeyFromHandle(PK11SlotInfo *slot, CK_OBJECT_HANDLE handle)
{
    CK_ATTRIBUTE theTemplate[] = {
        { CKA_ID, NULL, 0 },
    };
    int tsize = sizeof(theTemplate) / sizeof(theTemplate[0]);
    CK_RV crv;
    SECItem *item;

    item = SECITEM_AllocItem(NULL, NULL, 0);

    if (item == NULL) {
        return NULL;
    }

    crv = PK11_GetAttributes(NULL, slot, handle, theTemplate, tsize);
    if (crv != CKR_OK) {
        SECITEM_FreeItem(item, PR_TRUE);
        PORT_SetError(PK11_MapError(crv));
        return NULL;
    }

    item->data = (unsigned char *)theTemplate[0].pValue;
    item->len = theTemplate[0].ulValueLen;

    return item;
}