|
root / base / usr / src / lib / libcryptoutil
libcryptoutil Plain Text 4466 lines 121.5 KB
   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
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

include $(SRC)/lib/Makefile.lib

HDRS=	cryptoutil.h
HDRDIR=         common
# Hammerhead: amd64-only
SUBDIRS = $(MACH64)

all :		TARGET= all
clean :	TARGET= clean
clobber :	TARGET= clobber
install :	TARGET= install

.KEEP_STATE:

all clean clobber install: $(SUBDIRS)

install_h:	$(ROOTHDRS)

check:  $(CHECKHDRS)

$(SUBDIRS):	FRC
	@cd $@; pwd; $(MAKE) $(TARGET)

FRC:

include $(SRC)/lib/Makefile.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
#
# Copyright (c) 2018, Joyent, Inc.

LIBRARY= libcryptoutil.a
VERS=	.1

OBJECTS= \
	debug.o \
	mechstr.o \
	config_parsing.o \
	tohexstr.o \
	mechkeygen.o \
	mechkeytype.o \
	pkcserror.o \
	passutils.o \
	random.o \
	keyfile.o \
	util.o \
	pkcs11_uri.o

include $(SRC)/lib/Makefile.lib
include $(SRC)/lib/Makefile.rootfs

SRCDIR=	../common

LIBS =	$(DYNLIB)
LDLIBS += -lc

CFLAGS +=	$(CCVERBOSE)
CPPFLAGS +=	-D_REENTRANT -D_POSIX_PTHREAD_SEMANTICS -I$(SRCDIR)

CERRWARN +=	-Wno-parentheses
CERRWARN +=	$(CNOWARN_UNINIT)

# not linted
SMATCH=off

all: $(LIBS)


include $(SRC)/lib/Makefile.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
#

This is an internal library for use only by:
	usr/src/cmd/cmd-crypto
	usr/src/lib/pkcs11
	usr/src/lib/libkmf

The library and the header file are installed into the proto area but
are not included in any pacakges.


			libcryptoutil Design

1. Introduction

There are a number of common code components and general utility functions
needed that are shared by various userland parts of the crypto framework.

The originally approved ARC materials (PSARC/2001/488 & PSARC/2001/553)
didn't have a library that was included by all user land libraries,
plugins and commands.

The solution to this is to follow what other project teams have done in the
past and create a project private util library.

2. Contents

Any code that is generic enough to be shared by multiple parts of the
user crypto framework is eligible.

The current contents are:

2.1 Error & Debug Functions

	cryptodebug_init(),
	cryptodebug()
	cryptoerror()

These functions log debug or error information to stderr and/or
syslog or a file.  Debug is off by default but the code is always
compiled in.

The cryptodebug_init() routine allows the caller to set a message
prefix for error and debug output.

The environment variable SUNW_CRYPTO_DEBUG determines wither or not
debug output is generated at run time, valid values are "syslog" or "stderr"

For example elfsign(1) could do:

	cryptodebug_init("elfsign");

and later:
	cryptoerror(LOG_STDERR, gettext("invalid number of arguments"));

This would cause an error message on stderr thus:

	"elfsign: invalid number of arguments"

The first argument to cryptoerror is either LOG_STDERR or a syslog(3c)
priority.  All messages include the PID and are logged at LOG_USER.

for debug output:

	cryptodebug("scmd=request opts=%s", opts);

This would go to the location defined by $SUNW_CRYPTO_DEBUG, ie
syslog, stderr or not be generated at all.

2.2 PKCS#11 Mechanism Type to and from Strings

	pkcs11_mech2str() and pkcs11_str2mech()

These functions use a table built at compile time from the contents of
the pkcs11t.h file to map mechanism numbers to the corresponding string
value.

pkcs11_mech2str() returns a pointer to a string that should be free(3c)'d
by the caller.

Consumers:  

	digest(1), mac(1), encrypt(1), decrypt(1) for translating
	command line args to mech numbers.  They will need to
	add the "CKM_" prefix before calling pkc11_str2mech()

	cryptoadm(8) for output to user, and for storing in pkcs11.conf
	file.

	Debug code.

2.3 The "pkcs11.conf" configuration file Parsing code.

The "pkcs11.conf" configuration file parsing code and data structures are
shared between:
	cryptoadm(8), libpkcs11(3crypto).

2.3.1 Data Structures:

	#define MECH_ID_HEX_LEN 11 /* length of mechanism id in hex form */

	typedef char libname_t[MAXPATHLEN];
	typedef char midstr_t[MECH_ID_HEX_LEN];

	/* The policy list for an entry in the config file  */
	typedef struct umechlist {
        	midstr_t                name;
	        struct umechlist        *next;
	} umechlist_t;

	/* An entry in the pkcs11.conf file */
	typedef struct uentry {
        	libname_t       name;
	        boolean_t       flag_enabledlist; /* TRUE if an enabledlist */
        	umechlist_t     *policylist; /* disabledlist or enabledlist */
	        int             count;
	} uentry_t;

	/* The entry list for the entire pkcs11.conf file */
	typedef struct uentrylist {
        	uentry_t               *pent;
	        struct uentrylist      *next;
	} uentrylist_t;


2.3.2 Functions:

extern int get_pkcs11conf_info(uentrylist_t **ppliblist);
$
    Retrieve the user-level provider info from the pkcs11.conf file.
    If successful, the result is returned from the ppliblist argument.
    This function returns SUCCESS if successfully done; otherwise it returns
    FAILURE.  The caller should use free_uentrylist() to free the space
    allocated for "ppliblist".

extern umechlist_t *create_umech(char *mechname);

    Create one item of type umechlist_t with the mechanism name in hex form. 
    A NULL is returned when the input name is NULL or the heap memory is
    insufficient.  The Caller should use free_umechlist() to free the space
    allocated for the returning data.

extern void free_uentrylist(uentrylist_t *ptr);

    Free space allocated for an pointer to the struct "uentrylist_t".

extern void free_uentry(uentry_t *ptr);

    Free space allocated for an pointer to the struct "uentry_t".
	
extern void free_umechlist(umechlist_t *ptr);

    Free space allocated for an pointer to the struct "umechlist_t".

2.4 PKCS#11 Mechanism Type to key type

	pkcs11_mech2keytype()

This function is used to get the key type for a mechanism.

Consumers:  

	encrypt(1), decrypt(1), and libpkcs11(3crypto) for getting
	the key type when creating an object for use with a
	specific mechanism.

2.5 PKCS#11 return code to string

	pkcs11_strerror()

This function returns a string representation of any given PKCS11 return
code.

Consumer:

	encrypt(1) and decrypt(1) uses this function for reporting errors.
	
2.5 PKCS#11 URI parsing code

	pkcs11_parse_uri()
	pkcs11_free_uri()

This function parses a PKCS#11 URI and fills up a pkcs11_uri_t structure. It
also reads the PIN if the PKCS#11 URI specifies a passphrase dialog. The
pkcs11_uri_t is described in cryptoutil.h, explanation of the return codes for
the pkcs11_parse_uri() function is in the function's comment in pk11_uri.c. The
pkcs11_parse_uri() function allocates the URI's fields and the caller is
responsible for calling pkcs11_free_uri() after it's done with the URI
structure.

Consumer:

	SunSSH will use the functions for parsing PKCS#11 URIs.
	
3. Non-Contents
	
Code for cryptographic algorithms does not belong in here.  That
comes from usr/src/common/<algorithm> since it is shared between user and
kernel.

PKCS#11 header files although they are common to various parts of the
user land framework come from usr/src/pkcs11/include

4. Interface Taxonomy

Everything in this library is Project Private or Internal.  The
exported symbols will all be marked as SUNWprivate_1.0 in the library
spec file.

5. Static vs Dynamic

The initial design was to only use a static archive library to avoid
exposing a new interface (even though it is all private).  However while
this is fine for initial delivery it creates difficulties later with
patching.  As such a Dynamic version will be build.

Libraries for lint and header files will not be shipped in any Sun packages
since this is all Project Private.  Similarly the abi_ file will not be
shipped even though a spec file will be used in the source gate.

6. Library location

At present all of the consumers of the library are in /usr/ so the
library is /usr/lib/{sparcv9}/libcryptoutil.so.1.  If kcfd ever moves
to /lib/crypto/kcf as a result of PSARC/2002/117 allowing it, then
libcryptoutil needs to move as well.
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License").  You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

include ../Makefile.com
include ../../Makefile.lib.64

.KEEP_STATE:

install: all $(ROOTLIBS64) $(ROOTLINKS64) $(ROOTCOMPATLINKS64)
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */


#include <stdio.h>
#include <errno.h>
#include <strings.h>
#include <locale.h>
#include <stdlib.h>
#include "cryptoutil.h"

static int uef_interpret(char *, uentry_t **);
static int parse_policylist(char *, uentry_t *);
static boolean_t is_fips(char *);

/*
 * Retrieve the user-level provider info from the pkcs11.conf file.
 * If successful, the result is returned from the ppliblist argument.
 * This function returns SUCCESS if successfully done; otherwise it returns
 * FAILURE.
 */
int
get_pkcs11conf_info(uentrylist_t **ppliblist)
{
	FILE *pfile;
	char buffer[BUFSIZ];
	size_t len;
	uentry_t *pent;
	uentrylist_t *pentlist;
	uentrylist_t *pcur;
	int rc = SUCCESS;

	*ppliblist = NULL;
	if ((pfile = fopen(_PATH_PKCS11_CONF, "rF")) == NULL) {
		cryptoerror(LOG_ERR, "failed to open %s.\n", _PATH_PKCS11_CONF);
		return (FAILURE);
	}

	while (fgets(buffer, BUFSIZ, pfile) != NULL) {
		if (buffer[0] == '#' || buffer[0] == ' ' ||
		    buffer[0] == '\n'|| buffer[0] == '\t') {
			continue;   /* ignore comment lines */
		}

		len = strlen(buffer);
		if (buffer[len-1] == '\n') { /* get rid of trailing '\n' */
			len--;
		}
		buffer[len] = '\0';

		if ((rc = uef_interpret(buffer,  &pent)) != SUCCESS) {
			break;
		}

		/* append pent into ppliblist */
		pentlist = malloc(sizeof (uentrylist_t));
		if (pentlist == NULL) {
			cryptoerror(LOG_ERR, "parsing %s, out of memory.\n",
			    _PATH_PKCS11_CONF);
			free_uentry(pent);
			rc = FAILURE;
			break;
		}
		pentlist->puent = pent;
		pentlist->next = NULL;

		if (*ppliblist == NULL) {
			*ppliblist = pcur = pentlist;
		} else {
			pcur->next = pentlist;
			pcur = pcur->next;
		}
	}

	(void) fclose(pfile);

	if (rc != SUCCESS) {
		free_uentrylist(*ppliblist);
		*ppliblist = NULL;
	}

	return (rc);
}

static int
parse_fips_mode(char *buf, boolean_t *mode)
{
	char *value;

	if (strncmp(buf, EF_FIPS_STATUS, sizeof (EF_FIPS_STATUS) - 1) == 0) {
		if (value = strpbrk(buf, SEP_EQUAL)) {
			value++; /* get rid of = */
			if (strcmp(value, DISABLED_KEYWORD) == 0) {
				*mode = B_FALSE;
			} else if (strcmp(value, ENABLED_KEYWORD) == 0) {
				*mode = B_TRUE;
			} else {
				cryptoerror(LOG_ERR, gettext(
				    "Failed to parse pkcs11.conf file.\n"));
				return (CKR_FUNCTION_FAILED);
			}
			return (CKR_OK);
		} else {
			return (CKR_FUNCTION_FAILED);
		}
	} else {
		/* should not come here */
		cryptoerror(LOG_ERR, gettext(
		    "Failed to parse pkcs11.conf file.\n"));
		return (CKR_FUNCTION_FAILED);
	}

}

/*
 * This routine converts a char string into a uentry_t structure
 * The input string "buf" should be one of the following:
 *	library_name
 *	library_name:NO_RANDOM
 *	library_name:disabledlist=m1,m2,...,mk
 *	library_name:disabledlist=m1,m2,...,mk;NO_RANDOM
 *	library_name:enabledlist=
 *	library_name:enabledlist=;NO_RANDOM
 *	library_name:enabledlist=m1,m2,...,mk
 *	library_name:enabledlist=m1,m2,...,mk;NO_RANDOM
 *	metaslot:status=enabled;enabledlist=m1,m2,....;slot=<slot-description>;\
 *	token=<token-label>
 *
 * Note:
 *	The mechanisms m1,..mk are in hex form. For example, "0x00000210"
 *	for CKM_MD5.
 *
 *	For the metaslot entry, "enabledlist", "slot", "auto_key_migrate"
 * 	or "token" is optional
 */
static int
uef_interpret(char *buf, uentry_t **ppent)
{
	uentry_t *pent;
	char	*token1;
	char	*token2;
	char	*lasts;
	int	rc;

	*ppent = NULL;
	if ((token1 = strtok_r(buf, SEP_COLON, &lasts)) == NULL) {
		/* buf is NULL */
		return (FAILURE);
	};

	pent = calloc(sizeof (uentry_t), 1);
	if (pent == NULL) {
		cryptoerror(LOG_ERR, "parsing %s, out of memory.\n",
		    _PATH_PKCS11_CONF);
		return (FAILURE);
	}
	(void) strlcpy(pent->name, token1, sizeof (pent->name));

	if (is_fips(token1)) {
		if ((rc = parse_fips_mode(buf + strlen(token1) + 1,
		    &pent->flag_fips_enabled)) != SUCCESS) {
			free_uentry(pent);
			return (rc);
		}

		*ppent = pent;
		return (SUCCESS);
	}

	/*
	 * in case metaslot_auto_key_migrate is not specified, it should
	 * be default to true
	 */
	pent->flag_metaslot_auto_key_migrate = B_TRUE;

	while ((token2 = strtok_r(NULL, SEP_SEMICOLON, &lasts)) != NULL) {
		if ((rc = parse_policylist(token2, pent)) != SUCCESS) {
			free_uentry(pent);
			return (rc);
		}
	}

	*ppent = pent;
	return (SUCCESS);
}


/*
 * This routine parses the policy list and stored the result in the argument
 * pent.
 *
 * 	Arg buf: input only, its format should be one of the following:
 *     		enabledlist=
 *		enabledlist=m1,m2,...,mk
 *		disabledlist=m1,m2,...,mk
 *		NO_RANDOM
 *		metaslot_status=enabled|disabled
 *		metaslot_token=<token-label>
 *		metaslot_slot=<slot-description.
 *
 *	Arg pent: input/output
 *
 *      return: SUCCESS or FAILURE
 */
static int
parse_policylist(char *buf, uentry_t *pent)
{
	umechlist_t *phead = NULL;
	umechlist_t *pcur = NULL;
	umechlist_t *pmech;
	char *next_token;
	char *value;
	char *lasts;
	int count = 0;
	int rc = SUCCESS;

	if (pent == NULL) {
		return (FAILURE);
	}

	if (strncmp(buf, EF_DISABLED, sizeof (EF_DISABLED) - 1) == 0) {
		pent->flag_enabledlist = B_FALSE;
	} else if (strncmp(buf, EF_ENABLED, sizeof (EF_ENABLED) - 1) == 0) {
		pent->flag_enabledlist = B_TRUE;
	} else if (strncmp(buf, EF_NORANDOM, sizeof (EF_NORANDOM) - 1) == 0) {
		pent->flag_norandom = B_TRUE;
		return (rc);
	} else if (strncmp(buf, METASLOT_TOKEN,
	    sizeof (METASLOT_TOKEN) - 1) == 0) {
		if (value = strpbrk(buf, SEP_EQUAL)) {
			value++; /* get rid of = */
			(void) strlcpy((char *)pent->metaslot_ks_token, value,
			    sizeof (pent->metaslot_ks_token));
			return (SUCCESS);
		} else {
			cryptoerror(LOG_ERR, "failed to parse %s.\n",
			    _PATH_PKCS11_CONF);
			return (FAILURE);
		}
	} else if (strncmp(buf, METASLOT_SLOT,
	    sizeof (METASLOT_SLOT) - 1) == 0) {
		if (value = strpbrk(buf, SEP_EQUAL)) {
			value++; /* get rid of = */
			(void) strlcpy((char *)pent->metaslot_ks_slot, value,
			    sizeof (pent->metaslot_ks_slot));
			return (SUCCESS);
		} else {
			cryptoerror(LOG_ERR, "failed to parse %s.\n",
			    _PATH_PKCS11_CONF);
			return (FAILURE);
		}
	} else if (strncmp(buf, METASLOT_STATUS,
	    sizeof (METASLOT_STATUS) - 1) == 0) {
		if (value = strpbrk(buf, SEP_EQUAL)) {
			value++; /* get rid of = */
			if (strcmp(value, DISABLED_KEYWORD) == 0) {
				pent->flag_metaslot_enabled = B_FALSE;
			} else if (strcmp(value, ENABLED_KEYWORD) == 0) {
				pent->flag_metaslot_enabled = B_TRUE;
			} else {
				cryptoerror(LOG_ERR, "failed to parse %s.\n",
				    _PATH_PKCS11_CONF);
				return (FAILURE);
			}
			return (SUCCESS);
		} else {
			cryptoerror(LOG_ERR, "failed to parse %s.\n",
			    _PATH_PKCS11_CONF);
			return (FAILURE);
		}
	} else if (strncmp(buf, METASLOT_AUTO_KEY_MIGRATE,
	    sizeof (METASLOT_AUTO_KEY_MIGRATE) - 1) == 0) {
		if (value = strpbrk(buf, SEP_EQUAL)) {
			value++; /* get rid of = */
			if (strcmp(value, DISABLED_KEYWORD) == 0) {
				pent->flag_metaslot_auto_key_migrate = B_FALSE;
			} else if (strcmp(value, ENABLED_KEYWORD) == 0) {
				pent->flag_metaslot_auto_key_migrate = B_TRUE;
			} else {
				cryptoerror(LOG_ERR, "failed to parse %s.\n",
				    _PATH_PKCS11_CONF);
				return (FAILURE);
			}
			return (SUCCESS);
		} else {
			cryptoerror(LOG_ERR, "failed to parse %s.\n",
			    _PATH_PKCS11_CONF);
			return (FAILURE);
		}
	} else {
		cryptoerror(LOG_ERR, "failed to parse %s.\n",
		    _PATH_PKCS11_CONF);
		return (FAILURE);
	}

	if (value = strpbrk(buf, SEP_EQUAL)) {
		value++; /* get rid of = */
	}

	if ((next_token = strtok_r(value, SEP_COMMA, &lasts)) == NULL) {
		if (pent->flag_enabledlist) {
			return (SUCCESS);
		} else {
			cryptoerror(LOG_ERR, "failed to parse %s.\n",
			    _PATH_PKCS11_CONF);
			return (FAILURE);
		}
	}

	while (next_token) {
		if ((pmech = create_umech(next_token)) == NULL) {
			cryptoerror(LOG_ERR, "parsing %s, out of memory.\n",
			    _PATH_PKCS11_CONF);
			rc = FAILURE;
			break;
		}

		if (phead == NULL) {
			phead = pcur = pmech;
		} else {
			pcur->next = pmech;
			pcur = pcur->next;
		}
		count++;
		next_token = strtok_r(NULL, SEP_COMMA, &lasts);
	}

	if (rc == SUCCESS) {
		pent->policylist = phead;
		pent->count = count;
	} else {
		free_umechlist(phead);
	}

	return (rc);
}


/*
 * Create one item of type umechlist_t with the mechanism name.  A NULL is
 * returned when the input name is NULL or the heap memory is insufficient.
 */
umechlist_t *
create_umech(char *name)
{
	umechlist_t *pmech = NULL;

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

	if ((pmech = malloc(sizeof (umechlist_t))) != NULL) {
		(void) strlcpy(pmech->name, name, sizeof (pmech->name));
		pmech->next = NULL;
	}

	return (pmech);
}


void
free_umechlist(umechlist_t *plist)
{
	umechlist_t *pnext;

	while (plist != NULL) {
		pnext = plist->next;
		free(plist);
		plist = pnext;
	}
}


