|
root / base / usr / src / lib / libelfsign
libelfsign Plain Text 2568 lines 65.7 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
#
# 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 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

include $(SRC)/lib/Makefile.lib

# Hammerhead: amd64-only
SUBDIRS = $(MACH64)

POFILE=		libelfsign.po
MSGFILES=	common/elfsignlib.c common/elfcertlib.c
XGETFLAGS=	-a

HDRS=		libelfsign.h
ROOTHDRDIR=	$(ROOT)/usr/include
HDRDIR=		common

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

.KEEP_STATE:

all clean clobber install: .WAIT $(SUBDIRS)

install_h:	$(ROOTHDRS)

check:		$(CHECKHDRS)

lint:	$(SUBDIRS)

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

$(POFILE): $(MSGFILES)
	$(BUILDPO.msgfiles)

_msg: $(MSGDOMAINPOFILE)

include $(SRC)/Makefile.msg.targ

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.
#

LIBRARY = libelfsign.a
VERS = .1

OBJECTS = \
	elfcertlib.o \
	elfsignlib.o

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

SRCDIR =	../common

LIBS =		$(DYNLIB)

LDLIBS +=	-lmd -lelf -lkmf -lcryptoutil -lc

CFLAGS +=	$(CCMT) $(CCVERBOSE)
CPPFLAGS +=	-D_REENTRANT -D_POSIX_PTHREAD_SEMANTICS

.KEEP_STATE:

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 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

Note that this library does not have a spec file.

There are no interfaces in this library that are public so an abi_
library for appcert and friends doesn't make any sense.  If the APIs
here are ever elevated to a public taxonomy then a spec file needs to
be introduced.

A 64 bit version of this library does not exist.
That isn't an issue since kcfd(8) and elfsign(1) are 32 bit
applications and are the only consumers.
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source. A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#
# Copyright 2025 Hammerhead Project
#

include ../Makefile.com
include $(SRC)/lib/Makefile.lib.64

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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <md5.h>
#include <pthread.h>

#include <cryptoutil.h>

#include <kmfapi.h>
#include <sys/crypto/elfsign.h>
#include <libelfsign.h>

#include <synch.h>

const char _PATH_ELFSIGN_CRYPTO_CERTS[] = CRYPTO_CERTS_DIR;
const char _PATH_ELFSIGN_ETC_CERTS[] = ETC_CERTS_DIR;

/*
 * The CACERT and OBJCACERT are the Cryptographic Trust Anchors
 * for the Solaris Cryptographic Framework.
 *
 * The SECACERT is the Signed Execution Trust Anchor that the
 * Cryptographic Framework uses for FIPS-140 validation of non-crypto
 * binaries
 */
static const char _PATH_CRYPTO_CACERT[] = CRYPTO_CERTS_DIR "/CA";
static const char _PATH_CRYPTO_OBJCACERT[] = CRYPTO_CERTS_DIR "/SUNWObjectCA";
static const char _PATH_CRYPTO_SECACERT[] = ETC_CERTS_DIR "/SUNWSolarisCA";
static ELFCert_t CACERT = NULL;
static ELFCert_t OBJCACERT = NULL;
static ELFCert_t SECACERT = NULL;
static pthread_mutex_t ca_mutex = PTHREAD_MUTEX_INITIALIZER;

static void elfcertlib_freecert(ELFsign_t, ELFCert_t);
static ELFCert_t elfcertlib_allocatecert(void);

/*
 * elfcertlib_verifycert - Verify the Cert with a Trust Anchor
 *
 * IN	ess		- elfsign context structure
 *	cert
 * OUT	NONE
 * RETURN	TRUE/FALSE
 *
 * We first setup the Trust Anchor (CA and SUNWObjectCA) certs
 * if it hasn't been done already.  We verify that the files on disk
 * are those we expected.
 *
 * We then verify the given cert using the publickey of a TA.
 * If the passed in cert is a TA or it has been verified already we
 * short cut and return TRUE without futher validation.
 */
/*ARGSUSED*/
boolean_t
elfcertlib_verifycert(ELFsign_t ess, ELFCert_t cert)
{
	KMF_ATTRIBUTE	attrlist[8];
	int		numattr;

	KMF_RETURN rv;
	if ((cert->c_verified == E_OK) || (cert->c_verified == E_IS_TA)) {
		return (B_TRUE);
	}

	(void) pthread_mutex_lock(&ca_mutex);
	if (CACERT == NULL) {
		(void) elfcertlib_getcert(ess, (char *)_PATH_CRYPTO_CACERT,
		    NULL, &CACERT, ES_GET);
	}

	if (OBJCACERT == NULL) {
		(void) elfcertlib_getcert(ess, (char *)_PATH_CRYPTO_OBJCACERT,
		    NULL, &OBJCACERT, ES_GET);
	}

	if (SECACERT == NULL) {
		(void) elfcertlib_getcert(ess,
		    (char *)_PATH_CRYPTO_SECACERT, NULL, &SECACERT,
		    ES_GET_FIPS140);
	}

	(void) pthread_mutex_unlock(&ca_mutex);

	if (CACERT != NULL) {
		numattr = 0;
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_CERT_DATA_ATTR, &cert->c_cert.certificate,
		    sizeof (KMF_DATA));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_SIGNER_CERT_DATA_ATTR, &CACERT->c_cert.certificate,
		    sizeof (KMF_DATA));

		rv = kmf_verify_cert(ess->es_kmfhandle, numattr, attrlist);
		if (rv == KMF_OK) {
			if (ess->es_certCAcallback != NULL)
				(ess->es_certvercallback)(ess->es_callbackctx,
				    cert, CACERT);
			cert->c_verified = E_OK;
			return (B_TRUE);
		}
	}

	if (OBJCACERT != NULL) {
		numattr = 0;
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_CERT_DATA_ATTR, &cert->c_cert.certificate,
		    sizeof (KMF_DATA));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_SIGNER_CERT_DATA_ATTR, &OBJCACERT->c_cert.certificate,
		    sizeof (KMF_DATA));

		rv = kmf_verify_cert(ess->es_kmfhandle, numattr, attrlist);
		if (rv == KMF_OK) {
			if (ess->es_certCAcallback != NULL)
				(ess->es_certvercallback)(ess->es_callbackctx,
				    cert, OBJCACERT);
			cert->c_verified = E_OK;
			return (B_TRUE);
		}
	}

	if (SECACERT != NULL) {
		numattr = 0;
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_CERT_DATA_ATTR, &cert->c_cert.certificate,
		    sizeof (KMF_DATA));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_SIGNER_CERT_DATA_ATTR, &SECACERT->c_cert.certificate,
		    sizeof (KMF_DATA));

		rv = kmf_verify_cert(ess->es_kmfhandle, numattr, attrlist);
		if (rv == KMF_OK) {
			if (ess->es_certCAcallback != NULL)
				(ess->es_certvercallback)(ess->es_callbackctx,
				    cert, SECACERT);
			cert->c_verified = E_OK;
			return (B_TRUE);
		}
	}

	return (B_FALSE);
}

/*
 * elfcertlib_getcert - Get the certificate for signer_DN
 *
 * IN	ess		- elfsign context structure
 *	cert_pathname	- path to cert (May be NULL)
 *	signer_DN	- The DN we are looking for (May be NULL)
 *      action		- indicates crypto verification call
 * OUT  certp		- allocated/loaded ELFCert_t
 *
 * If the cert_pathname is passed use it and don't search.
 * Otherwise, go looking in certificate directories
 */
boolean_t
elfcertlib_getcert(ELFsign_t ess, char *cert_pathname,
    char *signer_DN, ELFCert_t *certp, enum ES_ACTION action)
{
	KMF_RETURN rv;
	ELFCert_t	cert = NULL;
	KMF_X509_DER_CERT certbuf[2];
	uint32_t ncerts;
	boolean_t ret = B_FALSE;
	char	*pathlist[3], **plp;

	cryptodebug("elfcertlib_getcert: path=%s, DN=%s",
	    cert_pathname ? cert_pathname : "-none-",
	    signer_DN ? signer_DN : "-none-");
	*certp = NULL;
	if (cert_pathname == NULL && signer_DN == NULL) {
		cryptodebug("elfcertlib_getcert: lack of specificity");
		return (ret);
	}

	plp = pathlist;
	if (cert_pathname != NULL) {
		/* look in the specified object */
		*plp++ = cert_pathname;
	} else {
		/* look in the certificate directories */
		*plp++ = (char *)_PATH_ELFSIGN_CRYPTO_CERTS;
		/*
		 * crypto verifications don't search beyond
		 * _PATH_ELFSIGN_CRYPTO_CERTS
		 */
		if (action != ES_GET_CRYPTO)
			*plp++ = (char *)_PATH_ELFSIGN_ETC_CERTS;
	}
	*plp = NULL;

	if ((cert = elfcertlib_allocatecert()) == NULL) {
		return (ret);
	}

	for (plp = pathlist; *plp; plp++) {
		KMF_ATTRIBUTE	attrlist[8];
		KMF_KEYSTORE_TYPE	kstype;
		KMF_CERT_VALIDITY	certvalidity;
		int		numattr;

		kstype = KMF_KEYSTORE_OPENSSL;
		certvalidity = KMF_ALL_CERTS;
		ncerts = 2;

		numattr = 0;
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_KEYSTORE_TYPE_ATTR, &kstype, sizeof (kstype));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_X509_DER_CERT_ATTR, certbuf,
		    sizeof (KMF_X509_DER_CERT));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_COUNT_ATTR, &ncerts, sizeof (uint32_t));
		if (signer_DN != NULL) {
			kmf_set_attr_at_index(attrlist, numattr++,
			    KMF_SUBJECT_NAME_ATTR, signer_DN,
			    strlen(signer_DN));
		}
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_CERT_VALIDITY_ATTR, &certvalidity,
		    sizeof (KMF_CERT_VALIDITY));
		kmf_set_attr_at_index(attrlist, numattr++,
		    KMF_CERT_FILENAME_ATTR, *plp, strlen (*plp));

		rv = kmf_find_cert(ess->es_kmfhandle, numattr, attrlist);

		if (rv != KMF_OK)
			continue;
		/* found one */
		cert->c_cert = certbuf[0];
		if (ncerts > 1) {
			/* release any extras */
			kmf_free_kmf_cert(ess->es_kmfhandle, &certbuf[1]);
			if (signer_DN == NULL) {
				/* There can be only one */
				cryptodebug("elfcertlib_getcert: "
				    "too many certificates found in %s",
				    cert_pathname);
				goto cleanup;
			}
		}
		/* cache subject and issuer */
		rv = kmf_get_cert_subject_str(ess->es_kmfhandle,
		    &cert->c_cert.certificate, &cert->c_subject);
		if (rv != KMF_OK)
			goto cleanup;

		rv = kmf_get_cert_issuer_str(ess->es_kmfhandle,
		    &cert->c_cert.certificate, &cert->c_issuer);
		if (rv != KMF_OK)
			goto cleanup;
		break;
	}
	if (*plp == NULL) {
		cryptodebug("elfcertlib_getcert: no certificate found");
		goto cleanup;
	}

	cert->c_verified = E_UNCHECKED;

	/*
	 * If the cert we are loading is the trust anchor (ie the CA) then
	 * we mark it as such in cert.  This is so that we don't attempt
	 * to verify it later.  The CA is always implicitly verified.
	 */
	if (cert_pathname != NULL && (
	    strcmp(cert_pathname, _PATH_CRYPTO_CACERT) == 0 ||
	    strcmp(cert_pathname, _PATH_CRYPTO_OBJCACERT) == 0 ||
	    strcmp(cert_pathname, _PATH_CRYPTO_SECACERT) == 0)) {
		if (ess->es_certCAcallback != NULL)
			(ess->es_certCAcallback)(ess->es_callbackctx, cert,
			    cert_pathname);
		cert->c_verified = E_IS_TA;
	}

	ret = B_TRUE;