void
free_uentry(uentry_t  *pent)
{
	if (pent == NULL) {
		return;
	} else {
		free_umechlist(pent->policylist);
		free(pent);
	}
}


void
free_uentrylist(uentrylist_t *entrylist)
{
	uentrylist_t *pnext;

	while (entrylist != NULL) {
		pnext = entrylist->next;
		free_uentry(entrylist->puent);
		free(entrylist);
		entrylist = pnext;
	}
}



/*
 * Duplicate an UEF mechanism list.  A NULL pointer is returned if out of
 * memory or the input argument is NULL.
 */
static umechlist_t *
dup_umechlist(umechlist_t *plist)
{
	umechlist_t *pres = NULL;
	umechlist_t *pcur;
	umechlist_t *ptmp;
	int rc = SUCCESS;

	while (plist != NULL) {
		if (!(ptmp = create_umech(plist->name))) {
			rc = FAILURE;
			break;
		}

		if (pres == NULL) {
			pres = pcur = ptmp;
		} else {
			pcur->next = ptmp;
			pcur = pcur->next;
		}
		plist = plist->next;
	}

	if (rc != SUCCESS) {
		free_umechlist(pres);
		return (NULL);
	}

	return (pres);
}


/*
 * Duplicate an uentry.  A NULL pointer is returned if out of memory
 * or the input argument is NULL.
 */
static uentry_t *
dup_uentry(uentry_t *puent1)
{
	uentry_t *puent2 = NULL;

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

	if ((puent2 = malloc(sizeof (uentry_t))) == NULL) {
		cryptoerror(LOG_STDERR, gettext("out of memory."));
		return (NULL);
	} else {
		(void) strlcpy(puent2->name, puent1->name,
		    sizeof (puent2->name));
		puent2->flag_norandom = puent1->flag_norandom;
		puent2->flag_enabledlist = puent1->flag_enabledlist;
		puent2->policylist = dup_umechlist(puent1->policylist);
		puent2->flag_metaslot_enabled = puent1->flag_metaslot_enabled;
		puent2->flag_metaslot_auto_key_migrate
		    = puent1->flag_metaslot_auto_key_migrate;
		(void) memcpy(puent2->metaslot_ks_slot,
		    puent1->metaslot_ks_slot, SLOT_DESCRIPTION_SIZE);
		(void) memcpy(puent2->metaslot_ks_token,
		    puent1->metaslot_ks_token, TOKEN_LABEL_SIZE);
		puent2->count = puent1->count;
		puent2->flag_fips_enabled = puent1->flag_fips_enabled;
		return (puent2);
	}
}

/*
 * Find the entry in the "pkcs11.conf" file with "libname" as the provider
 * name. Return the entry if found, otherwise return NULL.
 */
uentry_t *
getent_uef(char *libname)
{
	uentrylist_t	*pliblist = NULL;
	uentrylist_t	*plib = NULL;
	uentry_t	*puent = NULL;
	boolean_t	found = B_FALSE;

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

	if ((get_pkcs11conf_info(&pliblist)) == FAILURE) {
		return (NULL);
	}

	plib = pliblist;
	while (plib) {
		if (strcmp(plib->puent->name, libname) == 0) {
			found = B_TRUE;
			break;
		} else {
			plib = plib->next;
		}
	}

	if (found) {
		puent = dup_uentry(plib->puent);
	}

	free_uentrylist(pliblist);
	return (puent);
}



/*
 * Retrieve the metaslot information from the pkcs11.conf file.
 * This function returns SUCCESS if successfully done; otherwise it returns
 * FAILURE.   If successful, the caller is responsible to free the space
 * allocated for objectstore_slot_info and objectstore_token_info.
 */
int
get_metaslot_info(boolean_t  *status_enabled, boolean_t *migrate_enabled,
    char **objectstore_slot_info, char **objectstore_token_info)
{

	int rc = SUCCESS;
	uentry_t *puent;
	char *buf1 = NULL;
	char *buf2 = NULL;

	if ((puent = getent_uef(METASLOT_KEYWORD)) == NULL) {
		/* metaslot entry doesn't exist */
		return (FAILURE);
	}

	*status_enabled = puent->flag_metaslot_enabled;
	*migrate_enabled = puent->flag_metaslot_auto_key_migrate;

	buf1 = malloc(SLOT_DESCRIPTION_SIZE);
	if (buf1 == NULL) {
		cryptoerror(LOG_ERR, "get_metaslot_info() - out of memory.\n");
		rc = FAILURE;
		goto out;
	}
	(void) strcpy(buf1, (const char *) puent->metaslot_ks_slot);
	*objectstore_slot_info = buf1;

	buf2 = malloc(TOKEN_LABEL_SIZE);
	if (objectstore_slot_info == NULL) {
		cryptoerror(LOG_ERR, "get_metaslot_info() - out of memory.\n");
		rc = FAILURE;
		goto out;
	}
	(void) strcpy(buf2, (const char *) puent->metaslot_ks_token);
	*objectstore_token_info = buf2;

out:
	if (puent != NULL) {
		free_uentry(puent);
	}

	if (rc == FAILURE) {
		if (buf1 != NULL) {
			free(buf1);
		}
		if (buf2 != NULL) {
			free(buf2);
		}
	}

	return (rc);
}

static boolean_t
is_fips(char *name)
{
	if (strcmp(name, FIPS_KEYWORD) == 0) {
		return (B_TRUE);
	} else {
		return (B_FALSE);
	}
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Copyright 2010 Nexenta Systems, Inc.  All rights reserved.
 * Copyright 2014, OmniTI Computer Consulting, Inc. All rights reserved.
 * Copyright 2018, Joyent, Inc.
 */

#ifndef _CRYPTOUTIL_H
#define	_CRYPTOUTIL_H

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <syslog.h>
#include <security/cryptoki.h>
#include <sys/param.h>

#define	LOG_STDERR	-1
#define	SUCCESS		0
#define	FAILURE		1
#define	MECH_ID_HEX_LEN	11	/* length of mechanism id in hex form */

#define	_PATH_PKCS11_CONF	"/etc/crypto/pkcs11.conf"
#define	_PATH_KCF_CONF		"/etc/crypto/kcf.conf"
#define	_PATH_KCFD_LOCK		"/var/run/kcfd.lock"

/* $ISA substitution for parsing pkcs11.conf data */
#define	PKCS11_ISA	"/$ISA/"
#if defined(_LP64)
#define	PKCS11_ISA_DIR	"/64/"
#else	/* !_LP64 */
#define	PKCS11_ISA_DIR	"/"
#endif

/* keywords and delimiters for parsing configuration files */
#define	SEP_COLON	":"
#define	SEP_SEMICOLON	";"
#define	SEP_EQUAL	"="
#define	SEP_COMMA	","
#define	METASLOT_KEYWORD	"metaslot"
#define	FIPS_KEYWORD	"fips-140"
#define	EF_DISABLED	"disabledlist="
#define	EF_ENABLED	"enabledlist="
#define	EF_NORANDOM	"NO_RANDOM"
#define	METASLOT_TOKEN	"metaslot_token="
#define	METASLOT_SLOT	"metaslot_slot="
#define	METASLOT_STATUS	"metaslot_status="
#define	EF_FIPS_STATUS	"fips_status="
#define	METASLOT_AUTO_KEY_MIGRATE	"metaslot_auto_key_migrate="
#define	ENABLED_KEYWORD		"enabled"
#define	DISABLED_KEYWORD	"disabled"
#define	SLOT_DESCRIPTION_SIZE	64
#define	TOKEN_LABEL_SIZE	32
#define	TOKEN_MANUFACTURER_SIZE	32
#define	TOKEN_SERIAL_SIZE	16
#define	CRYPTO_FIPS_MODE_DISABLED	0
#define	CRYPTO_FIPS_MODE_ENABLED	1

/*
 * Define the following softtoken values that are used by softtoken
 * library, cryptoadm and pktool command.
 */
#define	SOFT_SLOT_DESCRIPTION	\
			"Sun Crypto Softtoken            " \
			"                                "
#define	SOFT_TOKEN_LABEL	"Sun Software PKCS#11 softtoken  "
#define	SOFT_TOKEN_SERIAL	"                "
#define	SOFT_MANUFACTURER_ID	"Sun Microsystems, Inc.          "
#define	SOFT_DEFAULT_PIN	"changeme"

typedef char libname_t[MAXPATHLEN];
typedef char midstr_t[MECH_ID_HEX_LEN];

typedef struct umechlist {
	midstr_t		name;	/* mechanism name in hex form */
	struct umechlist	*next;
} umechlist_t;

typedef struct uentry {
	libname_t	name;
	boolean_t	flag_norandom; /* TRUE if random is disabled */
	boolean_t	flag_enabledlist; /* TRUE if an enabledlist */
	umechlist_t	*policylist; /* disabledlist or enabledlist */
	boolean_t	flag_metaslot_enabled; /* TRUE if metaslot's enabled */
	boolean_t	flag_metaslot_auto_key_migrate;
	CK_UTF8CHAR	metaslot_ks_slot[SLOT_DESCRIPTION_SIZE + 1];
	CK_UTF8CHAR	metaslot_ks_token[TOKEN_LABEL_SIZE + 1];
	int		count;
	boolean_t	flag_fips_enabled;
} uentry_t;

typedef struct uentrylist {
	uentry_t	*puent;
	struct uentrylist	*next;
} uentrylist_t;

/* Return codes for pkcs11_parse_uri() */
#define	PK11_URI_OK		0
#define	PK11_URI_INVALID	1
#define	PK11_MALLOC_ERROR	2
#define	PK11_URI_VALUE_OVERFLOW	3
#define	PK11_NOT_PKCS11_URI	4

/*
 * There is no limit for the attribute length in the spec. 256 bytes should be
 * enough for the object name.
 */
#define	PK11_MAX_OBJECT_LEN		256
/*
 * CKA_ID is of type "byte array" which can be of arbitrary length. 256 bytes
 * should be sufficient though.
 */
#define	PK11_MAX_ID_LEN			256

/* Structure for the PKCS#11 URI. */
typedef struct pkcs11_uri_t {
	/* CKA_LABEL attribute to the C_FindObjectsInit function. */
	CK_UTF8CHAR_PTR	object;
	/*
	 * CKA_CLASS attribute to the C_FindObjectsInit function. The
	 * "objecttype" URI attribute can have a value one of "private",
	 * "public", "cert", "secretkey", and "data". The "objecttype" field can
	 * have a value of CKO_PUBLIC_KEY, CKO_PRIVATE_KEY, CKO_CERTIFICATE,
	 * CKO_SECRET_KEY, and CKO_DATA. This attribute cannot be empty in the
	 * URI.
	 */
	CK_ULONG	objecttype;
	/* CKO_DATA is 0 so we need this flag. Not part of the URI itself. */
	boolean_t	objecttype_present;
	/*
	 * Token, manufufacturer, serial and model are of fixed size length in
	 * the specification. We allocate memory on the fly to distinguish
	 * between an attribute not present and an empty value. We check for
	 * overflows. We always terminate the string with '\0' even when that is
	 * not used in the PKCS#11's CK_TOKEN_INFO structure (fields are padded
	 * with spaces).
	 */
	/* Token label from CK_TOKEN_INFO. */
	CK_UTF8CHAR_PTR	token;
	/* ManufacturerID from CK_TOKEN_INFO. */
	CK_UTF8CHAR_PTR	manuf;
	/* SerialNumber from CK_TOKEN_INFO. */
	CK_CHAR_PTR	serial;
	/* Model from CK_TOKEN_INFO. */
	CK_UTF8CHAR_PTR	model;
	/* This is a byte array, we need a length parameter as well. */
	CK_BYTE_PTR	id;
	int		id_len;
	/*
	 * Location of the file with a token PIN. Application can overload this,
	 * eg. "/bin/askpass|" may mean to read the PIN from a command. However,
	 * the pkcs11_parse_uri() function does not interpret this field in any
	 * way.
	 */
	char		*pinfile;
} pkcs11_uri_t;

extern void cryptodebug(const char *fmt, ...);
extern void cryptoerror(int priority, const char *fmt, ...);
extern void cryptodebug_init(const char *prefix);
extern void cryptoerror_off();
extern void cryptoerror_on();

extern const char *pkcs11_mech2str(CK_MECHANISM_TYPE mech);
extern CK_RV pkcs11_str2mech(char *mech_str, CK_MECHANISM_TYPE_PTR mech);

extern int get_pkcs11conf_info(uentrylist_t **);
extern umechlist_t *create_umech(char *);
extern void free_umechlist(umechlist_t *);
extern void free_uentrylist(uentrylist_t *);
extern void free_uentry(uentry_t *);
extern uentry_t *getent_uef(char *);

extern void tohexstr(uchar_t *bytes, size_t blen, char *hexstr, size_t hexlen);
extern int hexstr_to_bytes(char *hexstr, size_t hexlen, uchar_t **bytes,
    size_t *blen);
extern CK_RV pkcs11_mech2keytype(CK_MECHANISM_TYPE mech_type,
    CK_KEY_TYPE *ktype);
extern CK_RV pkcs11_mech2keygen(CK_MECHANISM_TYPE mech_type,
    CK_MECHANISM_TYPE *gen_mech);
extern char *pkcs11_strerror(CK_RV rv);

extern int
get_metaslot_info(boolean_t  *status_enabled, boolean_t *migrate_enabled,
    char **objectstore_slot_info, char **objectstore_token_info);

extern char *get_fullpath(char *dir, char *filepath);
extern int str2lifetime(char *ltimestr, uint32_t *ltime);

extern char *pkcs11_default_token(void);
extern int pkcs11_get_pass(char *token_name, char **pdata, size_t *psize,
    size_t min_psize, boolean_t with_confirmation);

extern int pkcs11_seed_urandom(void *sbuf, size_t slen);
extern int pkcs11_get_random(void *dbuf, size_t dlen);
extern int pkcs11_get_urandom(void *dbuf, size_t dlen);
extern int pkcs11_get_nzero_urandom(void *dbuf, size_t dlen);
extern int pkcs11_read_data(char *filename, void **dbuf, size_t *dlen);

extern int open_nointr(const char *path, int oflag, ...);
extern ssize_t readn_nointr(int fd, void *dbuf, size_t dlen);
extern ssize_t writen_nointr(int fd, void *dbuf, size_t dlen);
extern int update_conf(char *conf_file, char *entry);

extern int pkcs11_parse_uri(const char *str, pkcs11_uri_t *uri);
extern void pkcs11_free_uri(pkcs11_uri_t *uri);

extern CK_RV crypto2pkcs11_error_number(uint_t);

#ifdef __cplusplus
}
#endif

#endif /* _CRYPTOUTIL_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <syslog.h>
#include <string.h>
#include <cryptoutil.h>

#define	CRYPTO_DEBUG_ENV	"SUNW_CRYPTO_DEBUG"

static char *_cryptodebug_prefix = NULL;
static int _cryptodebug_enabled = -1; /* -1 unknown, 0 disabled, 1 enabled */
static int _cryptoerror_enabled = 1; /* 0 disabled, 1 enabled */
static boolean_t _cryptodebug_syslog = B_TRUE;

/*PRINTFLIKE1*/
void
cryptodebug(const char *fmt, ...)
{
	va_list args;
	char fmtbuf[BUFSIZ];
	char msgbuf[BUFSIZ];

	if (fmt == NULL || _cryptodebug_enabled != 1)
		return;

	va_start(args, fmt);
	if (_cryptodebug_prefix == NULL) {
		(void) vsnprintf(msgbuf, sizeof (msgbuf), fmt, args);
	} else {
		(void) snprintf(fmtbuf, sizeof (fmtbuf), "%s: %s",
		    _cryptodebug_prefix, fmt);
		(void) vsnprintf(msgbuf, sizeof (msgbuf), fmtbuf, args);
	}

	if (_cryptodebug_syslog) {
		syslog(LOG_DEBUG, msgbuf);
	} else {
		(void) fprintf(stderr, "%s\n", msgbuf);
	}
	va_end(args);
}

/*
 * cryptoerror
 *
 * This is intended to be used both by interactive commands like cryptoadm(8)
 * digest(1) etc, and by libraries libpkcs11, libelfsign etc.
 *
 * A library probably wants most (all?) of its errors going to syslog but
 * commands are usually happy for them to go to stderr.
 *
 * If a syslog priority is passed we log on that priority.  Otherwise we
 * use LOG_STDERR to mean use stderr instead. LOG_STDERR is defined in
 * cryptoutil.h
 */

/*PRINTFLIKE2*/
void
cryptoerror(int priority, const char *fmt, ...)
{
	char fmtbuf[BUFSIZ];
	char msgbuf[BUFSIZ];
	va_list args;

	if (fmt == NULL || _cryptoerror_enabled == 0)
		return;

	va_start(args, fmt);
	if (_cryptodebug_prefix == NULL) {
		(void) vsnprintf(msgbuf, sizeof (msgbuf), fmt, args);
	} else {
		(void) snprintf(fmtbuf, sizeof (fmtbuf), "%s: %s",
		    _cryptodebug_prefix, fmt);
		(void) vsnprintf(msgbuf, sizeof (msgbuf), fmtbuf, args);
	}

	if ((priority == LOG_STDERR) || (priority < 0))  {
		(void) fprintf(stderr, "%s\n", msgbuf);
	} else {
		syslog(priority, msgbuf);
	}
	va_end(args);
}

void
cryptoerror_off()
{
	_cryptoerror_enabled = 0;
}

void
cryptoerror_on()
{
	_cryptoerror_enabled = 1;
}

void
cryptodebug_init(const char *prefix)
{
	char *envval = NULL;

	if (prefix != NULL) {
		_cryptodebug_prefix = strdup(prefix);
	}

	if (_cryptodebug_enabled == -1) {
		envval = getenv(CRYPTO_DEBUG_ENV);
		/*
		 * If unset or it isn't one of syslog or stderr
		 * disable debug.
		 */
		if (envval == NULL || (strcmp(envval, "") == 0)) {
			_cryptodebug_enabled = 0;
			return;
		} else if (strcmp(envval, "stderr") == 0) {
			_cryptodebug_syslog = B_FALSE;
			_cryptodebug_enabled = 1;
		} else if (strcmp(envval, "syslog") == 0) {
			_cryptodebug_syslog = B_TRUE;
			_cryptodebug_enabled = 1;
		}
	}

	openlog(_cryptodebug_prefix, LOG_PID, LOG_USER);
}

#pragma fini(_cryptodebug_fini)

static void
_cryptodebug_fini(void)
{
	if (_cryptodebug_prefix != NULL)
		free(_cryptodebug_prefix);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <locale.h>
#include <cryptoutil.h>

/*
 * Read file into buffer.  Used to read raw key data or initialization
 * vector data.  Buffer must be freed by caller using free().
 *
 * If file is a regular file, entire file is read and dlen is set
 * to the number of bytes read.  Otherwise, dlen should first be set
 * to the number of bytes requested and will be reset to actual number
 * of bytes returned.
 *
 * Return 0 on success and errno on error.
 */
int
pkcs11_read_data(char *filename, void **dbuf, size_t *dlen)
{
	int	fd = -1;
	struct stat statbuf;
	boolean_t plain_file;
	void	*filebuf = NULL;
	size_t	filesize = 0;
	int ret = 0;

	if (filename == NULL || dbuf == NULL || dlen == NULL)
		return (-1);

	if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) == -1) {
		ret = errno;
		cryptoerror(LOG_STDERR, gettext("cannot open %s"), filename);
		goto error;
	}

	if (fstat(fd, &statbuf) == -1) {
		ret = errno;
		cryptoerror(LOG_STDERR, gettext("cannot stat %s"), filename);
		goto error;
	}

	if (S_ISREG(statbuf.st_mode)) {
		/* read the entire regular file */
		filesize = statbuf.st_size;
		plain_file = B_TRUE;
	} else {
		/* read requested bytes from special file */
		filesize = *dlen;
		plain_file = B_FALSE;
	}

	if (filesize == 0) {
		/*
		 * for decrypt this is an error; for digest this is ok;
		 * make it ok here but also set dbuf = NULL and dlen = 0
		 * to indicate there was no data to read and caller can
		 * retranslate that to an error if it wishes.
		 */
		(void) close(fd);
		*dbuf = NULL;
		*dlen = 0;
		return (0);
	}

	if ((filebuf = malloc(filesize)) == NULL) {
		ret = errno;
		cryptoerror(LOG_STDERR, gettext("malloc: %s"), strerror(ret));
		goto error;
	}

	if (plain_file) {
		/* either it got read or it didn't */
		if (read(fd, filebuf, filesize) != filesize) {
			ret = errno;
			cryptoerror(LOG_STDERR,
			    gettext("error reading file %s: %s"), filename,
			    strerror(ret));
			goto error;
		}
	} else {
		/* reading from special file may need some coaxing */
		char	*marker = (char *)filebuf;
		size_t	left = filesize;
		ssize_t	nread;

		for (/* */; left > 0; marker += nread, left -= nread) {
			/* keep reading it's going well */
			nread = read(fd, marker, left);
			if (nread > 0 || (nread == 0 && errno == EINTR)) {
				errno = 0;
				continue;
			}

			/* might have to be good enough for caller */
			if (nread == 0 && errno == EAGAIN)
				break;

			/* anything else is an error */
			if (errno) {
				ret = errno;
				cryptoerror(LOG_STDERR,
				    gettext("error reading file %s: %s"),
				    filename, strerror(ret));
				goto error;
			}
		}
		/* reset to actual number of bytes read */
		filesize -= left;
	}

	(void) close(fd);
	*dbuf = filebuf;
	*dlen = filesize;
	return (0);