cleanup:
	if (ret) {
		*certp = cert;
	} else {
		if (cert != NULL)
			elfcertlib_freecert(ess, cert);
		if (signer_DN != NULL)
			cryptoerror(LOG_ERR, "unable to find a certificate "
			    "for DN: %s", signer_DN);
		else
			cryptoerror(LOG_ERR, "unable to load certificate "
			    "from %s", cert_pathname);
	}
	return (ret);
}

/*
 * elfcertlib_loadprivatekey - Load the private key from path
 *
 * IN	ess		- elfsign context structure
 *	cert
 *	pathname
 * OUT	cert
 * RETURNS	TRUE/FALSE
 */
boolean_t
elfcertlib_loadprivatekey(ELFsign_t ess, ELFCert_t cert, const char *pathname)
{
	KMF_RETURN	rv = KMF_OK;
	KMF_KEY_HANDLE	keybuf[2];
	KMF_ATTRIBUTE	attrlist[16];
	uint32_t	nkeys;
	KMF_KEYSTORE_TYPE	kstype;
	KMF_KEY_ALG	keytype;
	KMF_KEY_CLASS	keyclass;
	KMF_ENCODE_FORMAT	format;
	int		numattr;

	kstype = KMF_KEYSTORE_OPENSSL;
	nkeys = 2;
	keytype = KMF_KEYALG_NONE;
	keyclass = KMF_ASYM_PRI;
	format = KMF_FORMAT_UNDEF;

	numattr = 0;
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYSTORE_TYPE_ATTR,
	    &kstype, sizeof (kstype));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEY_HANDLE_ATTR,
	    keybuf, sizeof (KMF_KEY_HANDLE));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_COUNT_ATTR,
	    &nkeys, sizeof (uint32_t));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYALG_ATTR,
	    &keytype, sizeof (keytype));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYCLASS_ATTR,
	    &keyclass, sizeof (keyclass));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_ENCODE_FORMAT_ATTR,
	    &format, sizeof (format));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEY_FILENAME_ATTR,
	    (char *)pathname, strlen(pathname));

	rv = kmf_find_key(ess->es_kmfhandle, numattr, attrlist);
	if (rv != KMF_OK)
		return (B_FALSE);
	if (nkeys != 1) {
		/* lack of specificity */
		cryptodebug("found %d keys at %s", nkeys, pathname);
		return (B_FALSE);
	}
	cert->c_privatekey = keybuf[0];
	cryptodebug("key %s loaded", pathname);
	return (B_TRUE);
}

/*
 * elfcertlib_loadtokenkey - Load the private key from token
 *
 * IN	ess		- elfsign context structure
 *	cert
 *	token_label
 *	pin
 * OUT	cert
 * RETURNS	TRUE/FALSE
 */
boolean_t
elfcertlib_loadtokenkey(ELFsign_t ess, ELFCert_t cert,
    const char *token_label, const char *pin)
{
	KMF_RETURN	rv;
	char		*idstr = NULL;
	char		*kmferr;
	KMF_ATTRIBUTE	attrlist[16];
	uint32_t	nkeys;
	KMF_KEYSTORE_TYPE	kstype;
	KMF_KEY_ALG	keytype;
	KMF_KEY_CLASS	keyclass;
	KMF_ENCODE_FORMAT	format;
	KMF_CREDENTIAL	pincred;
	boolean_t	tokenbool, privatebool;
	int		numattr;

	/*
	 * We will search for the key based on the ID attribute
	 * which was added when the key was created.  ID is
	 * a SHA-1 hash of the public modulus shared by the
	 * key and the certificate.
	 */
	rv = kmf_get_cert_id_str(&cert->c_cert.certificate, &idstr);
	if (rv != KMF_OK) {
		(void) kmf_get_kmf_error_str(rv, &kmferr);
		cryptodebug("Error getting ID from cert: %s\n",
		    (kmferr ? kmferr : "Unrecognized KMF error"));
		free(kmferr);
		return (B_FALSE);
	}

	kstype = KMF_KEYSTORE_PK11TOKEN;
	nkeys = 1;
	keytype = KMF_KEYALG_NONE;
	keyclass = KMF_ASYM_PRI;
	format = KMF_FORMAT_UNDEF;
	pincred.cred = (char *)pin;
	pincred.credlen = strlen(pin);
	tokenbool = B_FALSE;
	privatebool = B_TRUE;

	numattr = 0;
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYSTORE_TYPE_ATTR,
	    &kstype, sizeof (kstype));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEY_HANDLE_ATTR,
	    &cert->c_privatekey, sizeof (KMF_KEY_HANDLE));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_COUNT_ATTR,
	    &nkeys, sizeof (uint32_t));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYALG_ATTR,
	    &keytype, sizeof (keytype));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYCLASS_ATTR,
	    &keyclass, sizeof (keyclass));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_ENCODE_FORMAT_ATTR,
	    &format, sizeof (format));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_IDSTR_ATTR,
	    idstr, strlen(idstr));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_CREDENTIAL_ATTR,
	    &pincred, sizeof (KMF_CREDENTIAL));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_TOKEN_BOOL_ATTR,
	    &tokenbool, sizeof (tokenbool));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_PRIVATE_BOOL_ATTR,
	    &privatebool, sizeof (privatebool));

	rv = kmf_find_key(ess->es_kmfhandle, numattr, attrlist);
	free(idstr);
	if (rv != KMF_OK) {
		(void) kmf_get_kmf_error_str(rv, &kmferr);
		cryptodebug("Error finding private key: %s\n",
		    (kmferr ? kmferr : "Unrecognized KMF error"));
		free(kmferr);
		return (B_FALSE);
	}
	if (nkeys != 1) {
		cryptodebug("Error finding private key: No key found\n");
		return (B_FALSE);
	}
	cryptodebug("key found in %s", token_label);
	cryptodebug("elfcertlib_loadprivatekey = 0x%.8X",
	    &cert->c_privatekey);

	return (B_TRUE);
}

static const CK_BYTE MD5_DER_PREFIX[] = {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08,
	0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10};

/*
 * elfcertlib_sign - sign the given DATA using the privatekey in cert
 *
 * IN	ess		- elfsign context structure
 *	cert
 *	data
 *	data_len
 * OUT	sig	- must be big enough to hold the signature of data
 *		  Caller must allocate
 *	sig_len	- actual length used; 0 on failure.
 * RETURNS	TRUE/FALSE
 */
/*ARGSUSED*/
boolean_t
elfcertlib_sign(ELFsign_t ess, ELFCert_t cert,
	const uchar_t *data, size_t data_len,
	uchar_t *sig, size_t *sig_len)
{
	KMF_RETURN	ret;
	KMF_DATA	tobesigned;
	KMF_DATA	signature;
	uchar_t		der_data[sizeof (MD5_DER_PREFIX) + MD5_DIGEST_LENGTH];
	KMF_ATTRIBUTE	attrlist[8];
	int		numattr;

	if (ess->es_version <= FILESIG_VERSION2) {
		/* compatibility: take MD5 hash of SHA1 hash */
		size_t	derlen = MD5_DIGEST_LENGTH;
		MD5_CTX ctx;

		/*
		 * first: digest using software-based methods, don't
		 * rely on the token for hashing.
		 */
		MD5Init(&ctx);
		MD5Update(&ctx, data, data_len);
		MD5Final(&der_data[sizeof (MD5_DER_PREFIX)], &ctx);

		/*
		 * second: insert prefix
		 */
		(void) memcpy(der_data, MD5_DER_PREFIX,
		    sizeof (MD5_DER_PREFIX));
		/*
		 * prepare to sign the local buffer
		 */
		tobesigned.Data = (uchar_t *)der_data;
		tobesigned.Length = sizeof (MD5_DER_PREFIX) + derlen;
	} else {
		tobesigned.Data = (uchar_t *)data;
		tobesigned.Length = data_len;
	}

	signature.Data = (uchar_t *)sig;
	signature.Length = *sig_len;

	numattr = 0;
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_KEYSTORE_TYPE_ATTR, &(cert->c_privatekey.kstype),
	    sizeof (KMF_KEYSTORE_TYPE));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_KEY_HANDLE_ATTR, &cert->c_privatekey, sizeof (KMF_KEY_HANDLE));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_OID_ATTR, (KMF_OID *)&KMFOID_RSA, sizeof (KMF_OID));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_DATA_ATTR, &tobesigned, sizeof (KMF_DATA));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_OUT_DATA_ATTR, &signature, sizeof (KMF_DATA));

	ret = kmf_sign_data(ess->es_kmfhandle, numattr, attrlist);

	if (ret != KMF_OK) {
		char	*kmferr;

		(void) kmf_get_kmf_error_str(ret, &kmferr);
		cryptodebug("Error signing data: %s\n",
		    (kmferr ? kmferr : "Unrecognized KMF error"));
		free(kmferr);
		*sig_len = 0;
		return (B_FALSE);
	}
	*sig_len = signature.Length;
	return (B_TRUE);
}

/*
 * elfcertlib_verifysig - verify the given DATA using the public key in cert
 *
 * IN	ess		- elfsign context structure
 *	cert
 *	signature
 *	sig_len
 *	data
 *	data_len
 * OUT	N/A
 * RETURNS	TRUE/FALSE
 */
boolean_t
elfcertlib_verifysig(ELFsign_t ess, ELFCert_t cert,
	const uchar_t *signature, size_t sig_len,
	const uchar_t *data, size_t data_len)
{
	KMF_RETURN	rv;
	KMF_DATA	indata;
	KMF_DATA	insig;
	KMF_ALGORITHM_INDEX algid;
	KMF_ATTRIBUTE	attrlist[8];
	KMF_KEYSTORE_TYPE	kstype;
	int		numattr;

	indata.Data = (uchar_t *)data;
	indata.Length = data_len;
	insig.Data = (uchar_t *)signature;
	insig.Length = sig_len;

	if (ess->es_version <= FILESIG_VERSION2)
		algid = KMF_ALGID_MD5WithRSA;
	else
		algid = KMF_ALGID_RSA;

	/*
	 * We tell KMF to use the PKCS11 verification APIs
	 * here to prevent the use of OpenSSL and to keep
	 * all validation within the FIPS-140 boundary for
	 * the Cryptographic Framework.
	 */
	kstype = KMF_KEYSTORE_PK11TOKEN;

	numattr = 0;
	kmf_set_attr_at_index(attrlist, numattr++, KMF_KEYSTORE_TYPE_ATTR,
	    &kstype,  sizeof (kstype));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_DATA_ATTR,
	    &indata, sizeof (KMF_DATA));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_IN_SIGN_ATTR,
	    &insig, sizeof (KMF_DATA));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_SIGNER_CERT_DATA_ATTR,
	    (KMF_DATA *)(&cert->c_cert.certificate), sizeof (KMF_DATA));
	kmf_set_attr_at_index(attrlist, numattr++, KMF_ALGORITHM_INDEX_ATTR,
	    &algid, sizeof (algid));

	rv = kmf_verify_data(ess->es_kmfhandle, numattr, attrlist);

	return ((rv == KMF_OK));
}

/*
 * elfcertlib_getdn
 *
 * IN	cert
 * OUT	NONE
 * RETURN 	dn or NULL
 */
char *
elfcertlib_getdn(ELFCert_t cert)
{
	cryptodebug("elfcertlib_getdn");

	return (cert->c_subject);
}

/*
 * elfcertlib_getissuer
 *
 * IN	cert
 * OUT	NONE
 * RETURN 	dn or NULL
 */
char *
elfcertlib_getissuer(ELFCert_t cert)
{
	cryptodebug("elfcertlib_issuer");

	return (cert->c_issuer);
}

boolean_t
elfcertlib_init(ELFsign_t ess)
{
	boolean_t rc = B_TRUE;
	KMF_RETURN rv;
	if (ess->es_kmfhandle == NULL) {
		rv = kmf_initialize(&ess->es_kmfhandle, NULL, NULL);
		if (rv != KMF_OK) {
			cryptoerror(LOG_ERR,
			    "unable to initialize KMF library");
			rc = B_FALSE;
		}
	}
	return (rc);
}

void
elfcertlib_fini(ELFsign_t ess)
{
	(void) kmf_finalize(ess->es_kmfhandle);
}

/*
 * set the token device
 */
boolean_t
elfcertlib_settoken(ELFsign_t ess, char *token)
{
	boolean_t	rc = B_TRUE;
	KMF_RETURN	rv;
	KMF_ATTRIBUTE	attrlist[8];
	KMF_KEYSTORE_TYPE	kstype;
	boolean_t	readonly;
	int	numattr;

	kstype = KMF_KEYSTORE_PK11TOKEN;
	readonly = B_TRUE;

	numattr = 0;
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_KEYSTORE_TYPE_ATTR, &kstype, sizeof (kstype));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_TOKEN_LABEL_ATTR, token, strlen(token));
	kmf_set_attr_at_index(attrlist, numattr++,
	    KMF_READONLY_ATTR, &readonly, sizeof (readonly));

	rv = kmf_configure_keystore(ess->es_kmfhandle, numattr, attrlist);
	if (rv != KMF_OK) {
		cryptoerror(LOG_ERR, "unable to select token\n");
		rc = B_FALSE;
	}

	return (rc);
}

/*
 * set the certificate CA identification callback
 */
void
elfcertlib_setcertCAcallback(ELFsign_t ess,
    void (*cb)(void *, ELFCert_t, char *))
{
	ess->es_certCAcallback = cb;
}

/*
 * set the certificate verification callback
 */
void
elfcertlib_setcertvercallback(ELFsign_t ess,
    void (*cb)(void *, ELFCert_t, ELFCert_t))
{
	ess->es_certvercallback = cb;
}


/*
 * elfcertlib_releasecert - release a cert
 *
 * IN cert
 * OUT cert
 * RETURN	N/A
 *
 */
void
elfcertlib_releasecert(ELFsign_t ess, ELFCert_t cert)
{
	elfcertlib_freecert(ess, cert);
}

/*
 * elfcertlib_allocatecert - create a new ELFCert_t
 *
 * IN N/A
 * OUT	N/A
 * RETURN 	ELFCert_t, NULL on failure.
 */
static ELFCert_t
elfcertlib_allocatecert(void)
{
	ELFCert_t cert = NULL;

	cert = malloc(sizeof (struct ELFCert_s));
	if (cert == NULL) {
		cryptoerror(LOG_ERR,
		    "elfcertlib_allocatecert: malloc failed %s",
		    strerror(errno));
		return (NULL);
	}
	(void) memset(cert, 0, sizeof (struct ELFCert_s));
	cert->c_verified = E_UNCHECKED;
	cert->c_subject = NULL;
	cert->c_issuer = NULL;
	return (cert);
}

/*
 * elfcertlib_freecert - freeup the memory of a cert
 *
 * IN cert
 * OUT cert
 * RETURN	N/A
 *
 */
static void
elfcertlib_freecert(ELFsign_t ess, ELFCert_t cert)
{
	if (cert == NULL)
		return;

	free(cert->c_subject);
	free(cert->c_issuer);

	kmf_free_kmf_cert(ess->es_kmfhandle, &cert->c_cert);
	kmf_free_kmf_key(ess->es_kmfhandle, &cert->c_privatekey);

	free(cert);
}
/*
 * 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) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#define	ELF_TARGET_ALL	/* get definitions of all section flags */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>
#include <stddef.h>
#include <stdlib.h>
#include <libintl.h>
#include <dirent.h>
#include <errno.h>
#include <libelf.h>
#include <gelf.h>
#include <cryptoutil.h>
#include <sha1.h>
#include <sys/crypto/elfsign.h>
#include <libelfsign.h>

#ifndef SHA1_DIGEST_LENGTH
#define	SHA1_DIGEST_LENGTH 20
#endif /* SHA1_DIGEST_LENGTH */

const char SUNW_ELF_SIGNATURE_ID[] =	ELF_SIGNATURE_SECTION;
const char OID_sha1WithRSAEncryption[] = "1.2.840.113549.1.1.5";

static ELFsign_status_t elfsign_adjustoffsets(ELFsign_t ess,
    Elf_Scn *scn, uint64_t new_size);
static uint32_t elfsign_switch_uint32(uint32_t i);
static ELFsign_status_t elfsign_switch(ELFsign_t ess,
    struct filesignatures *fssp, enum ES_ACTION action);

struct filesig_extraction {
	filesig_vers_t	fsx_version;
	char	*fsx_format;
	char	fsx_signer_DN[ELFCERT_MAX_DN_LEN];
	size_t	fsx_signer_DN_len;
	uchar_t	fsx_signature[SIG_MAX_LENGTH];
	size_t	fsx_sig_len;
	char	fsx_sig_oid[100];
	size_t	fsx_sig_oid_len;
	time_t	fsx_time;
};

static char *
version_to_str(filesig_vers_t v)
{
	char	*ret;

	switch (v) {
	case FILESIG_VERSION1:
		ret = "VERSION1";
		break;
	case FILESIG_VERSION2:
		ret = "VERSION2";
		break;
	case FILESIG_VERSION3:
		ret = "VERSION3";
		break;
	case FILESIG_VERSION4:
		ret = "VERSION4";
		break;
	default:
		ret = "UNKNOWN";
		break;
	}
	return (ret);
}

/*
 * Update filesignatures to include the v1/v2 filesig,
 *	composed of signer DN, signature, and OID.
 */