error:
	if (fd != -1)
		(void) close(fd);

	return (ret);
}
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2014, OmniTI Computer Consulting Inc. All rights reserved.
# Copyright 2018, Joyent, Inc.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate {
    global:
	create_umech;
	crypto2pkcs11_error_number;
	cryptodebug;
	cryptodebug_init;
	cryptoerror;
	cryptoerror_off;
	cryptoerror_on;
	free_uentry;
	free_uentrylist;
	free_umechlist;
	getent_uef;
	get_fullpath;
	get_metaslot_info;
	get_pkcs11conf_info;
	hexstr_to_bytes;
	open_nointr;
	pkcs11_default_token;
	pkcs11_free_uri;
	pkcs11_get_nzero_urandom;
	pkcs11_get_pass;
	pkcs11_get_random;
	pkcs11_get_urandom;
	pkcs11_mech2keytype;
	pkcs11_mech2keygen;
	pkcs11_mech2str;
	pkcs11_parse_uri;
	pkcs11_read_data;
	pkcs11_seed_random;
	pkcs11_seed_urandom;
	pkcs11_str2mech;
	pkcs11_strerror;
	readn_nointr;
	str2lifetime;
	tohexstr;
	writen_nointr;
    local:
	*;
};
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2012 Milan Jurik. All rights reserved.
 * Copyright 2016 Jason King.  All rights reserved.
 */

#include <cryptoutil.h>

/*
 * Get the key generation mechanism for the given mechanism.
 *
 * All mechanisms in PKCS #11 v2.20 are listed here.
 */