static struct filesignatures *
filesig_insert_dso(struct filesignatures *fssp,
    filesig_vers_t	version,
    const char		*dn,
    int			dn_len,
    const uchar_t	*sig,
    int			sig_len,
    const char		*oid,
    int			oid_len)
{
	struct filesig	*fsgp;
	char		*fsdatap;

	if (oid == NULL) {
		/*
		 * This OID is used for the rsa_md5_sha1 format signature also.
		 * This use is historical, and is hence continued,
		 * despite its lack of technical accuracy.
		 */
		oid = OID_sha1WithRSAEncryption;
		oid_len = strlen(oid);
	}

	/*
	 * for now, always insert a single-signature signature block
	 */
	if (fssp != NULL)
		free(fssp);
	fssp  = (struct filesignatures *)
	    malloc(filesig_ALIGN(sizeof (struct filesignatures) +
	    dn_len + sig_len + oid_len));
	if (fssp == NULL)
		return (fssp);

	fssp->filesig_cnt = 1;
	fssp->filesig_pad = 0;	/* reserve for future use */

	fsgp = &fssp->filesig_sig;
	fsgp->filesig_size = sizeof (struct filesig) +
	    dn_len + sig_len + oid_len;
	fsgp->filesig_version = version;
	switch (version) {
	case FILESIG_VERSION1:
	case FILESIG_VERSION2:
		fsgp->filesig_size -= sizeof (struct filesig) -
		    offsetof(struct filesig, filesig_v1_data[0]);
		fsgp->filesig_v1_dnsize = dn_len;
		fsgp->filesig_v1_sigsize = sig_len;
		fsgp->filesig_v1_oidsize = oid_len;
		fsdatap = &fsgp->filesig_v1_data[0];
		break;
	case FILESIG_VERSION3:
	case FILESIG_VERSION4:
		fsgp->filesig_size -= sizeof (struct filesig) -
		    offsetof(struct filesig, filesig_v3_data[0]);
		fsgp->filesig_v3_time = time(NULL);
		fsgp->filesig_v3_dnsize = dn_len;
		fsgp->filesig_v3_sigsize = sig_len;
		fsgp->filesig_v3_oidsize = oid_len;
		fsdatap = &fsgp->filesig_v3_data[0];
		break;
	default:
		cryptodebug("filesig_insert_dso: unknown version: %d",
		    version);
		free(fssp);
		return (NULL);
	}
	(void) memcpy(fsdatap, dn, dn_len);
	fsdatap += dn_len;
	(void) memcpy(fsdatap, (char *)sig, sig_len);
	fsdatap += sig_len;
	(void) memcpy(fsdatap, oid, oid_len);
	fsdatap += oid_len;
	fsgp = filesig_next(fsgp);
	(void) memset(fsdatap, 0, (char *)(fsgp) - fsdatap);

	return (fssp);
}

/*
 * filesig_extract - extract filesig structure to internal form
 */
static filesig_vers_t
filesig_extract(struct filesig *fsgp, struct filesig_extraction *fsxp)
{
	char	*fsdp;

#define	filesig_extract_common(cp, field, data_var, len_var, len_limit)  { \
	len_var = len_limit; \
	if (len_var > fsgp->field) \
		len_var = fsgp->field; \
	(void) memcpy(data_var, cp, len_var); \
	cp += fsgp->field; }
#define	filesig_extract_str(cp, field, data_var, len_var) \
	filesig_extract_common(cp, field, data_var, len_var, \
	    sizeof (data_var) - 1); \
	data_var[len_var] = '\0';
#define	filesig_extract_opaque(cp, field, data_var, len_var) \
	filesig_extract_common(cp, field, data_var, len_var, sizeof (data_var))

	fsxp->fsx_version = fsgp->filesig_version;
	cryptodebug("filesig_extract: version=%s",
	    version_to_str(fsxp->fsx_version));
	switch (fsxp->fsx_version) {
	case FILESIG_VERSION1:
	case FILESIG_VERSION2:
		/*
		 * extract VERSION1 DN, signature, and OID
		 */
		fsdp = fsgp->filesig_v1_data;
		fsxp->fsx_format = ES_FMT_RSA_MD5_SHA1;
		fsxp->fsx_time = 0;
		filesig_extract_str(fsdp, filesig_v1_dnsize,
		    fsxp->fsx_signer_DN, fsxp->fsx_signer_DN_len);
		filesig_extract_opaque(fsdp, filesig_v1_sigsize,
		    fsxp->fsx_signature, fsxp->fsx_sig_len);
		filesig_extract_str(fsdp, filesig_v1_oidsize,
		    fsxp->fsx_sig_oid, fsxp->fsx_sig_oid_len);
		break;
	case FILESIG_VERSION3:
	case FILESIG_VERSION4:
		fsdp = fsgp->filesig_v3_data;
		fsxp->fsx_format = ES_FMT_RSA_SHA1;
		fsxp->fsx_time = fsgp->filesig_v3_time;
		filesig_extract_str(fsdp, filesig_v3_dnsize,
		    fsxp->fsx_signer_DN, fsxp->fsx_signer_DN_len);
		filesig_extract_opaque(fsdp, filesig_v3_sigsize,
		    fsxp->fsx_signature, fsxp->fsx_sig_len);
		filesig_extract_str(fsdp, filesig_v3_oidsize,
		    fsxp->fsx_sig_oid, fsxp->fsx_sig_oid_len);
		break;
	default:
		break;
	}

	return (fsxp->fsx_version);
}

ELFsign_status_t
elfsign_begin(const char *filename, enum ES_ACTION action, ELFsign_t *essp)
{
	Elf_Cmd		elfcmd;
	int		oflags = 0;
	short		l_type;
	ELFsign_t	ess;
	struct stat	stb;
	union {
		char	c[2];
		short	s;
	}	uorder;
	GElf_Ehdr	elfehdr;
	char		*ident;

	switch (action) {
	case ES_GET:
	case ES_GET_CRYPTO:
	case ES_GET_FIPS140:
		cryptodebug("elfsign_begin for get");
		elfcmd = ELF_C_READ;
		oflags = O_RDONLY | O_NOCTTY | O_NDELAY;
		l_type = F_RDLCK;
		break;
	case ES_UPDATE_RSA_MD5_SHA1:
	case ES_UPDATE_RSA_SHA1:
		cryptodebug("elfsign_begin for update");
		elfcmd = ELF_C_RDWR;
		oflags = O_RDWR | O_NOCTTY | O_NDELAY;
		l_type = F_WRLCK;
		break;
	default:
		return (ELFSIGN_UNKNOWN);
	}

	if ((ess = malloc(sizeof (struct ELFsign_s))) == NULL) {
		return (ELFSIGN_UNKNOWN);
	}
	(void) memset((void *)ess, 0, sizeof (struct ELFsign_s));

	if (!elfcertlib_init(ess)) {
		cryptodebug("elfsign_begin: failed initialization");
		return (ELFSIGN_UNKNOWN);
	}

	ess->es_elf = NULL;
	ess->es_action = action;
	ess->es_version = FILESIG_UNKNOWN;
	ess->es_pathname = NULL;
	ess->es_certpath = NULL;

	if (filename == NULL) {
		*essp = ess;
		return (ELFSIGN_SUCCESS);
	}

	if ((ess->es_fd = open(filename, oflags)) == -1) {
		elfsign_end(ess);
		return (ELFSIGN_INVALID_ELFOBJ);
	}
	if ((fstat(ess->es_fd, &stb) == -1) || !S_ISREG(stb.st_mode)) {
		elfsign_end(ess);
		return (ELFSIGN_INVALID_ELFOBJ);
	}
	if ((ess->es_pathname = strdup(filename)) == NULL) {
		elfsign_end(ess);
		return (ELFSIGN_UNKNOWN);
	}
	/*
	 * The following lock is released in elfsign_end() when we close(2)
	 * the es_fd. This ensures that we aren't trying verify a file
	 * we are currently updating.
	 */
	ess->es_flock.l_type = l_type;
	ess->es_flock.l_whence = SEEK_CUR;
	ess->es_flock.l_start = 0;
	ess->es_flock.l_len = 0;
	if (fcntl(ess->es_fd, F_SETLK, &ess->es_flock) == -1) {
		cryptodebug("fcntl(F_SETLK) of %s failed with: %s",
		    ess->es_pathname, strerror(errno));
		elfsign_end(ess);
		return (ELFSIGN_UNKNOWN);
	}

	if (elf_version(EV_CURRENT) == EV_NONE) {
		elfsign_end(ess);
		return (ELFSIGN_UNKNOWN);
	}

	if ((ess->es_elf = elf_begin(ess->es_fd, elfcmd,
	    (Elf *)NULL)) == NULL) {
		cryptodebug("elf_begin() failed: %s", elf_errmsg(-1));
		elfsign_end(ess);
		return (ELFSIGN_INVALID_ELFOBJ);
	}

	if (gelf_getehdr(ess->es_elf, &elfehdr) == NULL) {
		cryptodebug("elf_getehdr() failed: %s", elf_errmsg(-1));
		elfsign_end(ess);
		return (ELFSIGN_INVALID_ELFOBJ);
	}
	ess->es_has_phdr = (elfehdr.e_phnum != 0);

	uorder.s = ELFDATA2MSB << 8 | ELFDATA2LSB;
	ident = elf_getident(ess->es_elf, NULL);
	if (ident == NULL) {
		cryptodebug("elf_getident() failed: %s", elf_errmsg(-1));
		elfsign_end(ess);
		return (ELFSIGN_INVALID_ELFOBJ);
	}
	ess->es_same_endian = (ident[EI_DATA] == uorder.c[0]);
	ess->es_ei_class = ident[EI_CLASS];

	/*
	 * Call elf_getshstrndx to be sure we have a real ELF object
	 * this is required because elf_begin doesn't check that.
	 */
	if (elf_getshstrndx(ess->es_elf, &ess->es_shstrndx) == 0) {
		elfsign_end(ess);
		cryptodebug("elfsign_begin: elf_getshstrndx failed");
		return (ELFSIGN_INVALID_ELFOBJ);
	}

	/*
	 * Make sure libelf doesn't rearrange section ordering / offsets.
	 */
	(void) elf_flagelf(ess->es_elf, ELF_C_SET, ELF_F_LAYOUT);

	*essp = ess;

	return (ELFSIGN_SUCCESS);
}

/*
 * elfsign_end - cleanup the ELFsign_t
 *
 * IN/OUT:	ess
 */
void
elfsign_end(ELFsign_t ess)
{
	if (ess == NULL)
		return;

	if (ess->es_elf != NULL && ES_ACTISUPDATE(ess->es_action)) {
		if (elf_update(ess->es_elf, ELF_C_WRITE) == -1) {
			cryptodebug("elf_update() failed: %s",
			    elf_errmsg(-1));
			return;
		}
	}

	if (ess->es_fd != -1) {
		(void) close(ess->es_fd);
		ess->es_fd = -1;
	}

	if (ess->es_pathname != NULL) {
		free(ess->es_pathname);
		ess->es_pathname = NULL;
	}
	if (ess->es_certpath != NULL) {
		free(ess->es_certpath);
		ess->es_certpath = NULL;
	}

	if (ess->es_elf != NULL) {
		(void) elf_end(ess->es_elf);
		ess->es_elf = NULL;
	}

	elfcertlib_fini(ess);

	free(ess);
}

/*
 * set the certificate path
 */
ELFsign_status_t
elfsign_setcertpath(ELFsign_t ess, const char *certpath)
{
	/*
	 * Normally use of access(2) is insecure, here we are only
	 * doing it to help provide early failure and better error
	 * checking, so there is no race condition.
	 */
	if (access(certpath, R_OK) != 0)
		return (ELFSIGN_INVALID_CERTPATH);

	if ((ess->es_certpath = strdup(certpath)) == NULL)
		return (ELFSIGN_FAILED);

	if (ES_ACTISUPDATE(ess->es_action)) {
		ELFCert_t	cert = NULL;
		char		*subject;

		/* set the version based on the certificate */
		if (elfcertlib_getcert(ess, ess->es_certpath, NULL,
		    &cert, ess->es_action)) {
			if ((subject = elfcertlib_getdn(cert)) != NULL) {
				if (strstr(subject, ELFSIGN_CRYPTO))
					ess->es_version = (ess->es_action ==
					    ES_UPDATE_RSA_MD5_SHA1) ?
					    FILESIG_VERSION1 : FILESIG_VERSION3;
				else
					ess->es_version = (ess->es_action ==
					    ES_UPDATE_RSA_MD5_SHA1) ?
					    FILESIG_VERSION2 : FILESIG_VERSION4;
			}
			elfcertlib_releasecert(ess, cert);
		}
		if (ess->es_version == FILESIG_UNKNOWN)
			return (ELFSIGN_FAILED);
	}
	return (ELFSIGN_SUCCESS);
}

/*
 * set the callback context
 */
void
elfsign_setcallbackctx(ELFsign_t ess, void *ctx)
{
	ess->es_callbackctx = ctx;
}

/*
 * set the signature extraction callback
 */
void
elfsign_setsigvercallback(ELFsign_t ess,
    void (*cb)(void *, void *, size_t, ELFCert_t))
{
	ess->es_sigvercallback = cb;
}

/*
 * elfsign_signatures
 *
 * IN: 	ess, fsspp, action
 * OUT:	fsspp
 */
ELFsign_status_t
elfsign_signatures(ELFsign_t ess,
    struct filesignatures **fsspp,
    size_t *fslen,
    enum ES_ACTION action)
{
	Elf_Scn		*scn = NULL, *sig_scn = NULL;
	GElf_Shdr	shdr;
	Elf_Data	*data = NULL;
	const char	*elf_section = SUNW_ELF_SIGNATURE_ID;
	int		fscnt, fssize;
	struct filesig	*fsgp, *fsgpnext;
	uint64_t	sig_offset = 0;

	cryptodebug("elfsign_signature");
	if ((ess == NULL) || (fsspp == NULL)) {
		cryptodebug("invalid arguments");
		return (ELFSIGN_UNKNOWN);
	}

	cryptodebug("elfsign_signature %s for %s",
	    ES_ACTISUPDATE(action) ? "ES_UPDATE" : "ES_GET", elf_section);