CK_RV
pkcs11_mech2keygen(CK_MECHANISM_TYPE mech_type, CK_MECHANISM_TYPE *gen_mech)
{
	switch (mech_type) {

	case CKM_RSA_PKCS_KEY_PAIR_GEN:
	case CKM_RSA_PKCS:
	case CKM_RSA_9796:
	case CKM_RSA_X_509:
	case CKM_MD2_RSA_PKCS:
	case CKM_MD5_RSA_PKCS:
	case CKM_SHA1_RSA_PKCS:
	case CKM_SHA256_RSA_PKCS:
	case CKM_SHA384_RSA_PKCS:
	case CKM_SHA512_RSA_PKCS:
	case CKM_SHA256_RSA_PKCS_PSS:
	case CKM_SHA384_RSA_PKCS_PSS:
	case CKM_SHA512_RSA_PKCS_PSS:
	case CKM_RIPEMD128_RSA_PKCS:
	case CKM_RIPEMD160_RSA_PKCS:
	case CKM_RSA_PKCS_OAEP:
	case CKM_RSA_PKCS_OAEP_TPM_1_1:
	case CKM_RSA_PKCS_TPM_1_1:
		*gen_mech = CKM_RSA_PKCS_KEY_PAIR_GEN;
		break;

	case CKM_RSA_X9_31_KEY_PAIR_GEN:
	case CKM_RSA_X9_31:
	case CKM_SHA1_RSA_X9_31:
		*gen_mech = CKM_RSA_X9_31_KEY_PAIR_GEN;
		break;

	case CKM_RSA_PKCS_PSS:
	case CKM_SHA1_RSA_PKCS_PSS:
		*gen_mech = CKM_RSA_PKCS_KEY_PAIR_GEN;
		break;

	case CKM_DH_PKCS_PARAMETER_GEN:
		*gen_mech = CKM_DH_PKCS_PARAMETER_GEN;
		break;

	case CKM_DSA_KEY_PAIR_GEN:
	case CKM_DSA:
	case CKM_DSA_SHA1:
	case CKM_DSA_SHA224:
	case CKM_DSA_SHA256:
	case CKM_DSA_SHA384:
	case CKM_DSA_SHA512:
		*gen_mech = CKM_DSA_KEY_PAIR_GEN;
		break;

	case CKM_DSA_PARAMETER_GEN:
		*gen_mech = CKM_DSA_PARAMETER_GEN;
		break;

	case CKM_DSA_PROBABLISTIC_PARAMETER_GEN:
		*gen_mech = CKM_DSA_PROBABLISTIC_PARAMETER_GEN;
		break;

	case CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN:
		*gen_mech = CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN;
		break;

	case CKM_FORTEZZA_TIMESTAMP:
		*gen_mech = CKM_DSA_KEY_PAIR_GEN;
		break;

	case CKM_DH_PKCS_KEY_PAIR_GEN:
	case CKM_DH_PKCS_DERIVE:
		*gen_mech = CKM_DH_PKCS_KEY_PAIR_GEN;
		break;

	case CKM_ECDSA:
	case CKM_ECDSA_SHA1:
	case CKM_ECDSA_SHA224:
	case CKM_ECDSA_SHA256:
	case CKM_ECDSA_SHA384:
	case CKM_ECDSA_SHA512:
	case CKM_EC_KEY_PAIR_GEN:
	case CKM_ECDH1_DERIVE:
	case CKM_ECDH1_COFACTOR_DERIVE:
	case CKM_ECMQV_DERIVE:
		*gen_mech = CKM_EC_KEY_PAIR_GEN;
		break;

	case CKM_X9_42_DH_KEY_PAIR_GEN:
	case CKM_X9_42_DH_DERIVE:
	case CKM_X9_42_DH_HYBRID_DERIVE:
	case CKM_X9_42_MQV_DERIVE:
		*gen_mech = CKM_X9_42_DH_KEY_PAIR_GEN;
		break;

	case CKM_X9_42_DH_PARAMETER_GEN:
		*gen_mech = CKM_X9_42_DH_PARAMETER_GEN;
		break;

	case CKM_KEA_KEY_PAIR_GEN:
	case CKM_KEA_KEY_DERIVE:
		*gen_mech = CKM_KEA_KEY_PAIR_GEN;
		break;

	case CKM_MD2:
	case CKM_MD2_HMAC:
	case CKM_MD2_HMAC_GENERAL:
	case CKM_MD5:
	case CKM_MD5_HMAC:
	case CKM_MD5_HMAC_GENERAL:
	case CKM_SHA_1:
	case CKM_SHA_1_HMAC:
	case CKM_SHA_1_HMAC_GENERAL:
	case CKM_SHA256:
	case CKM_SHA256_HMAC:
	case CKM_SHA256_HMAC_GENERAL:
	case CKM_SHA384:
	case CKM_SHA384_HMAC:
	case CKM_SHA384_HMAC_GENERAL:
	case CKM_SHA512:
	case CKM_SHA512_HMAC:
	case CKM_SHA512_HMAC_GENERAL:
	case CKM_SHA512_224:
	case CKM_SHA512_224_HMAC:
	case CKM_SHA512_224_HMAC_GENERAL:
	case CKM_SHA512_224_KEY_DERIVATION:
	case CKM_SHA512_256:
	case CKM_SHA512_256_HMAC:
	case CKM_SHA512_256_HMAC_GENERAL:
	case CKM_SHA512_256_KEY_DERIVATION:
	case CKM_GENERIC_SECRET_KEY_GEN:
	case CKM_FASTHASH:
	case CKM_PKCS5_PBKD2:
	case CKM_PBA_SHA1_WITH_SHA1_HMAC:
	case CKM_CMS_SIG:
		*gen_mech = CKM_GENERIC_SECRET_KEY_GEN;
		break;

	case CKM_SSL3_MD5_MAC:
	case CKM_SSL3_SHA1_MAC:
	case CKM_SSL3_PRE_MASTER_KEY_GEN:
	case CKM_SSL3_MASTER_KEY_DERIVE:
	case CKM_SSL3_KEY_AND_MAC_DERIVE:
	case CKM_SSL3_MASTER_KEY_DERIVE_DH:
		*gen_mech = CKM_SSL3_PRE_MASTER_KEY_GEN;
		break;

	case CKM_TLS_PRE_MASTER_KEY_GEN:
	case CKM_TLS_MASTER_KEY_DERIVE:
	case CKM_TLS_KEY_AND_MAC_DERIVE:
	case CKM_TLS_MASTER_KEY_DERIVE_DH:
	case CKM_TLS_PRF:
		*gen_mech = CKM_TLS_PRE_MASTER_KEY_GEN;
		break;

	case CKM_WTLS_PRE_MASTER_KEY_GEN:
	case CKM_WTLS_MASTER_KEY_DERIVE:
	case CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC:
	case CKM_WTLS_PRF:
	case CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE:
	case CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE:
		*gen_mech = CKM_WTLS_PRE_MASTER_KEY_GEN;
		break;

	case CKM_CONCATENATE_BASE_AND_KEY:
	case CKM_CONCATENATE_BASE_AND_DATA:
	case CKM_CONCATENATE_DATA_AND_BASE:
	case CKM_XOR_BASE_AND_DATA:
	case CKM_EXTRACT_KEY_FROM_KEY:
	case CKM_RIPEMD128:
	case CKM_RIPEMD128_HMAC:
	case CKM_RIPEMD128_HMAC_GENERAL:
	case CKM_RIPEMD160:
	case CKM_RIPEMD160_HMAC:
	case CKM_RIPEMD160_HMAC_GENERAL:
	case CKM_SHA1_KEY_DERIVATION:
	case CKM_SHA256_KEY_DERIVATION:
	case CKM_SHA384_KEY_DERIVATION:
	case CKM_SHA512_KEY_DERIVATION:
	case CKM_MD5_KEY_DERIVATION:
	case CKM_MD2_KEY_DERIVATION:
	/* not sure the following 2 should be CKK_DES or not */
	case CKM_KEY_WRAP_LYNKS: /* wrap/unwrap secret key w/ DES key */
	case CKM_KEY_WRAP_SET_OAEP:  /* wrap/unwarp DES key w/ RSA key */
		*gen_mech = CKM_GENERIC_SECRET_KEY_GEN;
		break;

	case CKM_RC2_KEY_GEN:
	case CKM_RC2_ECB:
	case CKM_RC2_CBC:
	case CKM_RC2_MAC:
	case CKM_RC2_MAC_GENERAL:
	case CKM_RC2_CBC_PAD:
	case CKM_PBE_SHA1_RC2_128_CBC:
	case CKM_PBE_SHA1_RC2_40_CBC:
		*gen_mech = CKM_RC2_KEY_GEN;
		break;

	case CKM_RC4_KEY_GEN:
	case CKM_RC4:
	case CKM_PBE_SHA1_RC4_128:
	case CKM_PBE_SHA1_RC4_40:
		*gen_mech = CKM_RC4_KEY_GEN;
		break;

	case CKM_DES_KEY_GEN:
	case CKM_DES_ECB:
	case CKM_DES_CBC:
	case CKM_DES_MAC:
	case CKM_DES_MAC_GENERAL:
	case CKM_DES_CBC_PAD:
	case CKM_PBE_MD2_DES_CBC:
	case CKM_PBE_MD5_DES_CBC:
	case CKM_DES_OFB64:
	case CKM_DES_OFB8:
	case CKM_DES_CFB64:
	case CKM_DES_CFB8:
	case CKM_DES_ECB_ENCRYPT_DATA:
	case CKM_DES_CBC_ENCRYPT_DATA:
		*gen_mech = CKM_DES_KEY_GEN;
		break;

	case CKM_DES2_KEY_GEN:
	case CKM_PBE_SHA1_DES2_EDE_CBC:
		*gen_mech = CKM_DES2_KEY_GEN;
		break;

	case CKM_DES3_KEY_GEN:
	case CKM_DES3_ECB:
	case CKM_DES3_CBC:
	case CKM_DES3_MAC:
	case CKM_DES3_MAC_GENERAL:
	case CKM_DES3_CBC_PAD:
	case CKM_PBE_SHA1_DES3_EDE_CBC:
	case CKM_DES3_ECB_ENCRYPT_DATA:
	case CKM_DES3_CBC_ENCRYPT_DATA:
	case CKM_DES3_CMAC:
	case CKM_DES3_CMAC_GENERAL:
		*gen_mech = CKM_DES3_KEY_GEN;
		break;

	case CKM_ACTI:
	case CKM_ACTI_KEY_GEN:
		*gen_mech = CKM_ACTI_KEY_GEN;
		break;

	case CKM_CAST_KEY_GEN:
	case CKM_CAST_ECB:
	case CKM_CAST_CBC:
	case CKM_CAST_MAC:
	case CKM_CAST_MAC_GENERAL:
	case CKM_CAST_CBC_PAD:
	case CKM_PBE_MD5_CAST_CBC:
		*gen_mech = CKM_CAST_KEY_GEN;
		break;

	case CKM_CAST3_KEY_GEN:
	case CKM_CAST3_ECB:
	case CKM_CAST3_CBC:
	case CKM_CAST3_MAC:
	case CKM_CAST3_MAC_GENERAL:
	case CKM_CAST3_CBC_PAD:
	case CKM_PBE_MD5_CAST3_CBC:
		*gen_mech = CKM_CAST3_KEY_GEN;
		break;

	/* CAST5 and CAST128 are the same alg */
	case CKM_CAST5_CBC:
	case CKM_CAST5_CBC_PAD:
	case CKM_CAST5_ECB:
	case CKM_CAST5_KEY_GEN:
	case CKM_CAST5_MAC:
	case CKM_CAST5_MAC_GENERAL:
	case CKM_PBE_MD5_CAST5_CBC:
	case CKM_PBE_SHA1_CAST5_CBC:
		*gen_mech = CKM_CAST5_KEY_GEN;
		break;

	case CKM_RC5_KEY_GEN:
	case CKM_RC5_ECB:
	case CKM_RC5_CBC:
	case CKM_RC5_MAC:
	case CKM_RC5_MAC_GENERAL:
	case CKM_RC5_CBC_PAD:
		*gen_mech = CKM_RC5_KEY_GEN;
		break;

	case CKM_IDEA_KEY_GEN:
	case CKM_IDEA_ECB:
	case CKM_IDEA_CBC:
	case CKM_IDEA_MAC:
	case CKM_IDEA_MAC_GENERAL:
	case CKM_IDEA_CBC_PAD:
		*gen_mech = CKM_IDEA_KEY_GEN;
		break;

	case CKM_SKIPJACK_KEY_GEN:
	case CKM_SKIPJACK_ECB64:
	case CKM_SKIPJACK_CBC64:
	case CKM_SKIPJACK_OFB64:
	case CKM_SKIPJACK_CFB64:
	case CKM_SKIPJACK_CFB32:
	case CKM_SKIPJACK_CFB16:
	case CKM_SKIPJACK_CFB8:
	case CKM_SKIPJACK_WRAP:
	case CKM_SKIPJACK_PRIVATE_WRAP:
	case CKM_SKIPJACK_RELAYX:
		*gen_mech = CKM_SKIPJACK_KEY_GEN;
		break;

	case CKM_BATON_KEY_GEN:
	case CKM_BATON_ECB128:
	case CKM_BATON_ECB96:
	case CKM_BATON_CBC128:
	case CKM_BATON_COUNTER:
	case CKM_BATON_SHUFFLE:
	case CKM_BATON_WRAP:
		*gen_mech = CKM_BATON_KEY_GEN;
		break;

	case CKM_JUNIPER_KEY_GEN:
	case CKM_JUNIPER_ECB128:
	case CKM_JUNIPER_CBC128:
	case CKM_JUNIPER_COUNTER:
	case CKM_JUNIPER_SHUFFLE:
	case CKM_JUNIPER_WRAP:
		*gen_mech = CKM_JUNIPER_KEY_GEN;
		break;

	case CKM_CDMF_KEY_GEN:
	case CKM_CDMF_ECB:
	case CKM_CDMF_CBC:
	case CKM_CDMF_MAC:
	case CKM_CDMF_MAC_GENERAL:
	case CKM_CDMF_CBC_PAD:
		*gen_mech = CKM_CDMF_KEY_GEN;
		break;

	case CKM_AES_KEY_GEN:
	case CKM_AES_ECB:
	case CKM_AES_CBC:
	case CKM_AES_MAC:
	case CKM_AES_MAC_GENERAL:
	case CKM_AES_CBC_PAD:
	case CKM_AES_ECB_ENCRYPT_DATA:
	case CKM_AES_CBC_ENCRYPT_DATA:
	case CKM_AES_CCM:
	case CKM_AES_CFB1:
	case CKM_AES_CFB128:
	case CKM_AES_CFB64:
	case CKM_AES_CFB8:
	case CKM_AES_CMAC:
	case CKM_AES_CMAC_GENERAL:
	case CKM_AES_CTR:
	case CKM_AES_CTS:
	case CKM_AES_GCM:
	case CKM_AES_GMAC:
	case CKM_AES_KEY_WRAP:
	case CKM_AES_KEY_WRAP_PAD:
	case CKM_AES_OFB:
	case CKM_AES_XCBC_MAC:
	case CKM_AES_XCBC_MAC_96:
		*gen_mech = CKM_AES_KEY_GEN;
		break;

	case CKM_BLOWFISH_KEY_GEN:
	case CKM_BLOWFISH_CBC:
	case CKM_BLOWFISH_CBC_PAD:
		*gen_mech = CKM_BLOWFISH_KEY_GEN;
		break;

	case CKM_TWOFISH_KEY_GEN:
	case CKM_TWOFISH_CBC:
		*gen_mech = CKM_TWOFISH_KEY_GEN;
		break;

	case CKM_CAMELLIA_CBC:
	case CKM_CAMELLIA_CBC_ENCRYPT_DATA:
	case CKM_CAMELLIA_CBC_PAD:
	case CKM_CAMELLIA_CTR:
	case CKM_CAMELLIA_ECB:
	case CKM_CAMELLIA_ECB_ENCRYPT_DATA:
	case CKM_CAMELLIA_KEY_GEN:
	case CKM_CAMELLIA_MAC:
	case CKM_CAMELLIA_MAC_GENERAL:
		*gen_mech = CKM_CAMELLIA_KEY_GEN;
		break;

	case CKM_ARIA_CBC:
	case CKM_ARIA_CBC_ENCRYPT_DATA:
	case CKM_ARIA_CBC_PAD:
	case CKM_ARIA_ECB:
	case CKM_ARIA_ECB_ENCRYPT_DATA:
	case CKM_ARIA_KEY_GEN:
	case CKM_ARIA_MAC:
	case CKM_ARIA_MAC_GENERAL:
		*gen_mech = CKM_ARIA_KEY_GEN;
		break;

	case CKM_GOST28147:
	case CKM_GOST28147_ECB:
	case CKM_GOST28147_KEY_GEN:
	case CKM_GOST28147_KEY_WRAP:
	case CKM_GOST28147_MAC:
		*gen_mech = CKM_GOST28147_KEY_GEN;
		break;

	case CKM_GOSTR3410:
	case CKM_GOSTR3410_DERIVE:
	case CKM_GOSTR3410_KEY_PAIR_GEN:
	case CKM_GOSTR3410_KEY_WRAP:
	case CKM_GOSTR3410_WITH_GOSTR3411:
		*gen_mech = CKM_GOSTR3410_KEY_PAIR_GEN;
		break;

	case CKM_HOTP:
	case CKM_HOTP_KEY_GEN:
		*gen_mech = CKM_HOTP_KEY_GEN;
		break;

	case CKM_SECURID:
	case CKM_SECURID_KEY_GEN:
		*gen_mech = CKM_SECURID_KEY_GEN;
		break;

	case CKM_SEED_CBC:
	case CKM_SEED_CBC_ENCRYPT_DATA:
	case CKM_SEED_CBC_PAD:
	case CKM_SEED_ECB:
	case CKM_SEED_ECB_ENCRYPT_DATA:
	case CKM_SEED_KEY_GEN:
	case CKM_SEED_MAC:
	case CKM_SEED_MAC_GENERAL:
		*gen_mech = CKM_SEED_KEY_GEN;
		break;

	default:
		return (CKR_MECHANISM_INVALID);
	}

	return (CKR_OK);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright 2016 Jason King.
 */

#include <cryptoutil.h>

/*
 * Get the key type for the given mechanism
 *
 * All mechanisms in PKCS #11 v2.40 are listed here.
 */
CK_RV
pkcs11_mech2keytype(CK_MECHANISM_TYPE mech_type, CK_KEY_TYPE *ktype)
{

	CK_RV rv = CKR_OK;

	switch (mech_type) {

	case CKM_RSA_PKCS_KEY_PAIR_GEN:
	case CKM_RSA_PKCS:
	case CKM_RSA_9796:
	case CKM_RSA_X_509:
	case CKM_MD2_RSA_PKCS:
	case CKM_MD5_RSA_PKCS:
	case CKM_SHA1_RSA_PKCS:
	case CKM_SHA256_RSA_PKCS:
	case CKM_SHA384_RSA_PKCS:
	case CKM_SHA512_RSA_PKCS:
	case CKM_SHA256_RSA_PKCS_PSS:
	case CKM_SHA384_RSA_PKCS_PSS:
	case CKM_SHA512_RSA_PKCS_PSS:
	case CKM_SHA224_RSA_PKCS:
	case CKM_SHA224_RSA_PKCS_PSS:
	case CKM_RIPEMD128_RSA_PKCS:
	case CKM_RIPEMD160_RSA_PKCS:
	case CKM_RSA_PKCS_OAEP:
	case CKM_RSA_X9_31_KEY_PAIR_GEN:
	case CKM_RSA_X9_31:
	case CKM_SHA1_RSA_X9_31:
	case CKM_RSA_PKCS_PSS:
	case CKM_SHA1_RSA_PKCS_PSS:
	case CKM_RSA_PKCS_TPM_1_1:
	case CKM_RSA_PKCS_OAEP_TPM_1_1:
		*ktype = CKK_RSA;
		break;

	case CKM_DSA_KEY_PAIR_GEN:
	case CKM_DSA:
	case CKM_DSA_SHA1:
	case CKM_DSA_PARAMETER_GEN:
	case CKM_FORTEZZA_TIMESTAMP:
	case CKM_DSA_SHA224:
	case CKM_DSA_SHA256:
	case CKM_DSA_SHA384:
	case CKM_DSA_SHA512:
		*ktype = CKK_DSA;
		break;

	case CKM_DH_PKCS_PARAMETER_GEN:
	case CKM_DH_PKCS_KEY_PAIR_GEN:
	case CKM_DH_PKCS_DERIVE:
		*ktype = CKK_DH;
		break;

	case CKM_ECDSA:
	case CKM_ECDSA_SHA1:
	case CKM_EC_KEY_PAIR_GEN:
	case CKM_ECDH1_DERIVE:
	case CKM_ECDH1_COFACTOR_DERIVE:
	case CKM_ECMQV_DERIVE:
		*ktype = CKK_EC;
		break;

	case CKM_X9_42_DH_KEY_PAIR_GEN:
	case CKM_X9_42_DH_DERIVE:
	case CKM_X9_42_DH_HYBRID_DERIVE:
	case CKM_X9_42_MQV_DERIVE:
	case CKM_X9_42_DH_PARAMETER_GEN:
		*ktype = CKK_X9_42_DH;
		break;

	case CKM_KEA_KEY_PAIR_GEN:
	case CKM_KEA_KEY_DERIVE:
		*ktype = CKK_KEA;
		break;

	case CKM_MD2:
	case CKM_MD2_HMAC:
	case CKM_MD2_HMAC_GENERAL:
	case CKM_MD5:
	case CKM_MD5_HMAC:
	case CKM_MD5_HMAC_GENERAL:
	case CKM_SHA_1:
	case CKM_SHA_1_HMAC:
	case CKM_SHA_1_HMAC_GENERAL:
	case CKM_SHA256:
	case CKM_SHA256_HMAC:
	case CKM_SHA256_HMAC_GENERAL:
	case CKM_SHA224:
	case CKM_SHA224_HMAC:
	case CKM_SHA224_HMAC_GENERAL:
	case CKM_SHA384:
	case CKM_SHA384_HMAC:
	case CKM_SHA384_HMAC_GENERAL:
	case CKM_SHA512:
	case CKM_SHA512_HMAC:
	case CKM_SHA512_HMAC_GENERAL:
	case CKM_GENERIC_SECRET_KEY_GEN:
	case CKM_FASTHASH:
	case CKM_PKCS5_PBKD2:
	case CKM_PBA_SHA1_WITH_SHA1_HMAC:
	case CKM_SSL3_MD5_MAC:
	case CKM_SSL3_SHA1_MAC:
	case CKM_SSL3_PRE_MASTER_KEY_GEN:
	case CKM_SSL3_MASTER_KEY_DERIVE:
	case CKM_SSL3_KEY_AND_MAC_DERIVE:
	case CKM_SSL3_MASTER_KEY_DERIVE_DH:
	case CKM_TLS_PRE_MASTER_KEY_GEN:
	case CKM_TLS_MASTER_KEY_DERIVE:
	case CKM_TLS_KEY_AND_MAC_DERIVE:
	case CKM_TLS_MASTER_KEY_DERIVE_DH:
	case CKM_TLS_PRF:
	case CKM_WTLS_PRE_MASTER_KEY_GEN:
	case CKM_WTLS_MASTER_KEY_DERIVE:
	case CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC:
	case CKM_WTLS_PRF:
	case CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE:
	case CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE:
	case CKM_CONCATENATE_BASE_AND_KEY:
	case CKM_CONCATENATE_BASE_AND_DATA:
	case CKM_CONCATENATE_DATA_AND_BASE:
	case CKM_XOR_BASE_AND_DATA:
	case CKM_EXTRACT_KEY_FROM_KEY:
	case CKM_RIPEMD128:
	case CKM_RIPEMD128_HMAC:
	case CKM_RIPEMD128_HMAC_GENERAL:
	case CKM_RIPEMD160:
	case CKM_RIPEMD160_HMAC:
	case CKM_RIPEMD160_HMAC_GENERAL:
	case CKM_SHA1_KEY_DERIVATION:
	case CKM_SHA256_KEY_DERIVATION:
	case CKM_SHA384_KEY_DERIVATION:
	case CKM_SHA512_KEY_DERIVATION:
	case CKM_SHA224_KEY_DERIVATION:
	case CKM_MD5_KEY_DERIVATION:
	case CKM_MD2_KEY_DERIVATION:
	/* not sure the following 2 should be CKK_DES or not */
	case CKM_KEY_WRAP_LYNKS: /* wrap/unwrap secret key w/ DES key */
	case CKM_KEY_WRAP_SET_OAEP:  /* wrap/unwarp DES key w/ RSA key */
	case CKM_SHA512_224:
	case CKM_SHA512_224_HMAC:
	case CKM_SHA512_224_HMAC_GENERAL:
	case CKM_SHA512_224_KEY_DERIVATION:
	case CKM_SHA512_256:
	case CKM_SHA512_256_HMAC:
	case CKM_SHA512_256_HMAC_GENERAL:
	case CKM_SHA512_256_KEY_DERIVATION:
	case CKM_SHA512_T:
	case CKM_SHA512_T_HMAC:
	case CKM_SHA512_T_HMAC_GENERAL:
	case CKM_SHA512_T_KEY_DERIVATION:
	case CKM_TLS10_MAC_SERVER:
	case CKM_TLS10_MAC_CLIENT:
	case CKM_TLS12_MAC:
	case CKM_TLS12_MASTER_KEY_DERIVE:
	case CKM_TLS12_KEY_AND_MAC_DERIVE:
	case CKM_TLS12_MASTER_KEY_DERIVE_DH:
	case CKM_TLS12_KEY_SAFE_DERIVE:
	case CKM_TLS_MAC:
	case CKM_TLS_KDF:
		*ktype = CKK_GENERIC_SECRET;
		break;

	case CKM_RC2_KEY_GEN:
	case CKM_RC2_ECB:
	case CKM_RC2_CBC:
	case CKM_RC2_MAC:
	case CKM_RC2_MAC_GENERAL:
	case CKM_RC2_CBC_PAD:
	case CKM_PBE_SHA1_RC2_128_CBC:
	case CKM_PBE_SHA1_RC2_40_CBC:
		*ktype = CKK_RC2;
		break;

	case CKM_RC4_KEY_GEN:
	case CKM_RC4:
	case CKM_PBE_SHA1_RC4_128:
	case CKM_PBE_SHA1_RC4_40:
		*ktype = CKK_RC4;
		break;

	case CKM_DES_KEY_GEN:
	case CKM_DES_ECB:
	case CKM_DES_CBC:
	case CKM_DES_MAC:
	case CKM_DES_MAC_GENERAL:
	case CKM_DES_CBC_PAD:
	case CKM_PBE_MD2_DES_CBC:
	case CKM_PBE_MD5_DES_CBC:
	case CKM_DES_OFB64:
	case CKM_DES_OFB8:
	case CKM_DES_CFB64:
	case CKM_DES_CFB8:
	case CKM_DES_ECB_ENCRYPT_DATA:
	case CKM_DES_CBC_ENCRYPT_DATA:
		*ktype = CKK_DES;
		break;

	case CKM_DES2_KEY_GEN:
	case CKM_PBE_SHA1_DES2_EDE_CBC:
		*ktype = CKK_DES2;
		break;

	case CKM_DES3_KEY_GEN:
	case CKM_DES3_ECB:
	case CKM_DES3_CBC:
	case CKM_DES3_MAC:
	case CKM_DES3_MAC_GENERAL:
	case CKM_DES3_CBC_PAD:
	case CKM_PBE_SHA1_DES3_EDE_CBC:
	case CKM_DES3_ECB_ENCRYPT_DATA:
	case CKM_DES3_CBC_ENCRYPT_DATA:
		*ktype = CKK_DES3;
		break;

	case CKM_CAST_KEY_GEN:
	case CKM_CAST_ECB:
	case CKM_CAST_CBC:
	case CKM_CAST_MAC:
	case CKM_CAST_MAC_GENERAL:
	case CKM_CAST_CBC_PAD:
	case CKM_PBE_MD5_CAST_CBC:
		*ktype = CKK_CAST;
		break;

	case CKM_CAST3_KEY_GEN:
	case CKM_CAST3_ECB:
	case CKM_CAST3_CBC:
	case CKM_CAST3_MAC:
	case CKM_CAST3_MAC_GENERAL:
	case CKM_CAST3_CBC_PAD:
	case CKM_PBE_MD5_CAST3_CBC:
		*ktype = CKK_CAST3;
		break;

	case CKM_CAST128_KEY_GEN:
	case CKM_CAST128_ECB:
	case CKM_CAST128_CBC:
	case CKM_CAST128_MAC:
	case CKM_CAST128_MAC_GENERAL:
	case CKM_CAST128_CBC_PAD:
	case CKM_PBE_MD5_CAST128_CBC:
	case CKM_PBE_SHA1_CAST128_CBC:
		*ktype = CKK_CAST128;
		break;

	case CKM_RC5_KEY_GEN:
	case CKM_RC5_ECB:
	case CKM_RC5_CBC:
	case CKM_RC5_MAC:
	case CKM_RC5_MAC_GENERAL:
	case CKM_RC5_CBC_PAD:
		*ktype = CKK_RC5;
		break;

	case CKM_IDEA_KEY_GEN:
	case CKM_IDEA_ECB:
	case CKM_IDEA_CBC:
	case CKM_IDEA_MAC:
	case CKM_IDEA_MAC_GENERAL:
	case CKM_IDEA_CBC_PAD:
		*ktype = CKK_IDEA;
		break;

	case CKM_SKIPJACK_KEY_GEN:
	case CKM_SKIPJACK_ECB64:
	case CKM_SKIPJACK_CBC64:
	case CKM_SKIPJACK_OFB64:
	case CKM_SKIPJACK_CFB64:
	case CKM_SKIPJACK_CFB32:
	case CKM_SKIPJACK_CFB16:
	case CKM_SKIPJACK_CFB8:
	case CKM_SKIPJACK_WRAP:
	case CKM_SKIPJACK_PRIVATE_WRAP:
	case CKM_SKIPJACK_RELAYX:
		*ktype = CKK_SKIPJACK;
		break;

	case CKM_BATON_KEY_GEN:
	case CKM_BATON_ECB128:
	case CKM_BATON_ECB96:
	case CKM_BATON_CBC128:
	case CKM_BATON_COUNTER:
	case CKM_BATON_SHUFFLE:
	case CKM_BATON_WRAP:
		*ktype = CKK_BATON;
		break;

	case CKM_JUNIPER_KEY_GEN:
	case CKM_JUNIPER_ECB128:
	case CKM_JUNIPER_CBC128:
	case CKM_JUNIPER_COUNTER:
	case CKM_JUNIPER_SHUFFLE:
	case CKM_JUNIPER_WRAP:
		*ktype = CKK_JUNIPER;
		break;

	case CKM_CDMF_KEY_GEN:
	case CKM_CDMF_ECB:
	case CKM_CDMF_CBC:
	case CKM_CDMF_MAC:
	case CKM_CDMF_MAC_GENERAL:
	case CKM_CDMF_CBC_PAD:
		*ktype = CKK_CDMF;
		break;

	case CKM_AES_KEY_GEN:
	case CKM_AES_ECB:
	case CKM_AES_CBC:
	case CKM_AES_MAC:
	case CKM_AES_MAC_GENERAL:
	case CKM_AES_CBC_PAD:
	case CKM_AES_CTR:
	case CKM_AES_GCM:
	case CKM_AES_CCM:
	case CKM_AES_CTS:
	case CKM_AES_CMAC:
	case CKM_AES_CMAC_GENERAL:
	case CKM_AES_XCBC_MAC:
	case CKM_AES_XCBC_MAC_96:
	case CKM_AES_GMAC:
	case CKM_AES_ECB_ENCRYPT_DATA:
	case CKM_AES_CBC_ENCRYPT_DATA:
	case CKM_AES_OFB:
	case CKM_AES_CFB8:
	case CKM_AES_CFB64:
	case CKM_AES_CFB128:
	case CKM_AES_CFB1:
	case CKM_AES_KEY_WRAP:
	case CKM_AES_KEY_WRAP_PAD:
		*ktype = CKK_AES;
		break;

	case CKM_BLOWFISH_KEY_GEN:
	case CKM_BLOWFISH_CBC:
	case CKM_BLOWFISH_CBC_PAD:
		*ktype = CKK_BLOWFISH;
		break;

	case CKM_TWOFISH_KEY_GEN:
	case CKM_TWOFISH_CBC:
	case CKM_TWOFISH_CBC_PAD:
		*ktype = CKK_TWOFISH;
		break;

	case CKM_SECURID_KEY_GEN:
	case CKM_SECURID:
		*ktype = CKK_SECURID;
		break;

	case CKM_HOTP_KEY_GEN:
	case CKM_HOTP:
		*ktype = CKK_HOTP;
		break;

	case CKM_ACTI:
	case CKM_ACTI_KEY_GEN:
		*ktype = CKK_ACTI;
		break;

	case CKM_CAMELLIA_KEY_GEN:
	case CKM_CAMELLIA_ECB:
	case CKM_CAMELLIA_CBC:
	case CKM_CAMELLIA_MAC:
	case CKM_CAMELLIA_MAC_GENERAL:
	case CKM_CAMELLIA_CBC_PAD:
	case CKM_CAMELLIA_ECB_ENCRYPT_DATA:
	case CKM_CAMELLIA_CBC_ENCRYPT_DATA:
	case CKM_CAMELLIA_CTR:
		*ktype = CKK_CAMELLIA;
		break;

	case CKM_ARIA_KEY_GEN:
	case CKM_ARIA_ECB:
	case CKM_ARIA_CBC:
	case CKM_ARIA_MAC:
	case CKM_ARIA_MAC_GENERAL:
	case CKM_ARIA_CBC_PAD:
	case CKM_ARIA_ECB_ENCRYPT_DATA:
	case CKM_ARIA_CBC_ENCRYPT_DATA:
		*ktype = CKK_ARIA;
		break;

	case CKM_GOSTR3410:
	case CKM_GOSTR3410_WITH_GOSTR3411:
	case CKM_GOSTR3410_KEY_WRAP:
	case CKM_GOSTR3410_DERIVE:
		*ktype = CKK_GOSTR3410;
		break;

	case CKM_GOSTR3411:
	case CKM_GOSTR3411_HMAC:
		*ktype = CKK_GOSTR3411;
		break;

	case CKM_GOST28147_KEY_GEN:
	case CKM_GOST28147_ECB:
	case CKM_GOST28147:
	case CKM_GOST28147_MAC:
	case CKM_GOST28147_KEY_WRAP:
		*ktype = CKK_GOST28147;
		break;

	default:
		rv = CKR_MECHANISM_INVALID;
		break;
	}

	return (rv);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2016 Jason King
 */

/*
 * Convert Algorithm names as strings to PKCS#11 Mech numbers and vice versa.
 */

#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <security/cryptoki.h>
#include <security/pkcs11t.h>

#include <cryptoutil.h>

/*
 * This table is a one-to-one mapping between mechanism names and numbers.
 * As such, it should not contain deprecated mechanism names (aliases).
 */
typedef struct {
	const char		*str;
	CK_MECHANISM_TYPE	mech;
} pkcs11_mapping_t;

/*
 * Note: elements in this table MUST be in numeric order,
 * since bsearch(3C) is used to search this table.
 */
static const pkcs11_mapping_t mapping[] = {
	{ "CKM_RSA_PKCS_KEY_PAIR_GEN", CKM_RSA_PKCS_KEY_PAIR_GEN },
	{ "CKM_RSA_PKCS", CKM_RSA_PKCS },
	{ "CKM_RSA_9796", CKM_RSA_9796 },
	{ "CKM_RSA_X_509", CKM_RSA_X_509 },
	{ "CKM_MD2_RSA_PKCS", CKM_MD2_RSA_PKCS },
	{ "CKM_MD5_RSA_PKCS", CKM_MD5_RSA_PKCS },
	{ "CKM_SHA1_RSA_PKCS", CKM_SHA1_RSA_PKCS },
	{ "CKM_RIPEMD128_RSA_PKCS", CKM_RIPEMD128_RSA_PKCS },
	{ "CKM_RIPEMD160_RSA_PKCS", CKM_RIPEMD160_RSA_PKCS },
	{ "CKM_RSA_PKCS_OAEP", CKM_RSA_PKCS_OAEP },
	{ "CKM_RSA_X9_31_KEY_PAIR_GEN", CKM_RSA_X9_31_KEY_PAIR_GEN },
	{ "CKM_RSA_X9_31", CKM_RSA_X9_31 },
	{ "CKM_SHA1_RSA_X9_31", CKM_SHA1_RSA_X9_31 },
	{ "CKM_RSA_PKCS_PSS", CKM_RSA_PKCS_PSS },
	{ "CKM_SHA1_RSA_PKCS_PSS", CKM_SHA1_RSA_PKCS_PSS },
	{ "CKM_DSA_KEY_PAIR_GEN", CKM_DSA_KEY_PAIR_GEN },
	{ "CKM_DSA", CKM_DSA },
	{ "CKM_DSA_SHA1", CKM_DSA_SHA1 },
	{ "CKM_DSA_SHA224", CKM_DSA_SHA224 },
	{ "CKM_DSA_SHA256", CKM_DSA_SHA256 },
	{ "CKM_DSA_SHA384", CKM_DSA_SHA384 },
	{ "CKM_DSA_SHA512", CKM_DSA_SHA512 },
	{ "CKM_DH_PKCS_KEY_PAIR_GEN", CKM_DH_PKCS_KEY_PAIR_GEN },
	{ "CKM_DH_PKCS_DERIVE", CKM_DH_PKCS_DERIVE },
	{ "CKM_X9_42_DH_KEY_PAIR_GEN", CKM_X9_42_DH_KEY_PAIR_GEN },
	{ "CKM_X9_42_DH_DERIVE", CKM_X9_42_DH_DERIVE },
	{ "CKM_X9_42_DH_HYBRID_DERIVE", CKM_X9_42_DH_HYBRID_DERIVE },
	{ "CKM_X9_42_MQV_DERIVE", CKM_X9_42_MQV_DERIVE },
	{ "CKM_SHA256_RSA_PKCS", CKM_SHA256_RSA_PKCS },
	{ "CKM_SHA384_RSA_PKCS", CKM_SHA384_RSA_PKCS },
	{ "CKM_SHA512_RSA_PKCS", CKM_SHA512_RSA_PKCS },
	{ "CKM_SHA256_RSA_PKCS_PSS", CKM_SHA256_RSA_PKCS_PSS },
	{ "CKM_SHA384_RSA_PKCS_PSS", CKM_SHA384_RSA_PKCS_PSS },
	{ "CKM_SHA512_RSA_PKCS_PSS", CKM_SHA512_RSA_PKCS_PSS },
	{ "CKM_SHA224_RSA_PKCS", CKM_SHA224_RSA_PKCS },
	{ "CKM_SHA224_RSA_PKCS_PSS", CKM_SHA224_RSA_PKCS_PSS },
	{ "CKM_SHA512_224", CKM_SHA512_224 },
	{ "CKM_SHA512_224_HMAC", CKM_SHA512_224_HMAC },
	{ "CKM_SHA512_224_HMAC_GENERAL", CKM_SHA512_224_HMAC_GENERAL },
	{ "CKM_SHA512_224_KEY_DERIVATION", CKM_SHA512_224_KEY_DERIVATION },
	{ "CKM_SHA512_256", CKM_SHA512_256 },
	{ "CKM_SHA512_256_HMAC", CKM_SHA512_256_HMAC },
	{ "CKM_SHA512_256_HMAC_GENERAL", CKM_SHA512_256_HMAC_GENERAL },
	{ "CKM_SHA512_256_KEY_DERIVATION", CKM_SHA512_256_KEY_DERIVATION },
	{ "CKM_SHA512_T", CKM_SHA512_T },
	{ "CKM_SHA512_T_HMAC", CKM_SHA512_T_HMAC },
	{ "CKM_SHA512_T_HMAC_GENERAL", CKM_SHA512_T_HMAC_GENERAL },
	{ "CKM_SHA512_T_KEY_DERIVATION", CKM_SHA512_T_KEY_DERIVATION },
	{ "CKM_RC2_KEY_GEN", CKM_RC2_KEY_GEN },
	{ "CKM_RC2_ECB", CKM_RC2_ECB },
	{ "CKM_RC2_CBC", CKM_RC2_CBC },
	{ "CKM_RC2_MAC", CKM_RC2_MAC },
	{ "CKM_RC2_MAC_GENERAL", CKM_RC2_MAC_GENERAL },
	{ "CKM_RC2_CBC_PAD", CKM_RC2_CBC_PAD },
	{ "CKM_RC4_KEY_GEN", CKM_RC4_KEY_GEN },
	{ "CKM_RC4", CKM_RC4 },
	{ "CKM_DES_KEY_GEN", CKM_DES_KEY_GEN },
	{ "CKM_DES_ECB", CKM_DES_ECB },
	{ "CKM_DES_CBC", CKM_DES_CBC },
	{ "CKM_DES_MAC", CKM_DES_MAC },
	{ "CKM_DES_MAC_GENERAL", CKM_DES_MAC_GENERAL },
	{ "CKM_DES_CBC_PAD", CKM_DES_CBC_PAD },
	{ "CKM_DES2_KEY_GEN", CKM_DES2_KEY_GEN },
	{ "CKM_DES3_KEY_GEN", CKM_DES3_KEY_GEN },
	{ "CKM_DES3_ECB", CKM_DES3_ECB },
	{ "CKM_DES3_CBC", CKM_DES3_CBC },
	{ "CKM_DES3_MAC", CKM_DES3_MAC },
	{ "CKM_DES3_MAC_GENERAL", CKM_DES3_MAC_GENERAL },
	{ "CKM_DES3_CBC_PAD", CKM_DES3_CBC_PAD },
	{ "CKM_DES3_CMAC_GENERAL", CKM_DES3_CMAC_GENERAL },
	{ "CKM_DES3_CMAC", CKM_DES3_CMAC },
	{ "CKM_CDMF_KEY_GEN", CKM_CDMF_KEY_GEN },
	{ "CKM_CDMF_ECB", CKM_CDMF_ECB },
	{ "CKM_CDMF_CBC", CKM_CDMF_CBC },
	{ "CKM_CDMF_MAC", CKM_CDMF_MAC },
	{ "CKM_CDMF_MAC_GENERAL", CKM_CDMF_MAC_GENERAL },
	{ "CKM_CDMF_CBC_PAD", CKM_CDMF_CBC_PAD },
	{ "CKM_DES_OFB64", CKM_DES_OFB64 },
	{ "CKM_DES_OFB8", CKM_DES_OFB8 },
	{ "CKM_DES_CFB64", CKM_DES_CFB64 },
	{ "CKM_DES_CFB8", CKM_DES_CFB8 },
	{ "CKM_MD2", CKM_MD2 },
	{ "CKM_MD2_HMAC", CKM_MD2_HMAC },
	{ "CKM_MD2_HMAC_GENERAL", CKM_MD2_HMAC_GENERAL },
	{ "CKM_MD5", CKM_MD5 },
	{ "CKM_MD5_HMAC", CKM_MD5_HMAC },
	{ "CKM_MD5_HMAC_GENERAL", CKM_MD5_HMAC_GENERAL },
	{ "CKM_SHA_1", CKM_SHA_1 },
	{ "CKM_SHA_1_HMAC", CKM_SHA_1_HMAC },
	{ "CKM_SHA_1_HMAC_GENERAL", CKM_SHA_1_HMAC_GENERAL },
	{ "CKM_RIPEMD128", CKM_RIPEMD128 },
	{ "CKM_RIPEMD128_HMAC", CKM_RIPEMD128_HMAC },
	{ "CKM_RIPEMD128_HMAC_GENERAL", CKM_RIPEMD128_HMAC_GENERAL },
	{ "CKM_RIPEMD160", CKM_RIPEMD160 },
	{ "CKM_RIPEMD160_HMAC", CKM_RIPEMD160_HMAC },
	{ "CKM_RIPEMD160_HMAC_GENERAL", CKM_RIPEMD160_HMAC_GENERAL },
	{ "CKM_SHA256", CKM_SHA256 },
	{ "CKM_SHA256_HMAC", CKM_SHA256_HMAC },
	{ "CKM_SHA256_HMAC_GENERAL", CKM_SHA256_HMAC_GENERAL },
	{ "CKM_SHA224", CKM_SHA224 },
	{ "CKM_SHA224_HMAC", CKM_SHA224_HMAC },
	{ "CKM_SHA224_HMAC_GENERAL", CKM_SHA224_HMAC_GENERAL },
	{ "CKM_SHA384", CKM_SHA384 },
	{ "CKM_SHA384_HMAC", CKM_SHA384_HMAC },
	{ "CKM_SHA384_HMAC_GENERAL", CKM_SHA384_HMAC_GENERAL },
	{ "CKM_SHA512", CKM_SHA512 },
	{ "CKM_SHA512_HMAC", CKM_SHA512_HMAC },
	{ "CKM_SHA512_HMAC_GENERAL", CKM_SHA512_HMAC_GENERAL },
	{ "CKM_SECURID_KEY_GEN", CKM_SECURID_KEY_GEN },
	{ "CKM_SECURID", CKM_SECURID },
	{ "CKM_HOTP_KEY_GEN", CKM_HOTP_KEY_GEN },
	{ "CKM_HOTP", CKM_HOTP },
	{ "CKM_ACTI", CKM_ACTI },
	{ "CKM_ACTI_KEY_GEN", CKM_ACTI_KEY_GEN },
	{ "CKM_CAST_KEY_GEN", CKM_CAST_KEY_GEN },
	{ "CKM_CAST_ECB", CKM_CAST_ECB },
	{ "CKM_CAST_CBC", CKM_CAST_CBC },
	{ "CKM_CAST_MAC", CKM_CAST_MAC },
	{ "CKM_CAST_MAC_GENERAL", CKM_CAST_MAC_GENERAL },
	{ "CKM_CAST_CBC_PAD", CKM_CAST_CBC_PAD },
	{ "CKM_CAST3_KEY_GEN", CKM_CAST3_KEY_GEN },
	{ "CKM_CAST3_ECB", CKM_CAST3_ECB },
	{ "CKM_CAST3_CBC", CKM_CAST3_CBC },
	{ "CKM_CAST3_MAC", CKM_CAST3_MAC },
	{ "CKM_CAST3_MAC_GENERAL", CKM_CAST3_MAC_GENERAL },
	{ "CKM_CAST3_CBC_PAD", CKM_CAST3_CBC_PAD },
	{ "CKM_CAST5_KEY_GEN", CKM_CAST5_KEY_GEN },
	{ "CKM_CAST128_KEY_GEN", CKM_CAST128_KEY_GEN },
	{ "CKM_CAST5_ECB", CKM_CAST5_ECB },
	{ "CKM_CAST128_ECB", CKM_CAST128_ECB },
	{ "CKM_CAST5_CBC", CKM_CAST5_CBC },
	{ "CKM_CAST128_CBC", CKM_CAST128_CBC },
	{ "CKM_CAST5_MAC", CKM_CAST5_MAC },
	{ "CKM_CAST128_MAC", CKM_CAST128_MAC },
	{ "CKM_CAST5_MAC_GENERAL", CKM_CAST5_MAC_GENERAL },
	{ "CKM_CAST128_MAC_GENERAL", CKM_CAST128_MAC_GENERAL },
	{ "CKM_CAST5_CBC_PAD", CKM_CAST5_CBC_PAD },
	{ "CKM_CAST128_CBC_PAD", CKM_CAST128_CBC_PAD },
	{ "CKM_RC5_KEY_GEN", CKM_RC5_KEY_GEN },
	{ "CKM_RC5_ECB", CKM_RC5_ECB },
	{ "CKM_RC5_CBC", CKM_RC5_CBC },
	{ "CKM_RC5_MAC", CKM_RC5_MAC },
	{ "CKM_RC5_MAC_GENERAL", CKM_RC5_MAC_GENERAL },
	{ "CKM_RC5_CBC_PAD", CKM_RC5_CBC_PAD },
	{ "CKM_IDEA_KEY_GEN", CKM_IDEA_KEY_GEN },
	{ "CKM_IDEA_ECB", CKM_IDEA_ECB },
	{ "CKM_IDEA_CBC", CKM_IDEA_CBC },
	{ "CKM_IDEA_MAC", CKM_IDEA_MAC },
	{ "CKM_IDEA_MAC_GENERAL", CKM_IDEA_MAC_GENERAL },
	{ "CKM_IDEA_CBC_PAD", CKM_IDEA_CBC_PAD },
	{ "CKM_GENERIC_SECRET_KEY_GEN", CKM_GENERIC_SECRET_KEY_GEN },
	{ "CKM_CONCATENATE_BASE_AND_KEY", CKM_CONCATENATE_BASE_AND_KEY },
	{ "CKM_CONCATENATE_BASE_AND_DATA", CKM_CONCATENATE_BASE_AND_DATA },
	{ "CKM_CONCATENATE_DATA_AND_BASE", CKM_CONCATENATE_DATA_AND_BASE },
	{ "CKM_XOR_BASE_AND_DATA", CKM_XOR_BASE_AND_DATA },
	{ "CKM_EXTRACT_KEY_FROM_KEY", CKM_EXTRACT_KEY_FROM_KEY },
	{ "CKM_SSL3_PRE_MASTER_KEY_GEN", CKM_SSL3_PRE_MASTER_KEY_GEN },
	{ "CKM_SSL3_MASTER_KEY_DERIVE", CKM_SSL3_MASTER_KEY_DERIVE },
	{ "CKM_SSL3_KEY_AND_MAC_DERIVE", CKM_SSL3_KEY_AND_MAC_DERIVE },
	{ "CKM_SSL3_MASTER_KEY_DERIVE_DH", CKM_SSL3_MASTER_KEY_DERIVE_DH },
	{ "CKM_TLS_PRE_MASTER_KEY_GEN", CKM_TLS_PRE_MASTER_KEY_GEN },
	{ "CKM_TLS_MASTER_KEY_DERIVE", CKM_TLS_MASTER_KEY_DERIVE },
	{ "CKM_TLS_KEY_AND_MAC_DERIVE", CKM_TLS_KEY_AND_MAC_DERIVE },
	{ "CKM_TLS_MASTER_KEY_DERIVE_DH", CKM_TLS_MASTER_KEY_DERIVE_DH },
	{ "CKM_TLS_PRF", CKM_TLS_PRF },
	{ "CKM_SSL3_MD5_MAC", CKM_SSL3_MD5_MAC },
	{ "CKM_SSL3_SHA1_MAC", CKM_SSL3_SHA1_MAC },
	{ "CKM_MD5_KEY_DERIVATION", CKM_MD5_KEY_DERIVATION },
	{ "CKM_MD2_KEY_DERIVATION", CKM_MD2_KEY_DERIVATION },
	{ "CKM_SHA1_KEY_DERIVATION", CKM_SHA1_KEY_DERIVATION },
	{ "CKM_SHA256_KEY_DERIVATION", CKM_SHA256_KEY_DERIVATION },
	{ "CKM_SHA384_KEY_DERIVATION", CKM_SHA384_KEY_DERIVATION },
	{ "CKM_SHA512_KEY_DERIVATION", CKM_SHA512_KEY_DERIVATION },
	{ "CKM_SHA224_KEY_DERIVATION", CKM_SHA224_KEY_DERIVATION },
	{ "CKM_PBE_MD2_DES_CBC", CKM_PBE_MD2_DES_CBC },
	{ "CKM_PBE_MD5_DES_CBC", CKM_PBE_MD5_DES_CBC },
	{ "CKM_PBE_MD5_CAST_CBC", CKM_PBE_MD5_CAST_CBC },
	{ "CKM_PBE_MD5_CAST3_CBC", CKM_PBE_MD5_CAST3_CBC },
	{ "CKM_PBE_MD5_CAST5_CBC", CKM_PBE_MD5_CAST5_CBC },
	{ "CKM_PBE_MD5_CAST128_CBC", CKM_PBE_MD5_CAST128_CBC },
	{ "CKM_PBE_SHA1_CAST5_CBC", CKM_PBE_SHA1_CAST5_CBC },
	{ "CKM_PBE_SHA1_CAST128_CBC", CKM_PBE_SHA1_CAST128_CBC },
	{ "CKM_PBE_SHA1_RC4_128", CKM_PBE_SHA1_RC4_128 },
	{ "CKM_PBE_SHA1_RC4_40", CKM_PBE_SHA1_RC4_40 },
	{ "CKM_PBE_SHA1_DES3_EDE_CBC", CKM_PBE_SHA1_DES3_EDE_CBC },
	{ "CKM_PBE_SHA1_DES2_EDE_CBC", CKM_PBE_SHA1_DES2_EDE_CBC },
	{ "CKM_PBE_SHA1_RC2_128_CBC", CKM_PBE_SHA1_RC2_128_CBC },
	{ "CKM_PBE_SHA1_RC2_40_CBC", CKM_PBE_SHA1_RC2_40_CBC },
	{ "CKM_PKCS5_PBKD2", CKM_PKCS5_PBKD2 },
	{ "CKM_PBA_SHA1_WITH_SHA1_HMAC", CKM_PBA_SHA1_WITH_SHA1_HMAC },
	{ "CKM_WTLS_PRE_MASTER_KEY_GEN", CKM_WTLS_PRE_MASTER_KEY_GEN },
	{ "CKM_WTLS_MASTER_KEY_DERIVE", CKM_WTLS_MASTER_KEY_DERIVE },
	{ "CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC",
	    CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC },
	{ "CKM_WTLS_PRF", CKM_WTLS_PRF },
	{ "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE",
	    CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE },
	{ "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE",
	    CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE },
	{ "CKM_TLS10_MAC_SERVER", CKM_TLS10_MAC_SERVER },
	{ "CKM_TLS10_MAC_CLIENT", CKM_TLS10_MAC_CLIENT },
	{ "CKM_TLS12_MAC", CKM_TLS12_MAC },
	{ "CKM_TLS12_KDF", CKM_TLS12_KDF },
	{ "CKM_TLS12_MASTER_KEY_DERIVE", CKM_TLS12_MASTER_KEY_DERIVE },
	{ "CKM_TLS12_KEY_AND_MAC_DERIVE", CKM_TLS12_KEY_AND_MAC_DERIVE },
	{ "CKM_TLS12_MASTER_KEY_DERIVE_DH", CKM_TLS12_MASTER_KEY_DERIVE_DH },
	{ "CKM_TLS12_KEY_SAFE_DERIVE", CKM_TLS12_KEY_SAFE_DERIVE },
	{ "CKM_TLS_MAC", CKM_TLS_MAC },
	{ "CKM_TLS_KDF", CKM_TLS_KDF },
	{ "CKM_KEY_WRAP_LYNKS", CKM_KEY_WRAP_LYNKS },
	{ "CKM_KEY_WRAP_SET_OAEP", CKM_KEY_WRAP_SET_OAEP },
	{ "CKM_CMS_SIG", CKM_CMS_SIG },
	{ "CKM_KIP_DERIVE", CKM_KIP_DERIVE },
	{ "CKM_KIP_WRAP", CKM_KIP_WRAP },
	{ "CKM_KIP_MAC", CKM_KIP_MAC },
	{ "CKM_CAMELLIA_KEY_GEN", CKM_CAMELLIA_KEY_GEN },
	{ "CKM_CAMELLIA_ECB", CKM_CAMELLIA_ECB },
	{ "CKM_CAMELLIA_CBC", CKM_CAMELLIA_CBC },
	{ "CKM_CAMELLIA_MAC", CKM_CAMELLIA_MAC },
	{ "CKM_CAMELLIA_MAC_GENERAL", CKM_CAMELLIA_MAC_GENERAL },
	{ "CKM_CAMELLIA_CBC_PAD", CKM_CAMELLIA_CBC_PAD },
	{ "CKM_CAMELLIA_ECB_ENCRYPT_DATA", CKM_CAMELLIA_ECB_ENCRYPT_DATA },
	{ "CKM_CAMELLIA_CBC_ENCRYPT_DATA", CKM_CAMELLIA_CBC_ENCRYPT_DATA },
	{ "CKM_CAMELLIA_CTR", CKM_CAMELLIA_CTR },
	{ "CKM_ARIA_KEY_GEN", CKM_ARIA_KEY_GEN },
	{ "CKM_ARIA_ECB", CKM_ARIA_ECB },
	{ "CKM_ARIA_CBC", CKM_ARIA_CBC },
	{ "CKM_ARIA_MAC", CKM_ARIA_MAC },
	{ "CKM_ARIA_MAC_GENERAL", CKM_ARIA_MAC_GENERAL },
	{ "CKM_ARIA_CBC_PAD", CKM_ARIA_CBC_PAD },
	{ "CKM_ARIA_ECB_ENCRYPT_DATA", CKM_ARIA_ECB_ENCRYPT_DATA },
	{ "CKM_ARIA_CBC_ENCRYPT_DATA", CKM_ARIA_CBC_ENCRYPT_DATA },
	{ "CKM_SEED_KEY_GEN", CKM_SEED_KEY_GEN },
	{ "CKM_SEED_ECB", CKM_SEED_ECB },
	{ "CKM_SEED_CBC", CKM_SEED_CBC },
	{ "CKM_SEED_MAC", CKM_SEED_MAC },
	{ "CKM_SEED_MAC_GENERAL", CKM_SEED_MAC_GENERAL },
	{ "CKM_SEED_CBC_PAD", CKM_SEED_CBC_PAD },
	{ "CKM_SEED_ECB_ENCRYPT_DATA", CKM_SEED_ECB_ENCRYPT_DATA },
	{ "CKM_SEED_CBC_ENCRYPT_DATA", CKM_SEED_CBC_ENCRYPT_DATA },
	{ "CKM_SKIPJACK_KEY_GEN", CKM_SKIPJACK_KEY_GEN },
	{ "CKM_SKIPJACK_ECB64", CKM_SKIPJACK_ECB64 },
	{ "CKM_SKIPJACK_CBC64", CKM_SKIPJACK_CBC64 },
	{ "CKM_SKIPJACK_OFB64", CKM_SKIPJACK_OFB64 },
	{ "CKM_SKIPJACK_CFB64", CKM_SKIPJACK_CFB64 },
	{ "CKM_SKIPJACK_CFB32", CKM_SKIPJACK_CFB32 },
	{ "CKM_SKIPJACK_CFB16", CKM_SKIPJACK_CFB16 },
	{ "CKM_SKIPJACK_CFB8", CKM_SKIPJACK_CFB8 },
	{ "CKM_SKIPJACK_WRAP", CKM_SKIPJACK_WRAP },
	{ "CKM_SKIPJACK_PRIVATE_WRAP", CKM_SKIPJACK_PRIVATE_WRAP },
	{ "CKM_SKIPJACK_RELAYX", CKM_SKIPJACK_RELAYX },
	{ "CKM_KEA_KEY_PAIR_GEN", CKM_KEA_KEY_PAIR_GEN },
	{ "CKM_KEA_KEY_DERIVE", CKM_KEA_KEY_DERIVE },
	{ "CKM_KEA_DERIVE", CKM_KEA_DERIVE },
	{ "CKM_FORTEZZA_TIMESTAMP", CKM_FORTEZZA_TIMESTAMP },
	{ "CKM_BATON_KEY_GEN", CKM_BATON_KEY_GEN },
	{ "CKM_BATON_ECB128", CKM_BATON_ECB128 },
	{ "CKM_BATON_ECB96", CKM_BATON_ECB96 },
	{ "CKM_BATON_CBC128", CKM_BATON_CBC128 },
	{ "CKM_BATON_COUNTER", CKM_BATON_COUNTER },
	{ "CKM_BATON_SHUFFLE", CKM_BATON_SHUFFLE },
	{ "CKM_BATON_WRAP", CKM_BATON_WRAP },
	{ "CKM_ECDSA_KEY_PAIR_GEN", CKM_ECDSA_KEY_PAIR_GEN },
	{ "CKM_EC_KEY_PAIR_GEN", CKM_EC_KEY_PAIR_GEN },
	{ "CKM_ECDSA", CKM_ECDSA },
	{ "CKM_ECDSA_SHA1", CKM_ECDSA_SHA1 },
	{ "CKM_ECDSA_SHA224", CKM_ECDSA_SHA224 },
	{ "CKM_ECDSA_SHA256", CKM_ECDSA_SHA256 },
	{ "CKM_ECDSA_SHA384", CKM_ECDSA_SHA384 },
	{ "CKM_ECDSA_SHA512", CKM_ECDSA_SHA512 },
	{ "CKM_ECDH1_DERIVE", CKM_ECDH1_DERIVE },
	{ "CKM_ECDH1_COFACTOR_DERIVE", CKM_ECDH1_COFACTOR_DERIVE },
	{ "CKM_ECMQV_DERIVE", CKM_ECMQV_DERIVE },
	{ "CKM_ECDH_AES_KEY_WRAP", CKM_ECDH_AES_KEY_WRAP },
	{ "CKM_RSA_AES_KEY_WRAP", CKM_RSA_AES_KEY_WRAP },
	{ "CKM_JUNIPER_KEY_GEN", CKM_JUNIPER_KEY_GEN },
	{ "CKM_JUNIPER_ECB128", CKM_JUNIPER_ECB128 },
	{ "CKM_JUNIPER_CBC128", CKM_JUNIPER_CBC128 },
	{ "CKM_JUNIPER_COUNTER", CKM_JUNIPER_COUNTER },
	{ "CKM_JUNIPER_SHUFFLE", CKM_JUNIPER_SHUFFLE },
	{ "CKM_JUNIPER_WRAP", CKM_JUNIPER_WRAP },
	{ "CKM_FASTHASH", CKM_FASTHASH },
	{ "CKM_AES_KEY_GEN", CKM_AES_KEY_GEN },
	{ "CKM_AES_ECB", CKM_AES_ECB },
	{ "CKM_AES_CBC", CKM_AES_CBC },
	{ "CKM_AES_MAC", CKM_AES_MAC },
	{ "CKM_AES_MAC_GENERAL", CKM_AES_MAC_GENERAL },
	{ "CKM_AES_CBC_PAD", CKM_AES_CBC_PAD },
	{ "CKM_AES_CTR", CKM_AES_CTR },
	{ "CKM_AES_GCM", CKM_AES_GCM },
	{ "CKM_AES_CCM", CKM_AES_CCM },
	{ "CKM_AES_CTS", CKM_AES_CTS },
	{ "CKM_AES_CMAC", CKM_AES_CMAC },
	{ "CKM_AES_CMAC_GENERAL", CKM_AES_CMAC_GENERAL },
	{ "CKM_AES_XCBC_MAC", CKM_AES_XCBC_MAC },
	{ "CKM_AES_XCBC_MAC_96", CKM_AES_XCBC_MAC_96 },
	{ "CKM_AES_GMAC", CKM_AES_GMAC },
	{ "CKM_BLOWFISH_KEY_GEN", CKM_BLOWFISH_KEY_GEN },
	{ "CKM_BLOWFISH_CBC", CKM_BLOWFISH_CBC },
	{ "CKM_TWOFISH_KEY_GEN", CKM_TWOFISH_KEY_GEN },
	{ "CKM_TWOFISH_CBC", CKM_TWOFISH_CBC },
	{ "CKM_BLOWFISH_CBC_PAD", CKM_BLOWFISH_CBC_PAD },
	{ "CKM_TWOFISH_CBC_PAD", CKM_TWOFISH_CBC_PAD },
	{ "CKM_DES_ECB_ENCRYPT_DATA", CKM_DES_ECB_ENCRYPT_DATA },
	{ "CKM_DES_CBC_ENCRYPT_DATA", CKM_DES_CBC_ENCRYPT_DATA },
	{ "CKM_DES3_ECB_ENCRYPT_DATA", CKM_DES3_ECB_ENCRYPT_DATA },
	{ "CKM_DES3_CBC_ENCRYPT_DATA", CKM_DES3_CBC_ENCRYPT_DATA },
	{ "CKM_AES_ECB_ENCRYPT_DATA", CKM_AES_ECB_ENCRYPT_DATA },
	{ "CKM_AES_CBC_ENCRYPT_DATA", CKM_AES_CBC_ENCRYPT_DATA },
	{ "CKM_GOSTR3410_KEY_PAIR_GEN", CKM_GOSTR3410_KEY_PAIR_GEN },
	{ "CKM_GOSTR3410", CKM_GOSTR3410 },
	{ "CKM_GOSTR3410_WITH_GOSTR3411", CKM_GOSTR3410_WITH_GOSTR3411 },
	{ "CKM_GOSTR3410_KEY_WRAP", CKM_GOSTR3410_KEY_WRAP },
	{ "CKM_GOSTR3410_DERIVE", CKM_GOSTR3410_DERIVE },
	{ "CKM_GOSTR3411", CKM_GOSTR3411 },
	{ "CKM_GOSTR3411_HMAC", CKM_GOSTR3411_HMAC },
	{ "CKM_GOST28147_KEY_GEN", CKM_GOST28147_KEY_GEN },
	{ "CKM_GOST28147_ECB", CKM_GOST28147_ECB },
	{ "CKM_GOST28147", CKM_GOST28147 },
	{ "CKM_GOST28147_MAC", CKM_GOST28147_MAC },
	{ "CKM_GOST28147_KEY_WRAP", CKM_GOST28147_KEY_WRAP },
	{ "CKM_DSA_PARAMETER_GEN", CKM_DSA_PARAMETER_GEN },
	{ "CKM_DH_PKCS_PARAMETER_GEN", CKM_DH_PKCS_PARAMETER_GEN },
	{ "CKM_X9_42_DH_PARAMETER_GEN", CKM_X9_42_DH_PARAMETER_GEN },
	{ "CKM_DSA_PROBABLISTIC_PARAMETER_GEN",
	    CKM_DSA_PROBABLISTIC_PARAMETER_GEN },
	{ "CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN",
	    CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN },
	{ "CKM_AES_OFB", CKM_AES_OFB },
	{ "CKM_AES_CFB64", CKM_AES_CFB64 },
	{ "CKM_AES_CFB8", CKM_AES_CFB8 },
	{ "CKM_AES_CFB128", CKM_AES_CFB128 },
	{ "CKM_AES_CFB1", CKM_AES_CFB1 },
	{ "CKM_AES_KEY_WRAP", CKM_AES_KEY_WRAP },
	{ "CKM_AES_KEY_WRAP_PAD", CKM_AES_KEY_WRAP_PAD },
	{ "CKM_RSA_PKCS_TPM_1_1", CKM_RSA_PKCS_TPM_1_1 },
	{ "CKM_RSA_PKCS_OAEP_TPM_1_1", CKM_RSA_PKCS_OAEP_TPM_1_1 },
	/*
	 * Values >= 0x8000000 (CKM_VENDOR_DEFINED) are represented
	 * as strings with hexadecimal numbers (e.g., "0x8123456").
	 */
	{ NULL, 0 }
};


/*
 * pkcs11_mech_comp - compare two pkcs11_mapping_t structures
 *
 * Return a strcmp-like result (positive, zero, or negative).
 * For use with bsearch(3C) in pkcs11_mech2str().
 */
static int
pkcs11_mech_comp(const void *mapping1, const void *mapping2)
{
	return (((pkcs11_mapping_t *)mapping1)->mech -
	    ((pkcs11_mapping_t *)mapping2)->mech);
}


/*
 * pkcs11_mech2str - convert PKCS#11 mech to a string
 *
 * Anything below CKM_VENDOR_DEFINED that wasn't in the mapping table
 * at build time causes NULL to be returned.  Anything above it also
 * returns NULL since we have no way to know its real name.
 */
const char
*pkcs11_mech2str(CK_MECHANISM_TYPE mech)
{
	pkcs11_mapping_t	target;
	pkcs11_mapping_t	*result = NULL;

	if (mech >= CKM_VENDOR_DEFINED) {
		return (NULL);
	}

	/* Search for the mechanism number using bsearch(3C) */
	target.mech = mech;
	target.str = NULL;
	result = (pkcs11_mapping_t *)bsearch((void *)&target, (void *)mapping,
	    (sizeof (mapping) / sizeof (pkcs11_mapping_t)) - 1,
	    sizeof (pkcs11_mapping_t), pkcs11_mech_comp);
	if (result != NULL) {
		return (result->str);
	}

	return (NULL);
}

/*
 * pkcs11_str2mech - convert a string into a PKCS#11 mech number.
 *
 * Since there isn't a reserved value for an invalid mech we return
 * CKR_MECHANISM_INVALID for anything we don't recognise.
 * The value in mech isn't meaningful in these cases.
 */
CK_RV
pkcs11_str2mech(char *mech_str, CK_MECHANISM_TYPE_PTR mech)
{
	int	i;
	int	compare_off = 0;

	if (mech_str == NULL)
		return (CKR_MECHANISM_INVALID);

	if (strncasecmp(mech_str, "0x", 2) == 0) {
		long long llnum;
		cryptodebug("pkcs11_str2mech: hex string passed in: %s",
		    mech_str);
		llnum = strtoll(mech_str, NULL, 16);
		if ((llnum >= CKM_VENDOR_DEFINED) && (llnum <= UINT_MAX)) {
			*mech = llnum;
			return (CKR_OK);
		} else {
			return (CKR_MECHANISM_INVALID);
		}
	}

	/* If there's no CKM_ prefix, then ignore it in comparisons */
	if (strncasecmp(mech_str, "CKM_", 4) != 0) {
		cryptodebug("pkcs11_str2mech: no CKM_ prefix: %s", mech_str);
		cryptodebug("pkcs11_str2mech: with prefix: CKM_%s", mech_str);
		compare_off = 4;
	}

	/* Linear search for a matching string */
	for (i = 0; mapping[i].str; i++) {
		if (strcasecmp(&mapping[i].str[compare_off], mech_str) == 0) {
			*mech = mapping[i].mech;
			return (CKR_OK);
		}
	}

	return (CKR_MECHANISM_INVALID);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <locale.h>
#include <cryptoutil.h>

#define	MAX_PASS_TRIES		5	/* maximum tries to get passphrase */

#define	DEFAULT_TOKEN_PROMPT	gettext("Enter PIN for %s: ")
#define	DEFAULT_TOKEN_REPROMPT	gettext("Re-enter PIN for %s: ")
#define	DEFAULT_TOKEN_MINSIZE	gettext("PIN must be at least %d characters.\n")

#define	DEFAULT_USER_PROMPT	gettext("Enter passphrase: ")
#define	DEFAULT_USER_REPROMPT	gettext("Re-enter passphrase: ")
#define	DEFAULT_USER_MINSIZE	\
			gettext("Passphrase must be at least %d characters.\n")

#define	DEFAULT_PK11TOKEN	SOFT_TOKEN_LABEL

/*
 * Default token name
 */
char *
pkcs11_default_token(void)
{
	return (DEFAULT_PK11TOKEN);
}

/*
 * Prompt user for a passphrase or the PIN for a token.
 *
 * An optional minimum length can be enforced.  Caller can optionally also
 * reprompt for the passphrase/PIN to confirm it was entered correctly.
 * The caller must free the buffer containing the passphrase/PIN with free().
 * 0 returned for success, -1 for failure with the first passphrase/PIN,
 * -2 for failure with the optional second passphrase/PIN used to confirm.
 */
int
pkcs11_get_pass(char *token_name, char **pdata, size_t *psize, size_t min_psize,
    boolean_t with_confirmation)
{
	char	prompt[1024];
	char	*tmpbuf = NULL;
	char	*databuf = NULL;
	int	tries;

	if (token_name != NULL)
		(void) snprintf(prompt, sizeof (prompt), DEFAULT_TOKEN_PROMPT,
		    token_name);
	else
		(void) snprintf(prompt, sizeof (prompt), DEFAULT_USER_PROMPT);

	for (tries = MAX_PASS_TRIES; tries > 0; tries--) {
		tmpbuf = getpassphrase(prompt);
		if (tmpbuf == NULL)
			return (-1);

		if (strnlen(tmpbuf, min_psize) >= min_psize)
			break;

		if (token_name != NULL)
			(void) printf(DEFAULT_TOKEN_MINSIZE, min_psize);
		else
			(void) printf(DEFAULT_USER_MINSIZE, min_psize);
	}
	if (tries == 0) {
		(void) printf(gettext("Exceeded number of attempts.\n"));
		return (-1);
	}

	databuf = strdup(tmpbuf);
	(void) memset(tmpbuf, 0, strlen(tmpbuf));	/* clean up */
	if (databuf == NULL)
		return (-1);

	if (with_confirmation) {
		if (token_name != NULL)
			(void) snprintf(prompt, sizeof (prompt),
			    DEFAULT_TOKEN_REPROMPT, token_name);
		else
			(void) snprintf(prompt, sizeof (prompt),
			    DEFAULT_USER_REPROMPT);
		tmpbuf = getpassphrase(prompt);
		if (tmpbuf == NULL) {
			/* clean up */
			(void) memset(databuf, 0, strlen(databuf));
			free(databuf);
			return (-2);
		}

		if (strcmp(databuf, tmpbuf) != 0) {
			/* clean up */
			(void) memset(tmpbuf, 0, strlen(tmpbuf));
			(void) memset(databuf, 0, strlen(databuf));
			free(databuf);
			return (-2);
		}
	}

	*pdata = databuf;
	*psize = strlen(databuf);

	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */

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

#include <security/cryptoki.h>
#include <security/pkcs11.h>

#include <cryptoutil.h>

/* PKCS#11 URI prefix and attributes. */
#define	PK11_URI_PREFIX		"pkcs11:"
#define	PK11_TOKEN		"token"
#define	PK11_MANUF		"manufacturer"
#define	PK11_SERIAL		"serial"
#define	PK11_MODEL		"model"
#define	PK11_OBJECT		"object"
#define	PK11_OBJECTTYPE		"objecttype"
#define	PK11_ID			"id"
#define	PK11_PINFILE		"pinfile"

/*
 * Gets a hexadecimal string of the xx:xx:xx-like format and fills the output
 * buffer with bytes represeting each of the hexadecimal numbers. Returns 0 on
 * error (missing ':', not a hexadecimal character (eg. 'z'), output buffer
 * overflow, etc.), or the number of hexadecimal numbers processed.
 *
 * Returns:
 *	0
 *		on failure
 *	>0
 *		number of bytes returned via the output parameter
 */
static int
read_id(char *str, unsigned char *output, int out_len)
{
	int i, len, n;
	unsigned int x1, x2;

	len = strlen(str);
	(void) memset(output, 0, out_len);
	/* Counter of the processed bytes. */
	i = 0;
	/* Counter for the used output bytes. */
	n = 0;

	while (i < len) {
		/* We require at least one hexadecimal character. */
		if (sscanf(str + i, "%1x", &x1) != 1)
			return (0);
		++i;
		/* And we accept the 2nd one if it is there. */
		if (sscanf(str + i, "%1x", &x2) == 1) {
			x1 = x1 * 16 + x2;
			++i;
		}

		/* Output buffer overflow? */
		if ((n + 1) > out_len)
			return (0);
		output[n] = (unsigned char)x1;
		/* Still some bytes to process? */
		if (i < len) {
			/* ':' is the only acceptable delimiter. */
			if (str[i] != ':')
				return (0);
			/* Skip ':' */
			++i;
		}
		++n;
	}

	return (n);
}

/*
 * Process the PKCS#11 URI. The function expects an allocated URI structure. The
 * caller is later expected to call pkcs11_free_uri() when the parsed URI is no
 * longer needed.
 *
 * Returns:
 *      PK11_URI_OK
 *		success
 *      PK11_URI_INVALID
 *		invalid PKCS#11 URI (one that has the "pkcs11:" prefix but is
 *		otherwise incorrectly specified)
 *      PK11_MALLOC_ERROR
 *		malloc(3C) failed when allocating one of the internal buffers
 *      PK11_URI_VALUE_OVERFLOW
 *		some attributes in the URI are of the fixed length accroding to
 *		the spec. If any of those attributes overflows we report an
 *		error
 *      PK11_NOT_PKCS11_URI
 *		the URI supplied is not the PKCS#11 URI at all (does not have
 *		the "pkcs11:" prefix)
 */
int
pkcs11_parse_uri(const char *str, pkcs11_uri_t *uri)
{
	char *str2, *l1, *l2, *tok, *name;

	/* Initialize the structure. */
	(void) memset(uri, 0, sizeof (pkcs11_uri_t));
	/* Be really safe. */
	uri->objecttype_present = B_FALSE;

	/* Check that we have the correct PKCS#11 URI prefix. */
	if (strncmp(str, PK11_URI_PREFIX, strlen(PK11_URI_PREFIX)) != 0)
		return (PK11_NOT_PKCS11_URI);
	/* Dup the string and skip over the prefix then. */
	if ((str2 = strdup(str + strlen(PK11_URI_PREFIX))) == NULL)
		return (PK11_MALLOC_ERROR);

	/*
	 * Using strtok_r() would silently skip over multiple semicolons. We
	 * must check such situation before moving on. We must also avoid ';' as
	 * the first and the last character of the URI.
	 */
	if (strstr(str2, ";;") != NULL || str2[0] == ';' ||
	    (strlen(str2) > 0 && str2[strlen(str2) - 1] == ';'))
		goto bad_uri;

	/* Now parse the URI. */
	tok = strtok_r(str2, ";", &l1);
	for (; tok != NULL; tok = strtok_r(NULL, ";", &l1)) {
		/* "tok" is not empty so there will be something in "name". */
		name = strtok_r(tok, "=", &l2);
		/* Check whether there is '=' at all. */
		if (l2 == NULL)
			goto bad_uri;

		/*
		 * Fill out the URI structure. We do not accept duplicate
		 * attributes.
		 */
		if (strcmp(name, PK11_TOKEN) == 0) {
			/* Check for duplicity. */
			if (uri->token != NULL)
				goto bad_uri;
			if (strlen(l2) > 32)
				goto value_overflow;
			if ((uri->token = (unsigned char *)strdup(l2)) == NULL)
				goto malloc_failed;
		} else if (strcmp(name, PK11_MANUF) == 0) {
			/* Check for duplicity. */
			if (uri->manuf != NULL)
				goto bad_uri;
			if (strlen(l2) > 32)
				goto value_overflow;
			if ((uri->manuf = (unsigned char *)strdup(l2)) == NULL)
				goto malloc_failed;
		} else if (strcmp(name, PK11_SERIAL) == 0) {
			/* Check for duplicity. */
			if (uri->serial != NULL)
				goto bad_uri;
			if (strlen(l2) > 16)
				goto value_overflow;
			if ((uri->serial = (unsigned char *)strdup(l2)) == NULL)
				goto malloc_failed;
		} else if (strcmp(name, PK11_MODEL) == 0) {
			/* Check for duplicity. */
			if (uri->model != NULL)
				goto bad_uri;
			if (strlen(l2) > 16)
				goto value_overflow;
			if ((uri->model = (unsigned char *)strdup(l2)) == NULL)
				goto malloc_failed;
		} else if (strcmp(name, PK11_ID) == 0) {
			/* Check for duplicity. */
			if (uri->id_len != 0)
				goto bad_uri;
			/*
			 * We can have maximum of PK11_MAX_ID_LEN 2-byte
			 * numbers separated by ':'s, like
			 * 01:02:0A:FF:...
			 */
			if (strlen(l2) > PK11_MAX_ID_LEN * 2 +
			    PK11_MAX_ID_LEN - 1) {
				goto value_overflow;
			}
			if ((uri->id = malloc(PK11_MAX_ID_LEN)) == NULL)
				goto malloc_failed;
			uri->id_len = read_id(l2, uri->id,
			    PK11_MAX_ID_LEN);
			if (uri->id_len == 0)
				goto bad_uri;
		} else if (strcmp(name, PK11_OBJECT) == 0) {
			/* Check for duplicity. */
			if (uri->object != NULL)
				goto bad_uri;
			if (strlen(l2) > PK11_MAX_OBJECT_LEN)
				goto value_overflow;
			if ((uri->object = (unsigned char *)strdup(l2)) == NULL)
				goto malloc_failed;
		} else if (strcmp(name, PK11_OBJECTTYPE) == 0) {
			/*
			 * Check for duplicity. objecttype can not be empty, it
			 * would not make sense.
			 */
			if (uri->objecttype_present == CK_TRUE)
				goto bad_uri;
			if (strcmp(l2, "public") == 0)
				uri->objecttype = CKO_PUBLIC_KEY;
			else if (strcmp(l2, "private") == 0)
				uri->objecttype = CKO_PRIVATE_KEY;
			else if (strcmp(l2, "cert") == 0)
				uri->objecttype = CKO_CERTIFICATE;
			else if (strcmp(l2, "secretkey") == 0)
				uri->objecttype = CKO_SECRET_KEY;
			else if (strcmp(l2, "data") == 0)
				uri->objecttype = CKO_DATA;
			else
				goto bad_uri;
			uri->objecttype_present = CK_TRUE;
		} else if (strcmp(name, PK11_PINFILE) == 0)
			/* Check for duplicity. */
			if (uri->pinfile == NULL) {
				if (strlen(l2) > MAXPATHLEN)
					goto value_overflow;
				if ((uri->pinfile = strdup(l2)) == NULL)
					goto malloc_failed;
				/* Empty pinfile makes no sense. */
				if (uri->pinfile[0] == '\0')
					goto bad_uri;
			} else
				goto bad_uri;
		else
			/* Unknown attribute name. */
			goto bad_uri;
	}

	free(str2);
	return (PK11_URI_OK);
malloc_failed:
	free(str2);
	pkcs11_free_uri(uri);
	return (PK11_MALLOC_ERROR);
bad_uri:
	free(str2);
	pkcs11_free_uri(uri);
	return (PK11_URI_INVALID);
value_overflow:
	free(str2);
	pkcs11_free_uri(uri);
	return (PK11_URI_VALUE_OVERFLOW);
}

/*
 * Free the PKCS#11 URI structure attributes but do not free the structure
 * itself.
 */
void
pkcs11_free_uri(pkcs11_uri_t *uri)
{
	if (uri->object != NULL)
		free(uri->object);
	if (uri->token != NULL)
		free(uri->token);
	if (uri->manuf != NULL)
		free(uri->manuf);
	if (uri->serial != NULL)
		free(uri->serial);
	if (uri->model != NULL)
		free(uri->model);
	if (uri->id != NULL)
		free(uri->id);
	if (uri->pinfile != NULL)
		free(uri->pinfile);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2012 Milan Jurik. All rights reserved.
 * Copyright 2015 Jason King.
 */

/*
 * Block comment which describes the contents of this file.
 */

#include <stdio.h>
#include <security/cryptoki.h>

/*
 * pkcs11_strerror: returns a string representation of the given return code.
 * The string returned is static pointer.  It doesn't need to be free'd
 * by the caller.
 */
char *
pkcs11_strerror(CK_RV rv)
{
	static char errstr[128];

	switch (rv) {
		case CKR_OK:
			return ("CKR_OK");
		case CKR_CANCEL:
			return ("CKR_CANCEL");
		case CKR_HOST_MEMORY:
			return ("CKR_HOST_MEMORY");
		case CKR_SLOT_ID_INVALID:
			return ("CKR_SLOT_ID_INVALID");
		case CKR_GENERAL_ERROR:
			return ("CKR_GENERAL_ERROR");
		case CKR_FUNCTION_FAILED:
			return ("CKR_FUNCTION_FAILED");
		case CKR_ARGUMENTS_BAD:
			return ("CKR_ARGUMENTS_BAD");
		case CKR_NO_EVENT:
			return ("CKR_NO_EVENT");
		case CKR_NEED_TO_CREATE_THREADS:
			return ("CKR_NEED_TO_CREATE_THREADS");
		case CKR_CANT_LOCK:
			return ("CKR_CANT_LOCK");
		case CKR_ATTRIBUTE_READ_ONLY:
			return ("CKR_ATTRIBUTE_READ_ONLY");
		case CKR_ATTRIBUTE_SENSITIVE:
			return ("CKR_ATTRIBUTE_SENSITIVE");
		case CKR_ATTRIBUTE_TYPE_INVALID:
			return ("CKR_ATTRIBUTE_TYPE_INVALID");
		case CKR_ATTRIBUTE_VALUE_INVALID:
			return ("CKR_ATTRIBUTE_VALUE_INVALID");
		case CKR_ACTION_PROHIBITED:
			return ("CKR_ACTION_PROHIBITED");
		case CKR_DATA_INVALID:
			return ("CKR_DATA_INVALID");
		case CKR_DATA_LEN_RANGE:
			return ("CKR_DATA_LEN_RANGE");
		case CKR_DEVICE_ERROR:
			return ("CKR_DEVICE_ERROR");
		case CKR_DEVICE_MEMORY:
			return ("CKR_DEVICE_MEMORY");
		case CKR_DEVICE_REMOVED:
			return ("CKR_DEVICE_REMOVED");
		case CKR_ENCRYPTED_DATA_INVALID:
			return ("CKR_ENCRYPTED_DATA_INVALID");
		case CKR_ENCRYPTED_DATA_LEN_RANGE:
			return ("CKR_ENCRYPTED_DATA_LEN_RANGE");
		case CKR_FUNCTION_CANCELED:
			return ("CKR_FUNCTION_CANCELED");
		case CKR_FUNCTION_NOT_PARALLEL:
			return ("CKR_FUNCTION_NOT_PARALLEL");
		case CKR_FUNCTION_NOT_SUPPORTED:
			return ("CKR_FUNCTION_NOT_SUPPORTED");
		case CKR_KEY_HANDLE_INVALID:
			return ("CKR_KEY_HANDLE_INVALID");
		case CKR_KEY_SIZE_RANGE:
			return ("CKR_KEY_SIZE_RANGE");
		case CKR_KEY_TYPE_INCONSISTENT:
			return ("CKR_KEY_TYPE_INCONSISTENT");
		case CKR_KEY_NOT_NEEDED:
			return ("CKR_KEY_NOT_NEEDED");
		case CKR_KEY_CHANGED:
			return ("CKR_KEY_CHANGED");
		case CKR_KEY_NEEDED:
			return ("CKR_KEY_NEEDED");
		case CKR_KEY_INDIGESTIBLE:
			return ("CKR_KEY_INDIGESTIBLE");
		case CKR_KEY_FUNCTION_NOT_PERMITTED:
			return ("CKR_KEY_FUNCTION_NOT_PERMITTED");
		case CKR_KEY_NOT_WRAPPABLE:
			return ("CKR_KEY_NOT_WRAPPABLE");
		case CKR_KEY_UNEXTRACTABLE:
			return ("CKR_KEY_UNEXTRACTABLE");
		case CKR_MECHANISM_INVALID:
			return ("CKR_MECHANISM_INVALID");
		case CKR_MECHANISM_PARAM_INVALID:
			return ("CKR_MECHANISM_PARAM_INVALID");
		case CKR_OBJECT_HANDLE_INVALID:
			return ("CKR_OBJECT_HANDLE_INVALID");
		case CKR_OPERATION_ACTIVE:
			return ("CKR_OPERATION_ACTIVE");
		case CKR_OPERATION_NOT_INITIALIZED:
			return ("CKR_OPERATION_NOT_INITIALIZED");
		case CKR_PIN_INCORRECT:
			return ("CKR_PIN_INCORRECT");
		case CKR_PIN_INVALID:
			return ("CKR_PIN_INVALID");
		case CKR_PIN_LEN_RANGE:
			return ("CKR_PIN_LEN_RANGE");
		case CKR_PIN_EXPIRED:
			return ("CKR_PIN_EXPIRED");
		case CKR_PIN_LOCKED:
			return ("CKR_PIN_LOCKED");
		case CKR_SESSION_CLOSED:
			return ("CKR_SESSION_CLOSED");
		case CKR_SESSION_COUNT:
			return ("CKR_SESSION_COUNT");
		case CKR_SESSION_HANDLE_INVALID:
			return ("CKR_SESSION_HANDLE_INVALID");
		case CKR_SESSION_PARALLEL_NOT_SUPPORTED:
			return ("CKR_SESSION_PARALLEL_NOT_SUPPORTED");
		case CKR_SESSION_READ_ONLY:
			return ("CKR_SESSION_READ_ONLY");
		case CKR_SESSION_EXISTS:
			return ("CKR_SESSION_EXISTS");
		case CKR_SESSION_READ_ONLY_EXISTS:
			return ("CKR_SESSION_READ_ONLY_EXISTS");
		case CKR_SESSION_READ_WRITE_SO_EXISTS:
			return ("CKR_SESSION_READ_WRITE_SO_EXISTS");
		case CKR_SIGNATURE_INVALID:
			return ("CKR_SIGNATURE_INVALID");
		case CKR_SIGNATURE_LEN_RANGE:
			return ("CKR_SIGNATURE_LEN_RANGE");
		case CKR_TEMPLATE_INCOMPLETE:
			return ("CKR_TEMPLATE_INCOMPLETE");
		case CKR_TEMPLATE_INCONSISTENT:
			return ("CKR_TEMPLATE_INCONSISTENT");
		case CKR_TOKEN_NOT_PRESENT:
			return ("CKR_TOKEN_NOT_PRESENT");
		case CKR_TOKEN_NOT_RECOGNIZED:
			return ("CKR_TOKEN_NOT_RECOGNIZED");
		case CKR_TOKEN_WRITE_PROTECTED:
			return ("CKR_TOKEN_WRITE_PROTECTED");
		case CKR_UNWRAPPING_KEY_HANDLE_INVALID:
			return ("CKR_UNWRAPPING_KEY_HANDLE_INVALID");
		case CKR_UNWRAPPING_KEY_SIZE_RANGE:
			return ("CKR_UNWRAPPING_KEY_SIZE_RANGE");
		case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT:
			return ("CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT");
		case CKR_USER_ALREADY_LOGGED_IN:
			return ("CKR_USER_ALREADY_LOGGED_IN");
		case CKR_USER_NOT_LOGGED_IN:
			return ("CKR_USER_NOT_LOGGED_IN");
		case CKR_USER_PIN_NOT_INITIALIZED:
			return ("CKR_USER_PIN_NOT_INITIALIZED");
		case CKR_USER_TYPE_INVALID:
			return ("CKR_USER_TYPE_INVALID");
		case CKR_USER_ANOTHER_ALREADY_LOGGED_IN:
			return ("CKR_USER_ANOTHER_ALREADY_LOGGED_IN");
		case CKR_USER_TOO_MANY_TYPES:
			return ("CKR_USER_TOO_MANY_TYPES");
		case CKR_WRAPPED_KEY_INVALID:
			return ("CKR_WRAPPED_KEY_INVALID");
		case CKR_WRAPPED_KEY_LEN_RANGE:
			return ("CKR_WRAPPED_KEY_LEN_RANGE");
		case CKR_WRAPPING_KEY_HANDLE_INVALID:
			return ("CKR_WRAPPING_KEY_HANDLE_INVALID");
		case CKR_WRAPPING_KEY_SIZE_RANGE:
			return ("CKR_WRAPPING_KEY_SIZE_RANGE");
		case CKR_WRAPPING_KEY_TYPE_INCONSISTENT:
			return ("CKR_WRAPPING_KEY_TYPE_INCONSISTENT");
		case CKR_RANDOM_SEED_NOT_SUPPORTED:
			return ("CKR_RANDOM_SEED_NOT_SUPPORTED");
		case CKR_RANDOM_NO_RNG:
			return ("CKR_RANDOM_NO_RNG");
		case CKR_DOMAIN_PARAMS_INVALID:
			return ("CKR_DOMAIN_PARAMS_INVALID");
		case CKR_CURVE_NOT_SUPPORTED:
			return ("CLR_CURVE_NOT_SUPPORTED");
		case CKR_BUFFER_TOO_SMALL:
			return ("CKR_BUFFER_TOO_SMALL");
		case CKR_SAVED_STATE_INVALID:
			return ("CKR_SAVED_STATE_INVALID");
		case CKR_INFORMATION_SENSITIVE:
			return ("CKR_INFORMATION_SENSITIVE");
		case CKR_STATE_UNSAVEABLE:
			return ("CKR_STATE_UNSAVEABLE");
		case CKR_CRYPTOKI_NOT_INITIALIZED:
			return ("CKR_CRYPTOKI_NOT_INITIALIZED");
		case CKR_CRYPTOKI_ALREADY_INITIALIZED:
			return ("CKR_CRYPTOKI_ALREADY_INITIALIZED");
		case CKR_MUTEX_BAD:
			return ("CKR_MUTEX_BAD");
		case CKR_MUTEX_NOT_LOCKED:
			return ("CKR_MUTEX_NOT_LOCKED");
		case CKR_NEW_PIN_MODE:
			return ("CKR_NEW_PIN_MODE");
		case CKR_NEXT_OTP:
			return ("CKR_NEXT_OTP");
		case CKR_EXCEEDED_MAX_ITERATIONS:
			return ("CKR_EXCEEDED_MAX_ITERATIONS");
		case CKR_FIPS_SELF_TEST_FAILED:
			return ("CKR_FIPS_SELF_TEST_FAILED");
		case CKR_LIBRARY_LOAD_FAILED:
			return ("CKR_LIBRARY_LOAD_FAILED");
		case CKR_PIN_TOO_WEAK:
			return ("CKR_PIN_TOO_WEAK");
		case CKR_PUBLIC_KEY_INVALID:
			return ("CKR_PUBLIC_KEY_INVALID");
		case CKR_FUNCTION_REJECTED:
			return ("CKR_FUNCTION_REJECTED");
		case CKR_VENDOR_DEFINED:
			return ("CKR_VENDOR_DEFINED");
		default:
			/* rv not found */
			(void) snprintf(errstr, sizeof (errstr),
			    "Unknown return code: 0x%lx", rv);
			return (errstr);
	}
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2014, OmniTI Computer Consulting, Inc. All rights reserved.
 */

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <locale.h>
#include <stdarg.h>
#include <cryptoutil.h>
#include <pthread.h>

#pragma init(pkcs11_random_init)

static pthread_mutex_t	random_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t	urandom_mutex = PTHREAD_MUTEX_INITIALIZER;

static pthread_mutex_t	random_seed_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t	urandom_seed_mutex = PTHREAD_MUTEX_INITIALIZER;

#define	RANDOM_DEVICE		"/dev/random"	/* random device name */
#define	URANDOM_DEVICE		"/dev/urandom"	/* urandom device name */

static int	random_fd = -1;
static int	urandom_fd = -1;

static int	random_seed_fd = -1;
static int	urandom_seed_fd = -1;


/*
 * Equivalent of open(2) insulated from EINTR.
 * Also sets close-on-exec.
 */
int
open_nointr(const char *path, int oflag, ...)
{
	int	fd;
	mode_t	pmode;
	va_list	alist;

	va_start(alist, oflag);
	pmode = va_arg(alist, mode_t);
	va_end(alist);

	do {
		if ((fd = open(path, oflag, pmode)) >= 0) {
			(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
			break;
		}
		/* errno definitely set by failed open() */
	} while (errno == EINTR);
	return (fd);
}

/*
 * Equivalent of read(2) insulated from EINTR.
 */
ssize_t
readn_nointr(int fd, void *dbuf, size_t dlen)
{
	char	*marker = dbuf;
	size_t	left = dlen;
	ssize_t	nread = 0, err;

	for (err = 0; left > 0 && nread != -1; marker += nread, left -= nread) {
		if ((nread = read(fd, marker, left)) < 0) {
			if (errno == EINTR) {	/* keep trying */
				nread = 0;
				continue;
			}
			err = nread;		/* hard error */
			break;
		} else if (nread == 0) {
			break;
		}
	}
	return (err != 0 ? err : dlen - left);
}

/*
 * Equivalent of write(2) insulated from EINTR.
 */
ssize_t
writen_nointr(int fd, void *dbuf, size_t dlen)
{
	char	*marker = dbuf;
	size_t	left = dlen;
	ssize_t	nwrite = 0, err;

	for (err = 0; left > 0 && nwrite != -1; marker += nwrite,
	    left -= nwrite) {
		if ((nwrite = write(fd, marker, left)) < 0) {
			if (errno == EINTR) {	/* keep trying */
				nwrite = 0;
				continue;
			}
			err = nwrite;		/* hard error */
			break;
		} else if (nwrite == 0) {
			break;
		}
	}
	return (err != 0 ? err : dlen - left);
}

/*
 * Opens the random number generator devices if not already open.
 * Always returns the opened fd of the device, or error.
 */
static int
pkcs11_open_common(int *fd, pthread_mutex_t *mtx, const char *dev, int oflag)
{
	(void) pthread_mutex_lock(mtx);
	if (*fd < 0)
		*fd = open_nointr(dev, oflag);
	(void) pthread_mutex_unlock(mtx);

	return (*fd);
}

static int
pkcs11_open_random(void)
{
	return (pkcs11_open_common(&random_fd, &random_mutex,
	    RANDOM_DEVICE, O_RDONLY));
}

static int
pkcs11_open_urandom(void)
{
	return (pkcs11_open_common(&urandom_fd, &urandom_mutex,
	    URANDOM_DEVICE, O_RDONLY));
}

static int
pkcs11_open_random_seed(void)
{
	return (pkcs11_open_common(&random_seed_fd, &random_seed_mutex,
	    RANDOM_DEVICE, O_WRONLY));
}

static int
pkcs11_open_urandom_seed(void)
{
	return (pkcs11_open_common(&urandom_seed_fd, &urandom_seed_mutex,
	    URANDOM_DEVICE, O_WRONLY));
}

/*
 * Close the random number generator devices if already open.
 */
static void
pkcs11_close_common(int *fd, pthread_mutex_t *mtx)
{
	(void) pthread_mutex_lock(mtx);
	(void) close(*fd);
	*fd = -1;
	(void) pthread_mutex_unlock(mtx);
}

static void
pkcs11_close_random(void)
{
	pkcs11_close_common(&random_fd, &random_mutex);
}

static void
pkcs11_close_urandom(void)
{
	pkcs11_close_common(&urandom_fd, &urandom_mutex);
}

static void
pkcs11_close_random_seed(void)
{
	pkcs11_close_common(&random_seed_fd, &random_seed_mutex);
}

static void
pkcs11_close_urandom_seed(void)
{
	pkcs11_close_common(&urandom_seed_fd, &urandom_seed_mutex);
}

/*
 * Read from the random number generator devices.
 */
static size_t
pkcs11_read_common(int *fd, pthread_mutex_t *mtx, void *dbuf, size_t dlen)
{
	size_t	n;

	(void) pthread_mutex_lock(mtx);
	n = readn_nointr(*fd, dbuf, dlen);
	(void) pthread_mutex_unlock(mtx);

	return (n);
}

static size_t
pkcs11_read_random(void *dbuf, size_t dlen)
{
	return (pkcs11_read_common(&random_fd, &random_mutex, dbuf, dlen));
}

static size_t
pkcs11_read_urandom(void *dbuf, size_t dlen)
{
	return (pkcs11_read_common(&urandom_fd, &urandom_mutex, dbuf, dlen));
}

/*
 * Write to the random number generator devices.
 */
static size_t
pkcs11_write_common(int *fd, pthread_mutex_t *mtx, void *dbuf, size_t dlen)
{
	size_t	n;

	(void) pthread_mutex_lock(mtx);
	n = writen_nointr(*fd, dbuf, dlen);
	(void) pthread_mutex_unlock(mtx);

	return (n);
}

static size_t
pkcs11_write_random_seed(void *dbuf, size_t dlen)
{
	return (pkcs11_write_common(&random_seed_fd, &random_seed_mutex,
	    dbuf, dlen));
}

static size_t
pkcs11_write_urandom_seed(void *dbuf, size_t dlen)
{
	return (pkcs11_write_common(&urandom_seed_fd, &urandom_seed_mutex,
	    dbuf, dlen));
}

/*
 * Seed /dev/random with the data in the buffer.
 */
int
pkcs11_seed_random(void *sbuf, size_t slen)
{
	int	rv;

	if (sbuf == NULL || slen == 0)
		return (0);

	/* Seeding error could mean it's not supported (errno = EACCES) */
	if (pkcs11_open_random_seed() < 0)
		return (-1);

	rv = -1;
	if (pkcs11_write_random_seed(sbuf, slen) == slen)
		rv = 0;

	pkcs11_close_random_seed();
	return (rv);
}

/*
 * Seed /dev/urandom with the data in the buffer.
 */
int
pkcs11_seed_urandom(void *sbuf, size_t slen)
{
	int	rv;

	if (sbuf == NULL || slen == 0)
		return (0);

	/* Seeding error could mean it's not supported (errno = EACCES) */
	if (pkcs11_open_urandom_seed() < 0)
		return (-1);

	rv = -1;
	if (pkcs11_write_urandom_seed(sbuf, slen) == slen)
		rv = 0;

	pkcs11_close_urandom_seed();
	return (rv);
}

/*
 * Put the requested amount of random data into a preallocated buffer.
 * Good for token key data, persistent objects.
 */
int
pkcs11_get_random(void *dbuf, size_t dlen)
{
	if (dbuf == NULL || dlen == 0)
		return (0);

	/* Read random data directly from /dev/random */
	if (pkcs11_open_random() < 0)
		return (-1);

	if (pkcs11_read_random(dbuf, dlen) == dlen)
		return (0);
	return (-1);
}

/*
 * Put the requested amount of random data into a preallocated buffer.
 * Good for passphrase salts, initialization vectors.
 */
int
pkcs11_get_urandom(void *dbuf, size_t dlen)
{
	if (dbuf == NULL || dlen == 0)
		return (0);

	/* Read random data directly from /dev/urandom */
	if (pkcs11_open_urandom() < 0)
		return (-1);

	if (pkcs11_read_urandom(dbuf, dlen) == dlen)
		return (0);
	return (-1);
}

/*
 * Same as pkcs11_get_urandom but ensures non zero data.
 */
int
pkcs11_get_nzero_urandom(void *dbuf, size_t dlen)
{
	char	extrarand[32];
	size_t	bytesleft = 0;
	size_t	i = 0;

	/* Start with some random data */
	if (pkcs11_get_urandom(dbuf, dlen) < 0)
		return (-1);

	/* Walk through data replacing any 0 bytes with more random data */
	while (i < dlen) {
		if (((char *)dbuf)[i] != 0) {
			i++;
			continue;
		}

		if (bytesleft == 0) {
			bytesleft = sizeof (extrarand);
			if (pkcs11_get_urandom(extrarand, bytesleft) < 0)
				return (-1);
		}
		bytesleft--;

		((char *)dbuf)[i] = extrarand[bytesleft];
	}
	return (0);
}

static void
pkcs11_random_prepare(void)
{
	/*
	 * NOTE - None of these are acquired more than one at a time.
	 * I can therefore acquire all four without fear of deadlock.
	 */
	(void) pthread_mutex_lock(&random_mutex);
	(void) pthread_mutex_lock(&urandom_mutex);
	(void) pthread_mutex_lock(&random_seed_mutex);
	(void) pthread_mutex_lock(&urandom_seed_mutex);
}

static void
pkcs11_random_parent_post(void)
{
	/* Drop the mutexes and get back to work! */
	(void) pthread_mutex_unlock(&urandom_seed_mutex);
	(void) pthread_mutex_unlock(&random_seed_mutex);
	(void) pthread_mutex_unlock(&urandom_mutex);
	(void) pthread_mutex_unlock(&random_mutex);
}

static void
pkcs11_random_child_post(void)
{
	pkcs11_random_parent_post();

	/* Also, close the FDs, just in case. */
	pkcs11_close_random();
	pkcs11_close_urandom();
	pkcs11_close_random_seed();
	pkcs11_close_urandom_seed();
}

static void
pkcs11_random_init(void)
{
	(void) pthread_atfork(pkcs11_random_prepare, pkcs11_random_parent_post,
	    pkcs11_random_child_post);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <sys/types.h>
#include <errno.h>
#include <ctype.h>

#include <cryptoutil.h>

/*
 * tohexstr
 * IN	bytes
 *	blen
 *	hexlen should be 2 * blen + 1
 * OUT
 *	hexstr
 */
void
tohexstr(uchar_t *bytes, size_t blen, char *hexstr, size_t hexlen)
{
	size_t i;
	char hexlist[] = "0123456789abcdef";

	for (i = 0; i < blen; i++) {
		if (hexlen < (2 * i + 1))
			break;
		hexstr[2 * i] = hexlist[(bytes[i] >> 4) & 0xf];
		hexstr[2 * i + 1] = hexlist[bytes[i] & 0xf];
	}
	hexstr[2 * blen] = '\0';
}

/*
 * This function takes a char[] and length of hexadecimal values and
 * returns a malloc'ed byte array with the length of that new byte array.
 * The caller needs to provide a pointer to where this new malloc'ed byte array
 * will be passed back; as well as, a pointer for the length of the new
 * byte array.
 *
 * The caller is responsible for freeing the malloc'ed array when done
 *
 * The return code is 0 if successful, otherwise the errno value is returned.
 */
int
hexstr_to_bytes(char *hexstr, size_t hexlen, uchar_t **bytes, size_t *blen)
{
	int i, ret = 0;
	unsigned char ch;
	uchar_t *b = NULL;

	*bytes = NULL;
	*blen = 0;

	if (hexstr == NULL || (hexlen % 2 == 1))
		return (EINVAL);

	if (hexstr[0] == '0' && ((hexstr[1] == 'x') || (hexstr[1] == 'X'))) {
		hexstr += 2;
		hexlen -= 2;
	}

	*blen = (hexlen / 2);

	b = malloc(*blen);
	if (b == NULL) {
		*blen = 0;
		return (errno);
	}

	for (i = 0; i < hexlen; i++) {
		ch = (unsigned char) *hexstr;

		if (!isxdigit(ch)) {
			ret = EINVAL;
			goto out;
		}

		hexstr++;

		if ((ch >= '0') && (ch <= '9'))
			ch -= '0';
		else if ((ch >= 'A') && (ch <= 'F'))
			ch = ch - 'A' + 10;
		else if ((ch >= 'a') && (ch <= 'f'))
			ch = ch - 'a' + 10;

		if (i & 1)
			b[i/2] |= ch;
		else
			b[i/2] = (ch << 4);
	}

out:
	if (b != NULL && ret != 0) {
		free(b);
		*blen = 0;
	} else
		*bytes = b;

	return (ret);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2018, Joyent, Inc.
 */

#include <cryptoutil.h>
#include <strings.h>
#include <stdio.h>
#include <tzfile.h>
#include <sys/crypto/common.h>

/*
 * In order to fit everything on one line, the 'CRYPTO_' prefix
 * has been dropped from the KCF #defines, e.g.
 * CRYPTO_SUCCESS becomes SUCCESS.
 */

static CK_RV error_number_table[CRYPTO_LAST_ERROR + 1] = {
CKR_OK,					/* SUCCESS */
CKR_CANCEL,				/* CANCEL */
CKR_HOST_MEMORY,			/* HOST_MEMORY */
CKR_GENERAL_ERROR,			/* GENERAL_ERROR */
CKR_FUNCTION_FAILED,			/* FAILED */
CKR_ARGUMENTS_BAD,			/* ARGUMENTS_BAD */
CKR_ATTRIBUTE_READ_ONLY,		/* ATTRIBUTE_READ_ONLY */
CKR_ATTRIBUTE_SENSITIVE,		/* ATTRIBUTE_SENSITIVE */
CKR_ATTRIBUTE_TYPE_INVALID,		/* ATTRIBUTE_TYPE_INVALID */
CKR_ATTRIBUTE_VALUE_INVALID,		/* ATTRIBUTE_VALUE_INVALID */
CKR_FUNCTION_FAILED,			/* CANCELED */
CKR_DATA_INVALID,			/* DATA_INVALID */
CKR_DATA_LEN_RANGE,			/* DATA_LEN_RANGE */
CKR_DEVICE_ERROR,			/* DEVICE_ERROR */
CKR_DEVICE_MEMORY,			/* DEVICE_MEMORY */
CKR_DEVICE_REMOVED,			/* DEVICE_REMOVED */
CKR_ENCRYPTED_DATA_INVALID,		/* ENCRYPTED_DATA_INVALID */
CKR_ENCRYPTED_DATA_LEN_RANGE,		/* ENCRYPTED_DATA_LEN_RANGE */
CKR_KEY_HANDLE_INVALID,			/* KEY_HANDLE_INVALID */
CKR_KEY_SIZE_RANGE,			/* KEY_SIZE_RANGE */
CKR_KEY_TYPE_INCONSISTENT,		/* KEY_TYPE_INCONSISTENT */
CKR_KEY_NOT_NEEDED,			/* KEY_NOT_NEEDED */
CKR_KEY_CHANGED,			/* KEY_CHANGED */
CKR_KEY_NEEDED,				/* KEY_NEEDED */
CKR_KEY_INDIGESTIBLE,			/* KEY_INDIGESTIBLE */
CKR_KEY_FUNCTION_NOT_PERMITTED,		/* KEY_FUNCTION_NOT_PERMITTED */
CKR_KEY_NOT_WRAPPABLE,			/* KEY_NOT_WRAPPABLE */
CKR_KEY_UNEXTRACTABLE,			/* KEY_UNEXTRACTABLE */
CKR_MECHANISM_INVALID,			/* MECHANISM_INVALID */
CKR_MECHANISM_PARAM_INVALID,		/* MECHANISM_PARAM_INVALID */
CKR_OBJECT_HANDLE_INVALID,		/* OBJECT_HANDLE_INVALID */
CKR_OPERATION_ACTIVE,			/* OPERATION_ACTIVE */
CKR_OPERATION_NOT_INITIALIZED,		/* OPERATION_NOT_INITIALIZED */
CKR_PIN_INCORRECT,			/* PIN_INCORRECT */
CKR_PIN_INVALID,			/* PIN_INVALID */
CKR_PIN_LEN_RANGE,			/* PIN_LEN_RANGE */
CKR_PIN_EXPIRED,			/* PIN_EXPIRED */
CKR_PIN_LOCKED,				/* PIN_LOCKED */
CKR_SESSION_CLOSED,			/* SESSION_CLOSED */
CKR_SESSION_COUNT,			/* SESSION_COUNT */
CKR_SESSION_HANDLE_INVALID,		/* SESSION_HANDLE_INVALID */
CKR_SESSION_READ_ONLY,			/* SESSION_READ_ONLY */
CKR_SESSION_EXISTS,			/* SESSION_EXISTS */
CKR_SESSION_READ_ONLY_EXISTS,		/* SESSION_READ_ONLY_EXISTS */
CKR_SESSION_READ_WRITE_SO_EXISTS,	/* SESSION_READ_WRITE_SO_EXISTS */
CKR_SIGNATURE_INVALID,			/* SIGNATURE_INVALID */
CKR_SIGNATURE_LEN_RANGE,		/* SIGNATURE_LEN_RANGE */
CKR_TEMPLATE_INCOMPLETE,		/* TEMPLATE_INCOMPLETE */
CKR_TEMPLATE_INCONSISTENT,		/* TEMPLATE_INCONSISTENT */
CKR_UNWRAPPING_KEY_HANDLE_INVALID,	/* UNWRAPPING_KEY_HANDLE_INVALID */
CKR_UNWRAPPING_KEY_SIZE_RANGE,		/* UNWRAPPING_KEY_SIZE_RANGE */
CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT,	/* UNWRAPPING_KEY_TYPE_INCONSISTENT */
CKR_USER_ALREADY_LOGGED_IN,		/* USER_ALREADY_LOGGED_IN */
CKR_USER_NOT_LOGGED_IN,			/* USER_NOT_LOGGED_IN */
CKR_USER_PIN_NOT_INITIALIZED,		/* USER_PIN_NOT_INITIALIZED */
CKR_USER_TYPE_INVALID,			/* USER_TYPE_INVALID */
CKR_USER_ANOTHER_ALREADY_LOGGED_IN,	/* USER_ANOTHER_ALREADY_LOGGED_IN */
CKR_USER_TOO_MANY_TYPES,		/* USER_TOO_MANY_TYPES */
CKR_WRAPPED_KEY_INVALID,		/* WRAPPED_KEY_INVALID */
CKR_WRAPPED_KEY_LEN_RANGE,		/* WRAPPED_KEY_LEN_RANGE */
CKR_WRAPPING_KEY_HANDLE_INVALID,	/* WRAPPING_KEY_HANDLE_INVALID */
CKR_WRAPPING_KEY_SIZE_RANGE,		/* WRAPPING_KEY_SIZE_RANGE */
CKR_WRAPPING_KEY_TYPE_INCONSISTENT,	/* WRAPPING_KEY_TYPE_INCONSISTENT */
CKR_RANDOM_SEED_NOT_SUPPORTED,		/* RANDOM_SEED_NOT_SUPPORTED */
CKR_RANDOM_NO_RNG,			/* RANDOM_NO_RNG */
CKR_DOMAIN_PARAMS_INVALID,		/* DOMAIN_PARAMS_INVALID */
CKR_BUFFER_TOO_SMALL,			/* BUFFER_TOO_SMALL */
CKR_INFORMATION_SENSITIVE,		/* INFORMATION_SENSITIVE */
CKR_FUNCTION_NOT_SUPPORTED,		/* NOT_SUPPORTED */
CKR_GENERAL_ERROR,			/* QUEUED */
CKR_GENERAL_ERROR,			/* BUFFER_TOO_BIG */
CKR_OPERATION_NOT_INITIALIZED,		/* INVALID_CONTEXT */
CKR_GENERAL_ERROR,			/* INVALID_MAC */
CKR_GENERAL_ERROR,			/* MECH_NOT_SUPPORTED */
CKR_GENERAL_ERROR,			/* INCONSISTENT_ATTRIBUTE */
CKR_GENERAL_ERROR,			/* NO_PERMISSION */
CKR_SLOT_ID_INVALID,			/* INVALID_PROVIDER_ID */
CKR_GENERAL_ERROR,			/* VERSION_MISMATCH */
CKR_GENERAL_ERROR,			/* BUSY */
CKR_GENERAL_ERROR,			/* UNKNOWN_PROVIDER */
CKR_GENERAL_ERROR,			/* MODVERIFICATION_FAILED */
CKR_GENERAL_ERROR,			/* OLD_CTX_TEMPLATE */
CKR_GENERAL_ERROR,			/* WEAK_KEY */
CKR_GENERAL_ERROR			/* FIPS140_ERROR */
};

#if CRYPTO_LAST_ERROR != CRYPTO_FIPS140_ERROR
#error "Crypto to PKCS11 error mapping table needs to be updated!"
#endif

/*
 * This function returns a fullpath based on the "dir" and "filepath" input
 * arugments.
 * - If the filepath specified does not start with a "/" and the directory
 *   is also given, prepend the directory to the filename.
 * - If only dir or filepath is given, this function returns a copy of the
 *   given argument.
 * - If the filepath is fully qualified already and the "dir" is also
 *   given, return NULL to indicate an error.
 */
char *
get_fullpath(char *dir, char *filepath)
{
	char *fullpath = NULL;
	int pathlen = 0;
	int dirlen = 0;

	if (filepath != NULL)
		pathlen = strlen(filepath);

	if (dir != NULL)
		dirlen = strlen(dir);

	if (pathlen > 0 && dirlen > 0) {
		if (filepath[0] != '/') {
			int len = pathlen + dirlen + 2;
			fullpath = (char *)malloc(len);
			if (fullpath != NULL)
				(void) snprintf(fullpath, len, "%s/%s",
				    dir, filepath);
		} else {
			return (NULL);
		}
	} else if (pathlen > 0) {
		fullpath = (char *)strdup(filepath);
	} else if (dirlen > 0) {
		fullpath = (char *)strdup(dir);
	}

	return (fullpath);
}

/*
 * This function converts the input string to the value of time
 * in seconds.
 * - If the input string is NULL, return zero second.
 * - The input string needs to be in the form of:
 *   number-second(s), number-minute(s), number-hour(s) or
 *   number-day(s).
 */
int
str2lifetime(char *ltimestr, uint32_t *ltime)
{
	int num;
	char timetok[10];

	if (ltimestr == NULL || !strlen(ltimestr)) {
		*ltime = 0;
		return (0);
	}

	(void) memset(timetok, 0, sizeof (timetok));
	if (sscanf(ltimestr, "%d-%08s", &num, timetok) != 2)
		return (-1);

	if (!strcasecmp(timetok, "second") ||
	    !strcasecmp(timetok, "seconds")) {
		*ltime = num;
	} else if (!strcasecmp(timetok, "minute") ||
	    !strcasecmp(timetok, "minutes")) {
		*ltime = num * SECSPERMIN;
	} else if (!strcasecmp(timetok, "day") ||
	    !strcasecmp(timetok, "days")) {
		*ltime = num * SECSPERDAY;
	} else if (!strcasecmp(timetok, "hour") ||
	    !strcasecmp(timetok, "hours")) {
		*ltime = num * SECSPERHOUR;
	} else {
		*ltime = 0;
		return (-1);
	}

	return (0);
}

/*
 * Map KCF error codes into PKCS11 error codes.
 */
CK_RV
crypto2pkcs11_error_number(uint_t n)
{
	if (n >= sizeof (error_number_table) / sizeof (error_number_table[0]))
		return (CKR_GENERAL_ERROR);

	return (error_number_table[n]);
}