	(void) elf_errno();
	while ((scn = elf_nextscn(ess->es_elf, scn)) != NULL) {
		const char	*sh_name;
		/*
		 * Do a string compare to examine each section header
		 * to see if this is the section that needs to be updated.
		 */
		if (gelf_getshdr(scn, &shdr) == NULL) {
			cryptodebug("gelf_getshdr() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		sh_name = elf_strptr(ess->es_elf, ess->es_shstrndx,
		    (size_t)shdr.sh_name);
		if (strcmp(sh_name, elf_section) == 0) {
			cryptodebug("elfsign_signature: found %s", elf_section);
			sig_scn = scn;
			break;
		}
		if (shdr.sh_type != SHT_NOBITS &&
		    sig_offset < shdr.sh_offset + shdr.sh_size) {
			sig_offset = shdr.sh_offset + shdr.sh_size;
		}
	}
	if (elf_errmsg(0) != NULL) {
		cryptodebug("unexpected error: %s", elf_section,
		    elf_errmsg(-1));
		return (ELFSIGN_FAILED);
	}

	if (ES_ACTISUPDATE(action) && (sig_scn == NULL))  {
		size_t	old_size, new_size;
		char	*new_d_buf;

		cryptodebug("elfsign_signature: %s not found - creating",
		    elf_section);

		/*
		 * insert section name in .shstrtab
		 */
		if ((scn = elf_getscn(ess->es_elf, ess->es_shstrndx)) == 0) {
			cryptodebug("elf_getscn() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		if (gelf_getshdr(scn, &shdr) == NULL) {
			cryptodebug("gelf_getshdr() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		if ((data = elf_getdata(scn, data)) == NULL) {
			cryptodebug("elf_getdata() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		old_size = data->d_size;
		if (old_size != shdr.sh_size) {
			cryptodebug("mismatch between data size %d "
			    "and section size %lld", old_size, shdr.sh_size);
			return (ELFSIGN_FAILED);
		}
		new_size = old_size + strlen(elf_section) + 1;
		if ((new_d_buf = malloc(new_size)) == NULL)
			return (ELFSIGN_FAILED);

		(void) memcpy(new_d_buf, data->d_buf, old_size);
		(void) strlcpy(new_d_buf + old_size, elf_section,
		    new_size - old_size);
		data->d_buf = new_d_buf;
		data->d_size = new_size;
		data->d_align = 1;
		/*
		 * Add the section name passed in to the end of the file.
		 * Initialize the fields in the Section Header that
		 * libelf will not fill in.
		 */
		if ((sig_scn = elf_newscn(ess->es_elf)) == 0) {
			cryptodebug("elf_newscn() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		if (gelf_getshdr(sig_scn, &shdr) == 0) {
			cryptodebug("gelf_getshdr() failed: %s",
			    elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		shdr.sh_name = old_size;
		shdr.sh_type = SHT_SUNW_SIGNATURE;
		shdr.sh_flags = SHF_EXCLUDE;
		shdr.sh_addr = 0;
		shdr.sh_link = 0;
		shdr.sh_info = 0;
		shdr.sh_size = 0;
		shdr.sh_offset = sig_offset;
		shdr.sh_addralign = 1;

		/*
		 * Flush the changes to the underlying elf32 or elf64
		 * section header.
		 */
		if (gelf_update_shdr(sig_scn, &shdr) == 0) {
			cryptodebug("gelf_update_shdr failed");
			return (ELFSIGN_FAILED);
		}

		if ((data = elf_newdata(sig_scn)) == NULL) {
			cryptodebug("can't add elf data area for %s: %s",
			    elf_section, elf_errmsg(-1));
			return (ELFSIGN_FAILED);
		}
		if (elfsign_adjustoffsets(ess, scn,
		    old_size + strlen(elf_section) + 1) != ELFSIGN_SUCCESS) {
			cryptodebug("can't adjust for new section name %s",
			    elf_section);
			return (ELFSIGN_FAILED);
		}
	} else {
		if (sig_scn == NULL) {
			cryptodebug("can't find signature section");
			*fsspp = NULL;
			return (ELFSIGN_NOTSIGNED);
		}
		if ((data = elf_getdata(sig_scn, NULL)) == 0) {
			cryptodebug("can't get section data for %s",
			    elf_section);
			return (ELFSIGN_FAILED);
		}
	}

	if (ES_ACTISUPDATE(action))  {
		fssize = offsetof(struct filesignatures, _u1);
		if (*fsspp != NULL) {
			fsgp = &(*fsspp)->filesig_sig;
			for (fscnt = 0; fscnt < (*fsspp)->filesig_cnt;
			    fscnt++) {
				fsgpnext = filesig_next(fsgp);
				fssize += (char *)(fsgpnext) - (char *)(fsgp);
				fsgp = fsgpnext;
			}
		}
		if (shdr.sh_addr != 0) {
			cryptodebug("section %s is part of a loadable segment, "
			    "it cannot be changed.\n", elf_section);
			return (ELFSIGN_FAILED);
		}
		if ((data->d_buf = malloc(fssize)) == NULL)
			return (ELFSIGN_FAILED);
		if (*fsspp != NULL) {
			(void) memcpy(data->d_buf, *fsspp, fssize);
			(void) elfsign_switch(ess,
			    (struct filesignatures *)data->d_buf, action);
		}
		data->d_size = fssize;
		data->d_align = 1;
		data->d_type = ELF_T_BYTE;
		cryptodebug("elfsign_signature: data->d_size = %d",
		    data->d_size);
		if (elfsign_adjustoffsets(ess, sig_scn, fssize) !=
		    ELFSIGN_SUCCESS) {
			cryptodebug("can't adjust for revised signature "
			    "section contents");
			return (ELFSIGN_FAILED);
		}
	} else {
		*fsspp = malloc(data->d_size);
		if (*fsspp == NULL)
			return (ELFSIGN_FAILED);
		(void) memcpy(*fsspp, data->d_buf, data->d_size);
		if (elfsign_switch(ess, *fsspp, ES_GET) != ELFSIGN_SUCCESS) {
			free(*fsspp);
			*fsspp = NULL;
			return (ELFSIGN_FAILED);
		}
		*fslen = data->d_size;
	}

	return (ELFSIGN_SUCCESS);
}

static ELFsign_status_t
elfsign_adjustoffsets(ELFsign_t ess, Elf_Scn *scn, uint64_t new_size)
{
	GElf_Ehdr	elfehdr;
	GElf_Shdr	shdr;
	uint64_t	prev_end, scn_offset;
	char		*name;
	Elf_Scn		*scnp;
	Elf_Data	*data;
	ELFsign_status_t	retval = ELFSIGN_FAILED;
	struct scninfo {
		struct scninfo	*scni_next;
		Elf_Scn		*scni_scn;
		uint64_t	scni_offset;
	}		*scnip = NULL, *tmpscnip, **scnipp;

	/* get the size of the current section */
	if (gelf_getshdr(scn, &shdr) == NULL)
		return (ELFSIGN_FAILED);
	if (shdr.sh_size == new_size)
		return (ELFSIGN_SUCCESS);
	scn_offset = shdr.sh_offset;
	name = elf_strptr(ess->es_elf, ess->es_shstrndx,
	    (size_t)shdr.sh_name);
	if (shdr.sh_flags & SHF_ALLOC && ess->es_has_phdr) {
		cryptodebug("elfsign_adjustoffsets: "
		    "can't move allocated section %s", name ? name : "NULL");
		return (ELFSIGN_FAILED);
	}

	/* resize the desired section */
	cryptodebug("elfsign_adjustoffsets: "
	    "resizing %s at 0x%llx from 0x%llx to 0x%llx",
	    name ? name : "NULL", shdr.sh_offset, shdr.sh_size, new_size);
	shdr.sh_size = new_size;
	if (gelf_update_shdr(scn, &shdr) == 0) {
		cryptodebug("gelf_update_shdr failed");
		goto bad;
	}
	prev_end = shdr.sh_offset + shdr.sh_size;

	/*
	 * find sections whose data follows the changed section
	 *	must scan all sections since section data may not
	 *	be in same order as section headers
	 */
	scnp = elf_getscn(ess->es_elf, 0);	/* "seek" to start */
	while ((scnp = elf_nextscn(ess->es_elf, scnp)) != NULL) {
		if (gelf_getshdr(scnp, &shdr) == NULL)
			goto bad;
		if (shdr.sh_offset <= scn_offset)
			continue;
		name = elf_strptr(ess->es_elf, ess->es_shstrndx,
		    (size_t)shdr.sh_name);
		if (shdr.sh_flags & SHF_ALLOC && ess->es_has_phdr) {
			if (shdr.sh_type == SHT_NOBITS) {
				/* .bss can occasionally overlap .shrtab */
				continue;
			}
			cryptodebug("elfsign_adjustoffsets: "
			    "can't move allocated section %s",
			    name ? name : "NULL");
			goto bad;
		}
		/*
		 * force reading of data to memory image
		 */
		data = NULL;
		while ((data = elf_rawdata(scnp, data)) != NULL)
			;
		/*
		 * capture section information
		 * insert into list in order of sh_offset
		 */
		cryptodebug("elfsign_adjustoffsets: "
		    "may have to adjust section %s, offset 0x%llx",
		    name ? name : "NULL", shdr.sh_offset);
		tmpscnip = (struct scninfo *)malloc(sizeof (struct scninfo));
		if (tmpscnip == NULL) {
			cryptodebug("elfsign_adjustoffsets: "
			    "memory allocation failure");
			goto bad;
		}
		tmpscnip->scni_scn = scnp;
		tmpscnip->scni_offset = shdr.sh_offset;
		for (scnipp = &scnip; *scnipp != NULL;
		    scnipp = &(*scnipp)->scni_next) {
			if ((*scnipp)->scni_offset > tmpscnip->scni_offset)
				break;
		}
		tmpscnip->scni_next = *scnipp;
		*scnipp = tmpscnip;
	}

	/* move following sections as necessary */
	for (tmpscnip = scnip; tmpscnip != NULL;
	    tmpscnip = tmpscnip->scni_next) {
		scnp = tmpscnip->scni_scn;
		if (gelf_getshdr(scnp, &shdr) == NULL) {
			cryptodebug("elfsign_adjustoffsets: "
			    "elf_getshdr for section %d failed",
			    elf_ndxscn(scnp));
			goto bad;
		}
		if (shdr.sh_offset >= prev_end)
			break;
		prev_end = (prev_end + shdr.sh_addralign - 1) &
		    (-shdr.sh_addralign);
		name = elf_strptr(ess->es_elf, ess->es_shstrndx,
		    (size_t)shdr.sh_name);
		cryptodebug("elfsign_adjustoffsets: "
		    "moving %s size 0x%llx from 0x%llx to 0x%llx",
		    name ? name : "NULL", shdr.sh_size,
		    shdr.sh_offset, prev_end);
		shdr.sh_offset = prev_end;
		if (gelf_update_shdr(scnp, &shdr) == 0) {
			cryptodebug("gelf_update_shdr failed");
			goto bad;
		}
		prev_end = shdr.sh_offset + shdr.sh_size;
	}

	/*
	 * adjust section header offset in elf header
	 */
	if (gelf_getehdr(ess->es_elf, &elfehdr) == NULL) {
		cryptodebug("elf_getehdr() failed: %s", elf_errmsg(-1));
		goto bad;
	}
	if (elfehdr.e_shoff < prev_end) {
		if (ess->es_ei_class == ELFCLASS32)
			prev_end = (prev_end + ELF32_FSZ_OFF - 1) &
			    (-ELF32_FSZ_OFF);
		else if (ess->es_ei_class == ELFCLASS64)
			prev_end = (prev_end + ELF64_FSZ_OFF - 1) &
			    (-ELF64_FSZ_OFF);
		cryptodebug("elfsign_adjustoffsets: "
		    "move sh_off from 0x%llx to 0x%llx",
		    elfehdr.e_shoff, prev_end);
		elfehdr.e_shoff = prev_end;
		if (gelf_update_ehdr(ess->es_elf, &elfehdr) == 0) {
			cryptodebug("elf_update_ehdr() failed: %s",
			    elf_errmsg(-1));
			goto bad;
		}
	}

	retval = ELFSIGN_SUCCESS;

bad:
	while (scnip != NULL) {
		tmpscnip = scnip->scni_next;
		free(scnip);
		scnip = tmpscnip;
	}
	return (retval);
}

struct filesignatures *
elfsign_insert_dso(ELFsign_t ess,
    struct filesignatures *fssp,
    const char		*dn,
    int			dn_len,
    const uchar_t	*sig,
    int			sig_len,
    const char		*oid,
    int			oid_len)
{
	return (filesig_insert_dso(fssp, ess->es_version, dn, dn_len,
	    sig, sig_len, oid, oid_len));
}

/*ARGSUSED*/
filesig_vers_t
elfsign_extract_sig(ELFsign_t ess,
    struct filesignatures *fssp,
    uchar_t		*sig,
    size_t		*sig_len)
{
	struct filesig_extraction	fsx;
	filesig_vers_t	version;

	if (fssp == NULL)
		return (FILESIG_UNKNOWN);
	if (fssp->filesig_cnt != 1)
		return (FILESIG_UNKNOWN);
	version = filesig_extract(&fssp->filesig_sig, &fsx);
	switch (version) {
	case FILESIG_VERSION1:
	case FILESIG_VERSION2:
	case FILESIG_VERSION3:
	case FILESIG_VERSION4:
		if (*sig_len >= fsx.fsx_sig_len) {
			(void) memcpy((char *)sig, (char *)fsx.fsx_signature,
			    *sig_len);
			*sig_len = fsx.fsx_sig_len;
		} else
			version = FILESIG_UNKNOWN;
		break;
	default:
		version = FILESIG_UNKNOWN;
		break;
	}

	if (ess->es_version == FILESIG_UNKNOWN) {
		ess->es_version = version;
	}

	return (version);
}

static ELFsign_status_t
elfsign_hash_common(ELFsign_t ess, uchar_t *hash, size_t *hash_len,
    boolean_t hash_mem_resident)
{
	Elf_Scn		*scn = NULL;
	ELFsign_status_t elfstat;
	GElf_Shdr	shdr;
	SHA1_CTX	ctx;

	/* The buffer must be large enough to hold the hash */
	if (*hash_len < SHA1_DIGEST_LENGTH)
		return (ELFSIGN_FAILED);

	bzero(hash, *hash_len);

	/* Initialize the digest session */
	SHA1Init(&ctx);

	scn = elf_getscn(ess->es_elf, 0);	/* "seek" to start */
	(void) elf_errno();
	while ((scn = elf_nextscn(ess->es_elf, scn)) != 0) {
		char *name = NULL;
		Elf_Data *data = NULL;

		if (gelf_getshdr(scn, &shdr) == NULL) {
			elfstat = ELFSIGN_FAILED;
			goto done;
		}

		name = elf_strptr(ess->es_elf, ess->es_shstrndx,
		    (size_t)shdr.sh_name);
		if (name == NULL)
			name = "NULL";

		if (!hash_mem_resident &&
		    (ess->es_version == FILESIG_VERSION1 ||
		    ess->es_version == FILESIG_VERSION3)) {
			/*
			 * skip the signature section only
			 */
			if (shdr.sh_type == SHT_SUNW_SIGNATURE) {
				cryptodebug("elfsign_hash: skipping %s", name);
				continue;
			}
		} else if (!(shdr.sh_flags & SHF_ALLOC)) {
			/*
			 * select only memory resident sections
			 */
			cryptodebug("elfsign_hash: skipping %s", name);
			continue;
		}

		/*
		 * throw this section into the hash
		 *   use elf_rawdata for endian-independence
		 *   use elf_getdata to get update of .shstrtab
		 */
		while ((data = (shdr.sh_type == SHT_STRTAB ?
		    elf_getdata(scn, data) : elf_rawdata(scn, data))) != NULL) {
			if (data->d_buf == NULL) {
				cryptodebug("elfsign_hash: %s has NULL data",
				    name);
				continue;
			}
			cryptodebug("elfsign_hash: updating hash "
			    "with %s data size=%d", name, data->d_size);
			SHA1Update(&ctx, data->d_buf, data->d_size);
		}
	}
	if (elf_errmsg(0) != NULL) {
		cryptodebug("elfsign_hash: %s", elf_errmsg(-1));
		elfstat = ELFSIGN_FAILED;
		goto done;
	}

	SHA1Final(hash, &ctx);
	*hash_len = SHA1_DIGEST_LENGTH;
	{ /* DEBUG START */
		const int hashstr_len = (*hash_len) * 2 + 1;
		char *hashstr = malloc(hashstr_len);

		if (hashstr != NULL) {
			tohexstr(hash, *hash_len, hashstr, hashstr_len);
			cryptodebug("hash value is: %s", hashstr);
			free(hashstr);
		}
	} /* DEBUG END */
	elfstat = ELFSIGN_SUCCESS;
done:
	return (elfstat);
}

/*
 * elfsign_hash - return the hash of the ELF sections affecting execution.
 *
 * IN:		ess, hash_len
 * OUT:		hash, hash_len
 */
ELFsign_status_t
elfsign_hash(ELFsign_t ess, uchar_t *hash, size_t *hash_len)
{
	return (elfsign_hash_common(ess, hash, hash_len, B_FALSE));
}

/*
 * elfsign_hash_mem_resident - return the hash of the ELF sections
 * with only memory resident sections.
 *
 * IN:		ess, hash_len
 * OUT:		hash, hash_len
 */
ELFsign_status_t
elfsign_hash_mem_resident(ELFsign_t ess, uchar_t *hash, size_t *hash_len)
{
	return (elfsign_hash_common(ess, hash, hash_len, B_TRUE));
}


/*
 * elfsign_verify_signature - Verify the signature of the ELF object.
 *
 * IN:		ess
 * OUT:		esipp
 * RETURNS:
 *	ELFsign_status_t
 */
ELFsign_status_t
elfsign_verify_signature(ELFsign_t ess, struct ELFsign_sig_info **esipp)
{
	ELFsign_status_t	ret = ELFSIGN_FAILED;
	struct	filesignatures *fssp;
	struct	filesig *fsgp;
	size_t	fslen;
	struct filesig_extraction	fsx;
	uchar_t	hash[SIG_MAX_LENGTH];
	size_t	hash_len;
	ELFCert_t	cert = NULL;
	int	sigcnt;
	int	nocert = 0;
	struct ELFsign_sig_info	*esip = NULL;

	if (esipp != NULL) {
		esip = (struct ELFsign_sig_info *)
		    calloc(1, sizeof (struct ELFsign_sig_info));
		*esipp = esip;
	}

	/*
	 * Find out which cert we need, based on who signed the ELF object
	 */
	if (elfsign_signatures(ess, &fssp, &fslen, ES_GET) != ELFSIGN_SUCCESS) {
		return (ELFSIGN_NOTSIGNED);
	}

	if (fssp->filesig_cnt < 1) {
		ret = ELFSIGN_FAILED;
		goto cleanup;
	}

	fsgp = &fssp->filesig_sig;

	/*
	 * Scan the signature block, looking for a verifiable signature
	 */
	for (sigcnt = 0; sigcnt < fssp->filesig_cnt;
	    sigcnt++, fsgp = filesig_next(fsgp)) {
		ess->es_version = filesig_extract(fsgp, &fsx);
		cryptodebug("elfsign_verify_signature: version=%s",
		    version_to_str(ess->es_version));
		switch (ess->es_version) {
		case FILESIG_VERSION1:
		case FILESIG_VERSION2:
		case FILESIG_VERSION3:
		case FILESIG_VERSION4:
			break;
		default:
			ret = ELFSIGN_FAILED;
			goto cleanup;
		}

		cryptodebug("elfsign_verify_signature: signer_DN=\"%s\"",
		    fsx.fsx_signer_DN);
		cryptodebug("elfsign_verify_signature: algorithmOID=\"%s\"",
		    fsx.fsx_sig_oid);
		/* return signer DN if requested */
		if (esipp != NULL) {
			esip->esi_format = fsx.fsx_format;
			if (esip->esi_signer != NULL)
				free(esip->esi_signer);
			esip->esi_signer = strdup(fsx.fsx_signer_DN);
			esip->esi_time = fsx.fsx_time;
		}

		/*
		 * look for certificate
		 */
		if (cert != NULL)
			elfcertlib_releasecert(ess, cert);

		/*
		 * skip unfound certificates
		 */
		if (!elfcertlib_getcert(ess, ess->es_certpath,
		    fsx.fsx_signer_DN, &cert, ess->es_action)) {
			cryptodebug("unable to find certificate "
			    "with DN=\"%s\" for %s",
			    fsx.fsx_signer_DN, ess->es_pathname);
			nocert++;
			continue;
		}

		/*
		 * skip unverified certificates
		 *	force verification of crypto certs
		 */
		if ((ess->es_action == ES_GET_CRYPTO ||
		    ess->es_action == ES_GET_FIPS140 ||
		    strstr(fsx.fsx_signer_DN, ELFSIGN_CRYPTO)) &&
		    !elfcertlib_verifycert(ess, cert)) {
			cryptodebug("elfsign_verify_signature: invalid cert");
			nocert++;
			continue;
		}

		/*
		 * At this time the only sha1WithRSAEncryption is supported,
		 * so check that is what we have and skip with anything else.
		 */
		if (strcmp(fsx.fsx_sig_oid, OID_sha1WithRSAEncryption) != 0) {
			continue;
		}

		nocert = 0;
		/*
		 * compute file hash
		 */
		hash_len = sizeof (hash);
		if (elfsign_hash(ess, hash, &hash_len) != ELFSIGN_SUCCESS) {
			cryptodebug("elfsign_verify_signature:"
			    " elfsign_hash failed");
			ret = ELFSIGN_FAILED;
			break;
		}

		{ /* DEBUG START */
			const int sigstr_len = fsx.fsx_sig_len * 2 + 1;
			char *sigstr = malloc(sigstr_len);

			if (sigstr != NULL) {
				tohexstr(fsx.fsx_signature, fsx.fsx_sig_len,
				    sigstr, sigstr_len);
				cryptodebug("signature value is: %s", sigstr);
				free(sigstr);
			}
		} /* DEBUG END */

		if (elfcertlib_verifysig(ess, cert,
		    fsx.fsx_signature, fsx.fsx_sig_len, hash, hash_len)) {
			if (ess->es_sigvercallback)
				(ess->es_sigvercallback)
				    (ess->es_callbackctx, fssp, fslen, cert);
			/*
			 * The signature is verified!
			 */
			ret = ELFSIGN_SUCCESS;
		}

		cryptodebug("elfsign_verify_signature: invalid signature");
	}

cleanup:
	if (cert != NULL)
		elfcertlib_releasecert(ess, cert);

	free(fssp);
	if (ret == ELFSIGN_FAILED && nocert)
		ret = ELFSIGN_INVALID_CERTPATH;
	return (ret);
}


static uint32_t
elfsign_switch_uint32(uint32_t i)
{
	return (((i & 0xff) << 24) | ((i & 0xff00) << 8) |
	    ((i >> 8) & 0xff00) | ((i >> 24) & 0xff));
}

static uint64_t
elfsign_switch_uint64(uint64_t i)
{
	return (((uint64_t)elfsign_switch_uint32(i) << 32) |
	    (elfsign_switch_uint32(i >> 32)));
}

/*
 * If appropriate, switch the endianness of the filesignatures structure
 *	Examine the structure only when it is in native endianness
 */
static ELFsign_status_t
elfsign_switch(ELFsign_t ess, struct filesignatures *fssp,
    enum ES_ACTION action)
{
	int		fscnt;
	filesig_vers_t	version;
	struct filesig	*fsgp, *fsgpnext;

	if (ess->es_same_endian)
		return (ELFSIGN_SUCCESS);

	if (ES_ACTISUPDATE(action))
		fscnt = fssp->filesig_cnt;
	fssp->filesig_cnt = elfsign_switch_uint32(fssp->filesig_cnt);
	if (!ES_ACTISUPDATE(action))
		fscnt = fssp->filesig_cnt;

	fsgp = &(fssp)->filesig_sig;
	for (; fscnt > 0; fscnt--, fsgp = fsgpnext) {
		if (ES_ACTISUPDATE(action)) {
			version = fsgp->filesig_version;
			fsgpnext = filesig_next(fsgp);
		}
		fsgp->filesig_size =
		    elfsign_switch_uint32(fsgp->filesig_size);
		fsgp->filesig_version =
		    elfsign_switch_uint32(fsgp->filesig_version);
		if (!ES_ACTISUPDATE(action)) {
			version = fsgp->filesig_version;
			fsgpnext = filesig_next(fsgp);
		}
		switch (version) {
		case FILESIG_VERSION1:
		case FILESIG_VERSION2:
			fsgp->filesig_v1_dnsize =
			    elfsign_switch_uint32(fsgp->filesig_v1_dnsize);
			fsgp->filesig_v1_sigsize =
			    elfsign_switch_uint32(fsgp->filesig_v1_sigsize);
			fsgp->filesig_v1_oidsize =
			    elfsign_switch_uint32(fsgp->filesig_v1_oidsize);
			break;
		case FILESIG_VERSION3:
		case FILESIG_VERSION4:
			fsgp->filesig_v3_time =
			    elfsign_switch_uint64(fsgp->filesig_v3_time);
			fsgp->filesig_v3_dnsize =
			    elfsign_switch_uint32(fsgp->filesig_v3_dnsize);
			fsgp->filesig_v3_sigsize =
			    elfsign_switch_uint32(fsgp->filesig_v3_sigsize);
			fsgp->filesig_v3_oidsize =
			    elfsign_switch_uint32(fsgp->filesig_v3_oidsize);
			break;
		default:
			cryptodebug("elfsign_switch: failed");
			return (ELFSIGN_FAILED);
		}
	}
	return (ELFSIGN_SUCCESS);
}

/*
 * get/put an integer value from/to a buffer, possibly of opposite endianness
 */
void
elfsign_buffer_len(ELFsign_t ess, size_t *ip, uchar_t *cp,
    enum ES_ACTION action)
{
	uint32_t tmp;

	if (!ES_ACTISUPDATE(action)) {
		/* fetch integer from buffer */
		(void) memcpy(&tmp, cp, sizeof (tmp));
		if (!ess->es_same_endian) {
			tmp = elfsign_switch_uint32(tmp);
		}
		*ip = tmp;
	} else {
		/* put integer into buffer */
		tmp = *ip;
		if (!ess->es_same_endian) {
			tmp = elfsign_switch_uint32(tmp);
		}
		(void) memcpy(cp, &tmp, sizeof (tmp));
	}
}

char const *
elfsign_strerror(ELFsign_status_t elferror)
{
	char const *msg = NULL;

	switch (elferror) {
		case ELFSIGN_SUCCESS:
			msg = gettext("sign or verify of ELF object succeeded");
			break;
		case ELFSIGN_FAILED:
			msg = gettext("sign or verify of ELF object failed");
			break;
		case ELFSIGN_NOTSIGNED:
			msg = gettext("ELF object not signed");
			break;
		case ELFSIGN_INVALID_CERTPATH:
			msg = gettext("cannot access certificate");
			break;
		case ELFSIGN_INVALID_ELFOBJ:
			msg = gettext("unable to open as an ELF object");
			break;
		case ELFSIGN_UNKNOWN:
		default:
			msg = gettext("Unknown error");
			break;
	}

	return (msg);
}

boolean_t
elfsign_sig_info(struct filesignatures *fssp, struct ELFsign_sig_info **esipp)
{
	struct filesig_extraction	fsx;
	struct ELFsign_sig_info	*esip;

	esip = (struct ELFsign_sig_info *)
	    calloc(1, sizeof (struct ELFsign_sig_info));
	*esipp = esip;
	if (esip == NULL)
		return (B_FALSE);

	switch (filesig_extract(&fssp->filesig_sig, &fsx)) {
	case FILESIG_VERSION1:
	case FILESIG_VERSION2:
	case FILESIG_VERSION3:
	case FILESIG_VERSION4:
		esip->esi_format = fsx.fsx_format;
		esip->esi_signer = strdup(fsx.fsx_signer_DN);
		esip->esi_time = fsx.fsx_time;
		break;
	default:
		free(esip);
		*esipp = NULL;
	}

	return (*esipp != NULL);
}

void
elfsign_sig_info_free(struct ELFsign_sig_info *esip)
{
	if (esip != NULL) {
		free(esip->esi_signer);
		free(esip);
	}
}
/*
 * 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) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef _LIBELFSIGN_H
#define	_LIBELFSIGN_H

#ifdef __cplusplus
extern "C" {
#endif

/*
 * libelfsign Private Interfaces
 * This header file should not be shipped as part of Solaris binary or
 * source products.
 */

#include <sys/crypto/elfsign.h>
#include <libelf.h>
#include <fcntl.h>
#include <md5.h>
#include <sha1.h>
#include <kmfapi.h>

/*
 * Certificate-related definitions
 */
#define	ELFSIGN_CRYPTO		"Solaris Cryptographic Framework"
#define	USAGELIMITED		"OU=UsageLimited"

typedef enum ELFCert_VStatus_e {
	E_UNCHECKED,
	E_OK,
	E_IS_TA,
	E_FAILED
} ELFCert_VStatus_t;

typedef struct ELFCert_s {
	ELFCert_VStatus_t	c_verified;
	char			*c_subject;
	char			*c_issuer;
	KMF_X509_DER_CERT	c_cert;
	KMF_KEY_HANDLE		c_privatekey;
}	*ELFCert_t;

#define	CRYPTO_CERTS_DIR	"/etc/crypto/certs"
#define	ETC_CERTS_DIR		"/etc/certs"

/*
 * libelfsign actions
 */
enum ES_ACTION {
	ES_GET,
	ES_GET_CRYPTO,
	ES_GET_FIPS140,
	ES_UPDATE,
	ES_UPDATE_RSA_MD5_SHA1,
	ES_UPDATE_RSA_SHA1
};
#define	ES_ACTISUPDATE(a)	((a) >= ES_UPDATE)

/*
 * Context for elfsign operation
 */
struct ELFsign_s {
	Elf	*es_elf;
	char	*es_pathname;
	char	*es_certpath;
	int	es_fd;
	size_t	es_shstrndx;
	enum ES_ACTION	es_action;
	KMF_KEY_HANDLE		es_privatekey;
	filesig_vers_t	es_version;
	boolean_t	es_same_endian;
	boolean_t	es_has_phdr;
	char		es_ei_class;
	struct flock	es_flock;
	KMF_HANDLE_T	es_kmfhandle;
	void		*es_callbackctx;
	void		(*es_sigvercallback)(void *, void *, size_t, ELFCert_t);
	void		(*es_certCAcallback)(void *, ELFCert_t, char *);
	void		(*es_certvercallback)(void *, ELFCert_t, ELFCert_t);
};

#define	ES_FMT_RSA_MD5_SHA1	"rsa_md5_sha1"
#define	ES_FMT_RSA_SHA1		"rsa_sha1"

/*
 * ELF signature handling
 */
typedef struct ELFsign_s *ELFsign_t;
struct ELFsign_sig_info {
	char	*esi_format;
	char	*esi_signer;
	time_t	esi_time;
};

extern struct filesignatures *elfsign_insert_dso(ELFsign_t ess,
    struct filesignatures *fsp, const char *dn, int dn_len,
    const uchar_t *sig, int sig_len, const char *oid, int oid_len);
extern filesig_vers_t elfsign_extract_sig(ELFsign_t ess,
    struct filesignatures *fsp, uchar_t *sig, size_t *sig_len);
extern ELFsign_status_t elfsign_begin(const char *,
    enum ES_ACTION, ELFsign_t *);
extern void elfsign_end(ELFsign_t ess);
extern ELFsign_status_t elfsign_setcertpath(ELFsign_t ess, const char *path);
extern ELFsign_status_t elfsign_verify_signature(ELFsign_t ess,
    struct ELFsign_sig_info **esipp);
extern ELFsign_status_t elfsign_hash(ELFsign_t ess, uchar_t *hash,
    size_t *hash_len);
extern ELFsign_status_t elfsign_hash_mem_resident(ELFsign_t ess,
    uchar_t *hash, size_t *hash_len);
extern void elfsign_buffer_len(ELFsign_t ess, size_t *ip, uchar_t *cp,
    enum ES_ACTION action);

extern void elfsign_setcallbackctx(ELFsign_t ess, void *ctx);
extern void elfsign_setsigvercallback(ELFsign_t ess,
    void (*cb)(void *, void *, size_t, ELFCert_t));
extern ELFsign_status_t elfsign_signatures(ELFsign_t ess,
    struct filesignatures **fspp, size_t *fs_len, enum ES_ACTION action);

extern char const *elfsign_strerror(ELFsign_status_t);
extern boolean_t elfsign_sig_info(struct filesignatures *fssp,
    struct ELFsign_sig_info **esipp);
extern void elfsign_sig_info_free(struct ELFsign_sig_info *);

/*
 * ELF "Certificate Library"
 */

extern const char _PATH_ELFSIGN_CERTS[];

#define	ELFCERT_MAX_DN_LEN	255

extern boolean_t elfcertlib_init(ELFsign_t);
extern void elfcertlib_fini(ELFsign_t);
extern boolean_t elfcertlib_settoken(ELFsign_t, char *);
extern void elfcertlib_setcertCAcallback(ELFsign_t ess,
    void (*cb)(void *, ELFCert_t, char *));
extern void elfcertlib_setcertvercallback(ELFsign_t ess,
    void (*cb)(void *, ELFCert_t, ELFCert_t));

extern boolean_t elfcertlib_getcert(ELFsign_t ess, char *cert_pathname,
	char *signer_DN, ELFCert_t *certp, enum ES_ACTION action);
extern void elfcertlib_releasecert(ELFsign_t, ELFCert_t);
extern char *elfcertlib_getdn(ELFCert_t cert);
extern char *elfcertlib_getissuer(ELFCert_t cert);

extern boolean_t elfcertlib_loadprivatekey(ELFsign_t ess, ELFCert_t cert,
	const char *path);
extern boolean_t elfcertlib_loadtokenkey(ELFsign_t ess, ELFCert_t cert,
	const char *token_id, const char *pin);

extern boolean_t elfcertlib_sign(ELFsign_t ess, ELFCert_t cert,
	const uchar_t *data, size_t data_len, uchar_t *sig,
	size_t *sig_len);

extern boolean_t elfcertlib_verifycert(ELFsign_t ess, ELFCert_t cert);
extern boolean_t elfcertlib_verifysig(ELFsign_t ess, ELFCert_t cert,
	const uchar_t *sig, size_t sig_len,
	const uchar_t *data, size_t data_len);

#ifdef __cplusplus
}
#endif

#endif /* _LIBELFSIGN_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 (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# 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 SUNW_1.1 {
    global:
	elfsign_begin;
	elfsign_buffer_len;
	elfsign_end;
	elfsign_extract_sig;
	elfsign_hash;
	elfsign_hash_mem_resident;
	elfsign_insert_dso;
	elfsign_setcallbackctx;
	elfsign_setsigvercallback;
	elfsign_setcertpath;
	elfsign_sig_info;
	elfsign_sig_info_free;
	elfsign_signatures;
	elfsign_strerror;
	elfsign_verify_signature;
	elfcertlib_getcert;
	elfcertlib_getdn;
	elfcertlib_getissuer;
	elfcertlib_init;
	elfcertlib_loadprivatekey;
	elfcertlib_loadtokenkey;
	elfcertlib_releasecert;
	elfcertlib_setcertCAcallback;
	elfcertlib_setcertvercallback;
	elfcertlib_settoken;
	elfcertlib_sign;
	elfcertlib_verifycert;
	elfcertlib_verifysig;
    local:
	*;
};