1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465
|
/*
* zkey - Generate, re-encipher, and validate secure keys
*
* Keystore handling functions
*
* Copyright IBM Corp. 2018, 2020
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <argz.h>
#include <dirent.h>
#include <err.h>
#include <errno.h>
#include <fnmatch.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "lib/util_base.h"
#include "lib/util_libc.h"
#include "lib/util_panic.h"
#include "lib/util_path.h"
#include "lib/util_rec.h"
#include "keystore.h"
#include "pkey.h"
#include "cca.h"
#include "properties.h"
#include "utils.h"
struct key_filenames {
char *skey_filename;
char *info_filename;
char *renc_filename;
};
#define FILE_EXTENSION_LEN 5
#define SKEY_FILE_EXTENSION ".skey"
#define INFO_FILE_EXTENSION ".info"
#define RENC_FILE_EXTENSION ".renc"
#define LOCK_FILE_NAME ".lock"
#define VOLUME_TYPE_PLAIN "plain"
#define VOLUME_TYPE_LUKS2 "luks2"
#ifdef HAVE_LUKS2_SUPPORT
#define DEFAULT_VOLUME_TYPE VOLUME_TYPE_LUKS2
#else
#define DEFAULT_VOLUME_TYPE VOLUME_TYPE_PLAIN
#endif
#define REC_KEY "Key"
#define REC_DESCRIPTION "Description"
#define REC_SEC_KEY_SIZE "Secure key size"
#define REC_CLR_KEY_SIZE "Clear key size"
#define REC_XTS "XTS type key"
#define REC_KEY_TYPE "Key type"
#define REC_VOLUMES "Volumes"
#define REC_APQNS "APQNs"
#define REC_KEY_FILE "Key file name"
#define REC_SECTOR_SIZE "Sector size"
#define REC_STATUS "Status"
#define REC_MASTERKEY "Enciphered with"
#define REC_CREATION_TIME "Created"
#define REC_CHANGE_TIME "Changed"
#define REC_REENC_TIME "Re-enciphered"
#define REC_KEY_VP "Verification pattern"
#define REC_VOLUME_TYPE "Volume type"
#define REC_KMS "KMS"
#define REC_KMS_KEY_LABEL "KMS key label"
#define pr_verbose(keystore, fmt...) do { \
if (keystore->verbose) \
warnx(fmt); \
} while (0)
static int _keystore_kms_key_unbind(struct keystore *keystore,
struct properties *properties);
/**
* Gets the file names of the .skey and .info and .renc files for a named
* key in the key strore's directory
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[out] names is filled with the names of the files
*
* @returns 0 for success or a negative errno in case of an error*
*/
static int _keystore_get_key_filenames(struct keystore *keystore,
const char *name,
struct key_filenames *names)
{
if (strpbrk(name, "/\\ *?'\"")) {
warnx("Key name '%s' contains invalid characters", name);
return -EINVAL;
}
util_asprintf(&names->skey_filename, "%s/%s%s", keystore->directory,
name, SKEY_FILE_EXTENSION);
util_asprintf(&names->info_filename, "%s/%s%s", keystore->directory,
name, INFO_FILE_EXTENSION);
util_asprintf(&names->renc_filename, "%s/%s%s", keystore->directory,
name, RENC_FILE_EXTENSION);
pr_verbose(keystore, "File names for key '%s': '%s' and '%s'", name,
names->skey_filename, names->info_filename);
return 0;
}
/**
* Checks if the .renc file exists.
*
* @param[in] file_names names of the files
*
* @returns 1 if the file exist, 0 if the file do not exist
*/
static int _keystore_reencipher_key_exists(struct key_filenames *file_names)
{
return util_path_is_reg_file("%s", file_names->renc_filename);
}
/**
* Checks if both, the .skey and the .info (and .renc) files exist.
*
* @param[in] file_names names of the files
*
* @returns 1 if all files exist, 0 if all files do not exist, -1 if one
* file exists but other one does not exist (inconsistent state)
*/
static int _keystore_exists_keyfiles(struct key_filenames *file_names)
{
bool rc_skey, rc_info;
rc_skey = util_path_is_reg_file("%s", file_names->skey_filename);
rc_info = util_path_is_reg_file("%s", file_names->info_filename);
if (rc_skey && rc_info)
return 1;
if (!rc_skey && !rc_info &&
_keystore_reencipher_key_exists(file_names) == 0)
return 0;
return -1;
}
/**
* Checks if the files belonging to a key exist. If not an appropriate error
* message is issued.
*
* @param[in] file_names names of the files
* @param[in] name name of the key
*
* @returns 0 if the files exist, -ENOENT if the files do not exist, -EPERM if
* one file exists but the other does not exist (inconsistent state)
*/
static int _keystore_ensure_keyfiles_exist(struct key_filenames *file_names,
const char *name)
{
int rc;
rc = _keystore_exists_keyfiles(file_names);
if (rc == 0) {
warnx("Key '%s' does not exist", name);
return -ENOENT;
}
if (rc == -1) {
warnx("Key '%s' is in an inconsistent state", name);
return -EPERM;
}
return 0;
}
/**
* Checks if the files belonging to a key do not exist. If they files exist,
* an appropriate error message is issued.
*
* @param[in] file_names names of the files
* @param[in] name name of the key
*
* @returns 0 if the files exist, -EEXIST if the files exist already, -EPERM if
* one file exists but the other does not exist (inconsistent state)
*/
static int _keystore_ensure_keyfiles_not_exist(struct key_filenames *file_names,
const char *name)
{
int rc;
rc = _keystore_exists_keyfiles(file_names);
if (rc == 1) {
warnx("Key '%s' exists already", name);
return -EEXIST;
}
if (rc == -1) {
warnx("Key '%s' is in an inconsistent state", name);
return -EPERM;
}
return 0;
}
/**
* Frees the file names stored inside the struct key_filenames
*
* @param[in] names names of the files
*/
static void _keystore_free_key_filenames(struct key_filenames *names)
{
if (names->skey_filename)
free(names->skey_filename);
if (names->info_filename)
free(names->info_filename);
if (names->renc_filename)
free(names->renc_filename);
}
/**
* Sets the file permissions of the file to the permissions and the group
* of the repository directory
*
* @param[in] keystroe the keystore
* @param[in] filename the name of the file to set permissions for
*
* @returns 0 on success, or a negative errno value on failure
*/
static int _keystore_set_file_permission(struct keystore *keystore,
const char *filename)
{
int rc;
if (chmod(filename, keystore->mode) != 0) {
rc = -errno;
warnx("chmod failed on file '%s': %s", filename, strerror(-rc));
return rc;
}
if (chown(filename, geteuid(), keystore->owner) != 0) {
rc = -errno;
warnx("chown failed on file '%s': %s", filename, strerror(-rc));
return rc;
}
return 0;
}
/**
* Checks if the sector size is power of two and in range 512 - 4096 bytes.
*
* @param[in] sector_size the sector size
*
* @returns 1 if the sector size is valid, 0 otherwise
*/
static int _keystore_valid_sector_size(size_t sector_size)
{
if (sector_size == 0)
return 1;
if (sector_size < 512 || sector_size > 4096)
return 0;
if (sector_size & (sector_size - 1))
return 0;
return 1;
}
/**
* Checks if the volume type is supported.
*
* @param[in] volume_type the volume type
*
* @returns 1 if the volume type is valid, 0 otherwise
*/
static int _keystore_valid_volume_type(const char *volume_type)
{
if (strcasecmp(volume_type, VOLUME_TYPE_PLAIN) == 0)
return 1;
#ifdef HAVE_LUKS2_SUPPORT
if (strcasecmp(volume_type, VOLUME_TYPE_LUKS2) == 0)
return 1;
#endif
return 0;
}
/**
* Returns the volume type contained in the properties. If no volume type
* property is contained, then 'plain' is assumed (for backward comatibility).
*
* @returns a string containing the volume type. Must be freed by the caller.
*/
static char *_keystore_get_volume_type(struct properties *properties)
{
char *type;
type = properties_get(properties, PROP_NAME_VOLUME_TYPE);
if (type == NULL)
type = util_strdup(VOLUME_TYPE_PLAIN);
return type;
}
/**
* Returns the key type contained in the properties. If no key type
* property is contained, then 'CCA-AESDATA' is assumed (for backward
* compatibility).
*
* @returns a string containing the key type. Must be freed by the caller.
*/
static char *_keystore_get_key_type(struct properties *properties)
{
char *type;
type = properties_get(properties, PROP_NAME_KEY_TYPE);
if (type == NULL)
type = util_strdup(KEY_TYPE_CCA_AESDATA);
return type;
}
/**
* Checks if the key type is supported.
*
* @param[in] key_type the key type
*
* @returns 1 if the key type is valid, 0 otherwise
*/
static int _keystore_valid_key_type(const char *key_type)
{
if (strcasecmp(key_type, KEY_TYPE_CCA_AESDATA) == 0)
return 1;
if (strcasecmp(key_type, KEY_TYPE_CCA_AESCIPHER) == 0)
return 1;
if (strcasecmp(key_type, KEY_TYPE_EP11_AES) == 0)
return 1;
return 0;
}
/**
* Checks if the keys is KMS-bound
*
* @param[in] key_props the key properties
* @param[out] kms_name the name of the KMS plugin, if KMS-bound
*
* @return true if the key is KMS bound, false otherwise
*/
static bool _keystore_is_kms_bound_key(struct properties *key_props,
char **kms_name)
{
bool ret = false;
char *kms;
if (kms_name != NULL)
*kms_name = NULL;
kms = properties_get(key_props, PROP_NAME_KMS);
if (kms != NULL && strcasecmp(kms, "LOCAL") != 0)
ret = true;
if (kms_name != NULL && ret == true)
*kms_name = kms;
else if (kms != NULL)
free(kms);
return ret;
}
/**
* Prints a message followed by a list of associated volumes, if volumes are
* associated and the volume-type matches (if specified)
*
* @param[in] msg the message to display
* @param[in] properties the properties
* @param[in] volume_type the volume type to display the message for (or NULL)
*
* @returns always zero
*/
static int _keystore_msg_for_volumes(const char *msg,
struct properties *properties,
const char *volume_type)
{
char *volumes = NULL;
char **volume_list;
char *type = NULL;
int i;
if (volume_type != NULL) {
type = _keystore_get_volume_type(properties);
if (strcasecmp(type, volume_type) != 0)
goto out;
}
volumes = properties_get(properties, PROP_NAME_VOLUMES);
if (volumes != NULL && strlen(volumes) > 0) {
volume_list = str_list_split(volumes);
util_print_indented(msg, 0);
for (i = 0; volume_list[i] != NULL; i++)
printf(" %s\n", volume_list[i]);
str_list_free_string_array(volume_list);
}
out:
if (volumes != NULL)
free(volumes);
if (type != NULL)
free(type);
return 0;
}
typedef int (*check_association_t)(const char *value, bool remove, bool set,
char **normalized, void *private);
/**
* Set an association property. For each object set function check_func is
* called (if not NULL).
*
* @param[in/out] key_props the properties object to modify
* @param[in] property the name of the property to modify
* @param[in] newvalue the new value(s) to add, remove or set
* @param[in] msg_obj the name of the object for error messages
* @param[in] check_func a function to call on each object before it is
* added, removed or set to the property
* @param[in] check_private a private pointer passed to check_func
*
* @returns 0 for success, or a negative errno value in case of an error, or
* whatever check_func returns if check_func returns a non-zero value.
*/
static int _keystore_set_association(struct properties *key_props,
const char *property,
const char *newvalue,
const char *msg_obj,
check_association_t check_func,
void *check_private)
{
char *normalized = NULL;
char **newvals = NULL;
char *value = NULL;
char *changedval;
char *newval;
int i, rc = 0;
newvals = str_list_split(newvalue);
if (newvals == NULL)
return -EINVAL;
for (i = 0; newvals[i] != NULL; i++) {
if (check_func != NULL) {
rc = check_func(newvals[i], 0, 1, &normalized,
check_private);
if (rc != 0)
goto out;
}
newval = normalized != NULL ? normalized : newvals[i];
if (value == NULL)
changedval = str_list_add("", newval);
else
changedval = str_list_add(value, newval);
if (changedval == NULL) {
warnx("The %s '%s' is already specified or contains "
"invalid characters", msg_obj, newval);
rc = -EEXIST;
goto out;
}
if (normalized != NULL)
free(normalized);
normalized = NULL;
free(value);
value = changedval;
}
rc = properties_set(key_props, property, value != NULL ? value : "");
if (rc != 0)
warnx("Invalid characters in %ss", msg_obj);
out:
if (newvals != NULL)
str_list_free_string_array(newvals);
if (value != NULL)
free(value);
if (normalized != NULL)
free(normalized);
return rc;
}
/**
* Add a value to an association property. For each object added function
* check_func is called (if not NULL).
*
* @param[in/out] key_props the properties object to modify
* @param[in] property the name of the property to modify
* @param[in] newvalue the new value(s) to add, remove or set
* @param[in] msg_obj the name of the object for error messages
* @param[in] check_func a function to call on each object before it is
* added, removed or set to the property
* @param[in] check_private a private pointer passed to check_func
*
* @returns 0 for success, or a negative errno value in case of an error, or
* whatever check_func returns if check_func returns a non-zero value.
*/
static int _keystore_add_association(struct properties *key_props,
const char *property,
const char *newvalue,
const char *msg_obj,
check_association_t check_func,
void *check_private)
{
char *normalized = NULL;
char **newvals = NULL;
char *changedval;
char *newval;
int i, rc = 0;
char *value;
value = properties_get(key_props, property);
if (value == NULL)
return _keystore_set_association(key_props, property,
newvalue, msg_obj,
check_func, check_private);
newvals = str_list_split(newvalue);
if (newvals == NULL) {
rc = -EINVAL;
goto out;
}
for (i = 0; newvals[i] != NULL; i++) {
if (check_func != NULL) {
rc = check_func(newvals[i], 0, 0, &normalized,
check_private);
if (rc != 0)
goto out;
}
newval = normalized != NULL ? normalized : newvals[i];
changedval = str_list_add(value, newval);
if (changedval == NULL) {
warnx("The %s '%s' is already associated with this key "
"or contains invalid characters", msg_obj,
newval);
rc = -EEXIST;
goto out;
}
if (normalized != NULL)
free(normalized);
normalized = NULL;
free(value);
value = changedval;
}
rc = properties_set(key_props, property, value);
if (rc != 0)
warnx("Invalid characters in %ss", msg_obj);
out:
if (newvals != NULL)
str_list_free_string_array(newvals);
if (value != NULL)
free(value);
if (normalized != NULL)
free(normalized);
return rc;
}
/**
* Removes a value from an association property. For each object removed
* function check_func is called (if not NULL).
*
* @param[in/out] key_props the properties object to modify
* @param[in] property the name of the property to modify
* @param[in] delvalue the value(s) to remove
* @param[in] msg_obj the name of the object for error messages
* @param[in] check_func a function to call on each object before it is
* added, removed or set to the property
* @param[in] check_private a private pointer passed to check_func
*
* @returns 0 for success, or a negative errno value in case of an error, or
* whatever check_func returns if check_func returns a non-zero value.
*/
static int _keystore_remove_association(struct properties *key_props,
const char *property,
const char *delvalue,
const char *msg_obj,
check_association_t check_func,
void *check_private)
{
char *normalized = NULL;
char **delvals = NULL;
char *changedval;
char *delval;
int i, rc = 0;
char *value;
value = properties_get(key_props, property);
if (value == NULL) {
warnx("No %ss are currently associated with this key", msg_obj);
return -ENOENT;
}
delvals = str_list_split(delvalue);
if (delvals == NULL) {
rc = -EINVAL;
goto out;
}
for (i = 0; delvals[i] != NULL; i++) {
if (check_func != NULL) {
rc = check_func(delvals[i], 1, 0, &normalized,
check_private);
if (rc != 0)
goto out;
}
delval = normalized != NULL ? normalized : delvals[i];
changedval = str_list_remove(value, delval);
if (changedval == NULL) {
warnx("%s '%s' is not associated with this key",
msg_obj, delval);
rc = -ENOENT;
goto out;
}
if (normalized != NULL)
free(normalized);
normalized = NULL;
free(value);
value = changedval;
}
rc = properties_set(key_props, property, value);
if (rc != 0)
warnx("Invalid characters in %ss", msg_obj);
out:
if (delvals != NULL)
str_list_free_string_array(delvals);
if (value != NULL)
free(value);
if (normalized != NULL)
free(normalized);
return rc;
}
/**
* Change an association property. This function adds the objects in the
* comma separated string when newvalue begins with a '+'. It removes the
* objects when newvalue begins with a '-', or it sets the property to
* newvalue when newvalue does not begin with '+' or '-'. For each object
* added, Removed or set function check_func is called (if not NULL).
*
* @param[in/out] key_props the properties object to modify
* @param[in] property the name of the property to modify
* @param[in] newvalue the new value(s) to add, remove or set
* @param[in] msg_obj the name of the object for error messages
* @param[in] check_func a function to call on each object before it is
* added, removed or set to the property
* @param[in] check_private a private pointer passed to check_func
*
* @returns 0 for success, or a negative errno value in case of an error, or
* whatever check_func returns if check_func returns a non-zero value.
*/
static int _keystore_change_association(struct properties *key_props,
const char *property,
const char *newvalue,
const char *msg_obj,
check_association_t check_func,
void *check_private)
{
switch (*newvalue) {
case '+':
return _keystore_add_association(key_props, property,
&newvalue[1], msg_obj,
check_func, check_private);
case '-':
return _keystore_remove_association(key_props, property,
&newvalue[1], msg_obj,
check_func, check_private);
default:
return _keystore_set_association(key_props, property,
newvalue, msg_obj,
check_func, check_private);
}
}
/**
* Filter match function for APQNs
*
* @param[in] pattern the pattern to match
* @param[in] apqn the apqn to match
* @param[in] flags Not used here
*
* @returns Zero if string matches pattern, FNM_NOMATCH if there is no match
* or another nonzero value if there is an error.
*/
static int _keystore_apqn_match(const char *pattern, const char *apqn,
int UNUSED(flags))
{
unsigned int card, domain;
char *pattern_domain;
char *pattern_card;
char *modified;
char *copy;
size_t i;
char *ch;
int rc;
if (sscanf(pattern, "%x.%x", &card, &domain) == 2) {
util_asprintf(&modified, "%02x.%04x", card, domain);
goto match;
}
copy = util_strdup(pattern);
ch = strchr(copy, '.');
if (ch != NULL) {
*ch = '\0';
pattern_card = copy;
pattern_domain = ch + 1;
modified = NULL;
if (strchr(pattern_card, '*') == NULL &&
strlen(pattern_card) < 2) {
for (i = 0; i < 2 - strlen(pattern_card); i++)
modified = util_strcat_realloc(modified, "0");
}
modified = util_strcat_realloc(modified, pattern_card);
modified = util_strcat_realloc(modified, ".");
if (strchr(pattern_domain, '*') == NULL &&
strlen(pattern_domain) < 4) {
for (i = 0; i < 4 - strlen(pattern_domain); i++)
modified = util_strcat_realloc(modified, "0");
}
modified = util_strcat_realloc(modified, pattern_domain);
} else {
modified = util_strdup(copy);
}
free(copy);
match:
rc = fnmatch(modified, apqn, FNM_CASEFOLD);
free(modified);
return rc;
}
typedef int (*filter_match_t)(const char *pattern, const char *string,
int flags);
/*
* Checks if the value matches the filter list. The value can be a comma
* separated string.
*
* If the filter values contain a second part separated by a colon (':'), then
* the filter matches only if both parts match. If the filter values do not
* contain a second part,then only the first part is checked, and the second
* parts of the values are ignored.
*
* @param[in] value the value to check
* @param[in] filter_list a list of filter strings to match the value with
* @param[in] match_func the filter match function. If NULL fnmatch() is used.
*
* @returns 1 for a match, 0 for not matched
*/
static int _keystore_match_filter(const char *value,
char **filter_list,
filter_match_t match_func)
{
char **value_list;
int i, k, rc = 0;
char *ch;
if (filter_list == NULL)
return 1;
if (match_func == NULL)
match_func = fnmatch;
value_list = str_list_split(value);
for (i = 0; filter_list[i] != NULL && rc == 0; i++) {
for (k = 0; value_list[k] != NULL; k++) {
/*
* Ignore part after ':' of value if filter does
* not also contain a ':' part.
*/
if (strchr(filter_list[i], ':') == NULL) {
ch = strchr(value_list[k], ':');
if (ch != NULL)
*ch = '\0';
}
if (match_func(filter_list[i], value_list[k], 0) == 0) {
rc = 1;
break;
}
}
}
str_list_free_string_array(value_list);
return rc;
}
/*
* Checks if the property value matches the filter list. The property value
* can be a comma separated string.
*
* If the filter values contain a second part separated by a colon (':'), then
* the filter matches only if both parts match. If the filter values do not
* contain a second part,then only the first part is checked, and the second
* parts of the values are ignored.
*
* @param[in] properties a properties object
* @param[in] property the name of the property to check
* @param[in] filter_list a list of filter strings to match the value with
* @param[in] match_func the filter match function. If NULL fnmatch() is used.
*
* @returns 1 for a match, 0 for not matched
*/
static int _keystore_match_filter_property(struct properties *properties,
const char *property,
char **filter_list,
filter_match_t match_func)
{
char *value;
int rc;
if (filter_list == NULL)
return 1;
value = properties_get(properties, property);
if (value == NULL)
return 0;
rc = _keystore_match_filter(value, filter_list, match_func);
free(value);
return rc;
}
/**
* Checks if the volume type property matches the specified volume type.
* If the properties do not contain a volume type property, then the default
* volume type is assumed.
*
* @param[in] properties a properties object
* @param[in] volume_type the volume type to match. Can be NULL. In this case
* it always matches.
*
* @returns 1 for a match, 0 for not matched
*/
static int _keystore_match_volume_type_property(struct properties *properties,
const char *volume_type)
{
char *type;
int rc = 0;
if (volume_type == NULL)
return 1;
type = _keystore_get_volume_type(properties);
if (strcasecmp(type, volume_type) == 0)
rc = 1;
free(type);
return rc;
}
/**
* Checks if the key type property matches the specified key type.
* If the properties do not contain a key type property, then the default
* key type is assumed.
*
* @param[in] properties a properties object
* @param[in] key_type the key type to match. Can be NULL. In this case
* it always matches.
*
* @returns 1 for a match, 0 for not matched
*/
static int _keystore_match_key_type_property(struct properties *properties,
const char *key_type)
{
char *type;
int rc = 0;
if (key_type == NULL)
return 1;
type = _keystore_get_key_type(properties);
if (strcasecmp(type, key_type) == 0)
rc = 1;
free(type);
return rc;
}
/**
* Checks if a key name matches a name filter
*
* @param[in] name the name to check
* @param[in] name_filter the name filter to match against
*
* @returns 1 if the filter matches, 0 otherwise
*/
static int _keystore_match_name_filter(const char *name,
const char *name_filter)
{
if (name_filter == NULL)
return 1;
if (fnmatch(name_filter, name, 0) != 0)
return 0;
return 1;
}
/**
* Filters directory entries for scanfile(). Only entries that are regular
* files and who's name ends with '.info' are matched.
*/
static int _keystore_info_file_filter(const struct dirent *dirent)
{
size_t len;
if (dirent->d_type != DT_REG && dirent->d_type != DT_UNKNOWN)
return 0;
len = strlen(dirent->d_name);
if (len > FILE_EXTENSION_LEN &&
strcmp(&dirent->d_name[len - FILE_EXTENSION_LEN],
INFO_FILE_EXTENSION) == 0)
return 1;
return 0;
}
typedef int (*process_key_t)(struct keystore *keystore,
const char *name, struct properties *properties,
struct key_filenames *file_names, void *private);
/**
* Iterates over all keys stored in the keystore. For every key that matches
* the specified filter process_func is called.
*
* @param[in] keystore the key store
* @param[in] name_filter the name filter. Can contain wild cards.
* NULL means no name filter.
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* If the filter does not contain the ':dm-name' part,
* then the volumes are matched without the dm-name
* part. If the filter contains the ':dm-name' part,
* then the filter is matched including the dm-name
* part.
* NULL means no volume filter.
* specification is ignored for filter matching.
* @param[in] apqn_filter the APQN filter. Can contain wild cards, and
* mutliple APQN filters separated by commas.
* NULL means no APQN filter.
* @param[in] volume_type If not NULL, specifies the volume type.
* @param[in] key_type The key type. NULL means no key type filter.
* @param[in] local if true, only local keys are processed
* @param[in] kms_bound if true, only KMS-bound keys are processed
* @param[in] process_func the callback function called for a matching key
* @param[in/out] process_private private data passed to the process_func
*
* @returns 0 for success, or a negative errno value in case of an error, or
* whatever process_func returns if process_func returns a non-zero
* value.
*/
static int _keystore_process_filtered(struct keystore *keystore,
const char *name_filter,
const char *volume_filter,
const char *apqn_filter,
const char *volume_type,
const char *key_type,
bool local, bool kms_bound,
process_key_t process_func,
void *process_private)
{
struct key_filenames file_names = { NULL, NULL, NULL };
char **apqn_filter_list = NULL;
char **vol_filter_list = NULL;
struct properties *key_props;
struct dirent **namelist;
int n, i, rc = 0;
bool skip = 0;
char *name;
int len;
pr_verbose(keystore, "Process_filtered: name_filter = '%s', "
"volume_filter = '%s', apqn_filter = '%s'",
name_filter ? name_filter : "(null)",
volume_filter ? volume_filter : "(null)",
apqn_filter ? apqn_filter : "(null)");
if (volume_filter != NULL)
vol_filter_list = str_list_split(volume_filter);
if (apqn_filter != NULL)
apqn_filter_list = str_list_split(apqn_filter);
n = scandir(keystore->directory, &namelist, _keystore_info_file_filter,
alphasort);
if (n == -1) {
rc = -errno;
pr_verbose(keystore, "scandir failed with: %s", strerror(-rc));
return rc;
}
for (i = 0; i < n ; i++) {
if (skip)
goto free;
name = namelist[i]->d_name;
len = strlen(name);
if (len > FILE_EXTENSION_LEN)
name[len - FILE_EXTENSION_LEN] = '\0';
if (_keystore_match_name_filter(name, name_filter) == 0) {
pr_verbose(keystore,
"Key '%s' filtered out due to name filter",
name);
goto free;
}
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto free;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto free_names;
key_props = properties_new();
rc = properties_load(key_props, file_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto free_prop;
}
rc = _keystore_match_filter_property(key_props,
PROP_NAME_VOLUMES,
vol_filter_list, NULL);
if (rc == 0) {
pr_verbose(keystore,
"Key '%s' filtered out due to volumes filter",
name);
goto free_prop;
}
rc = _keystore_match_filter_property(key_props,
PROP_NAME_APQNS,
apqn_filter_list,
_keystore_apqn_match);
if (rc == 0) {
pr_verbose(keystore,
"Key '%s' filtered out due to APQN filter",
name);
goto free_prop;
}
rc = _keystore_match_volume_type_property(key_props,
volume_type);
if (rc == 0) {
pr_verbose(keystore,
"Key '%s' filtered out due to volume type",
name);
goto free_prop;
}
rc = _keystore_match_key_type_property(key_props,
key_type);
if (rc == 0) {
pr_verbose(keystore,
"Key '%s' filtered out due to key type",
name);
goto free_prop;
}
if (local && _keystore_is_kms_bound_key(key_props, NULL)) {
pr_verbose(keystore,
"Key '%s' filtered out because it is KMS "
"bound", name);
rc = 0;
goto free_prop;
}
if (kms_bound && !_keystore_is_kms_bound_key(key_props, NULL)) {
pr_verbose(keystore,
"Key '%s' filtered out because it is not "
"KMS bound", name);
rc = 0;
goto free_prop;
}
rc = process_func(keystore, name, key_props, &file_names,
process_private);
if (rc != 0) {
pr_verbose(keystore, "Process function returned %d",
rc);
skip = 1;
}
free_prop:
properties_free(key_props);
free_names:
_keystore_free_key_filenames(&file_names);
free:
free(namelist[i]);
}
free(namelist);
if (vol_filter_list)
str_list_free_string_array(vol_filter_list);
if (apqn_filter_list)
str_list_free_string_array(apqn_filter_list);
pr_verbose(keystore, "Process_filtered rc = %d", rc);
return rc;
}
struct apqn_check {
bool noonlinecheck;
bool nomsg;
enum card_type cardtype;
};
/**
* Checks an APQN value for its syntax. This is a callback function for
* function _keystore_change_association().
*
* @param[in] apqn the APQN value to check
* @param[in] remove if true the apqn is removed
* @param[in] set if true the apqn is set (not used here)
* @param[out] normalized normalized value on return or NULL if no change
* @param[in] private private data (struct apqn_check)
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_apqn_check(const char *apqn, bool remove, bool UNUSED(set),
char **normalized, void *private)
{
struct apqn_check *info = (struct apqn_check *)private;
unsigned int card, domain;
regmatch_t pmatch[1];
unsigned int num;
regex_t reg_buf;
int rc;
*normalized = NULL;
rc = regcomp(®_buf, "[[:xdigit:]]+\\.[[:xdigit:]]", REG_EXTENDED);
if (rc != 0)
return -EIO;
rc = regexec(®_buf, apqn, (size_t) 1, pmatch, 0);
if (rc != 0) {
warnx("the APQN '%s' is not valid", apqn);
rc = -EINVAL;
goto out;
}
if (sscanf(apqn, "%x.%x%n", &card, &domain, (int *)&num) != 2 ||
num != strlen(apqn) || card > 0xff || domain > 0xFFFF) {
warnx("the APQN '%s' is not valid", apqn);
rc = -EINVAL;
goto out;
}
util_asprintf(normalized, "%02x.%04x", card, domain);
if (remove || info->noonlinecheck) {
rc = 0;
goto out;
}
rc = sysfs_is_apqn_online(card, domain, info->cardtype);
if (rc != 1) {
if (info->nomsg == 0)
warnx("The APQN %02x.%04x is %s", card, domain,
rc == -1 ? "not the correct type" : "not online");
rc = -EIO;
goto out;
} else {
rc = 0;
}
out:
regfree(®_buf);
return rc;
}
struct volume_check {
struct keystore *keystore;
const char *name;
const char *volume;
bool set;
bool nocheck;
};
/**
* Processing callback function for the volume association check function.
*
* @param[in] keystore the keystore (not used here)
* @param[in] name the name of the key
* @param[in] properties the properties object of the key (not used here)
* @param[in] file_names the file names used by this key (not used here)
* @param[in] private private data: struct volume_check
*
* @returns 0 if the key name is equal to the key we are checking the volume
* associations for, -EINVAL otherwise (i.e. to indicate duplicate
* volume association)
*/
static int _keystore_volume_check_process(struct keystore *UNUSED(keystore),
const char *name,
struct properties *UNUSED(properties),
struct key_filenames
*UNUSED(file_names),
void *private)
{
struct volume_check *info = (struct volume_check *)private;
if (info->set) {
if (strcmp(name, info->name) == 0)
return 0;
}
warnx("Key '%s' is already associated with volume '%s'", name,
info->volume);
return -EINVAL;
}
/**
* Checks if the volume is a block device
*
* @param[in] volume the volume to check
*
* @return 1 if the volume is a block device, 0 otherwise
*/
static int _keystore_is_block_device(const char *volume)
{
struct stat sb;
if (stat(volume, &sb))
return 0;
if (!S_ISBLK(sb.st_mode))
return 0;
return 1;
}
/**
* Checks an Volume value for its syntax and if it is already associated with
* another key. This is a callback function for function
* _keystore_change_association().
*
* @param[in] volume the Volume value to check
* @param[in] remove if true the volume is removed
* @param[in] set if true the volume is set
* @param[out] normalized normalized value on return or NULL if no change
* @param[in] private private data: struct volume_check
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_volume_check(const char *volume, bool remove, bool set,
char **normalized, void *private)
{
struct volume_check *info = (struct volume_check *)private;
char *ch;
int rc;
*normalized = NULL;
if (strpbrk(volume, "*?") != NULL) {
warnx("Volume name can not contain '*' or '?'");
return -EINVAL;
}
info->volume = util_strdup(volume);
ch = strchr(info->volume, ':');
if (ch == NULL || strlen(ch + 1) == 0) {
warnx("Volume specification must contain a dm-crypt mapping "
"name separated by a colon");
rc = -EINVAL;
goto out;
}
if (remove || info->nocheck) {
rc = 0;
goto out;
}
/*
* Strip off the ':dm-name' part, so that the volume filter only
* matches the volume part.
*/
*ch = '\0';
if (!_keystore_is_block_device(info->volume)) {
warnx("Volume '%s' is not a block device or is not available",
info->volume);
rc = -EINVAL;
goto out;
}
info->set = set;
rc = _keystore_process_filtered(info->keystore, NULL, info->volume,
NULL, NULL, NULL, false, false,
_keystore_volume_check_process, info);
out:
free((void *)info->volume);
info->volume = NULL;
return rc;
}
/**
* Locks the repository against other processes.
*
* @param[in] keystore the keystore
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_lock_repository(struct keystore *keystore)
{
char *lock_file_name;
struct stat sb;
int rc;
util_asprintf(&lock_file_name, "%s/%s", keystore->directory,
LOCK_FILE_NAME);
if (stat(lock_file_name, &sb) == 0) {
keystore->lock_fd = open(lock_file_name, O_RDONLY);
if (keystore->lock_fd == -1) {
rc = -errno;
warnx("Failed to open lock file '%s': %s",
lock_file_name,
strerror(-rc));
goto out;
}
} else {
keystore->lock_fd = open(lock_file_name, O_CREAT | O_RDONLY,
keystore->mode);
if (keystore->lock_fd == -1) {
rc = -errno;
warnx("Failed to create lock file '%s': %s",
lock_file_name,
strerror(-rc));
goto out;
}
if (fchown(keystore->lock_fd, geteuid(),
keystore->owner) != 0) {
rc = -errno;
warnx("chown faild on file '%s': %s", lock_file_name,
strerror(-rc));
return rc;
}
}
rc = flock(keystore->lock_fd, LOCK_EX);
if (rc == -1) {
rc = -errno;
warnx("Failed to obtain the file lock on '%s': %s",
lock_file_name, strerror((-rc)));
}
out:
free(lock_file_name);
return rc;
}
/**
* Unlocks the repository
*
* @param[in] keystore the keystore
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_unlock_repository(struct keystore *keystore)
{
int rc;
if (keystore->lock_fd == -1)
return 0;
rc = flock(keystore->lock_fd, LOCK_UN);
if (rc == -1) {
rc = -errno;
warnx("Failed to release the file lock: %s", strerror((-rc)));
}
close(keystore->lock_fd);
keystore->lock_fd = -1;
return rc;
}
/**
* Allocates new keystore object
*
* @param[in] directory the directory where the keystore resides
* @param[in] kms_info KMS plugin info
* @param[in] verbose if true, verbose messages are printed
*
* @returns a new keystore object
*/
struct keystore *keystore_new(const char *directory,
struct kms_info *kms_info, bool verbose)
{
struct keystore *keystore;
struct stat sb;
int rc;
util_assert(directory != NULL, "Internal error: directory is NULL");
if (stat(directory, &sb) != 0) {
warnx("Can not access '%s': %s", directory, strerror(errno));
return NULL;
}
if (!S_ISDIR(sb.st_mode)) {
warnx("'%s' is not a directory", directory);
return NULL;
}
if (!util_path_is_readable(directory) ||
!util_path_is_writable(directory)) {
warnx("Permission denied for '%s'", directory);
return NULL;
}
if (sb.st_mode & S_IWOTH) {
warnx("Directory '%s' is writable for others, this is not "
"accepted", directory);
return NULL;
}
keystore = util_zalloc(sizeof(struct keystore));
keystore->owner = sb.st_gid;
keystore->mode = sb.st_mode & (S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP |
S_IROTH);
keystore->lock_fd = -1;
keystore->verbose = verbose;
keystore->directory = util_strdup(directory);
if (keystore->directory[strlen(keystore->directory)-1] == '/')
keystore->directory[strlen(keystore->directory)-1] = '\0';
keystore->kms_info = kms_info;
rc = _keystore_lock_repository(keystore);
if (rc != 0) {
keystore_free(keystore);
return NULL;
}
pr_verbose(keystore, "Keystore in directory '%s' opened successfully",
keystore->directory);
return keystore;
}
/**
* Generate the key verification pattern from the specified secure key file
*
* @param[in] keystore the key store
* @param[in} keyfile the key file
* @param[in] vp buffer filled with the verification pattern
* @param[in] vp_len length of the buffer. Must be at
* least VERIFICATION_PATTERN_LEN bytes in size.
*
* @returns 0 for success or a negative errno in case of an error
*/
static int _keystore_generate_verification_pattern(struct keystore *keystore,
const char *keyfile,
char *vp, size_t vp_len)
{
size_t key_size;
u8 *key;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(keyfile != NULL, "Internal error: keyfile is NULL");
util_assert(vp != NULL, "Internal error: vp is NULL");
key = read_secure_key(keyfile, &key_size, keystore->verbose);
if (key == NULL)
return -EIO;
rc = generate_key_verification_pattern(key, key_size,
vp, vp_len, keystore->verbose);
free(key);
return rc;
}
/**
* Checks if the key verification pattern property exists. If not, then it is
* created from the secure key.
*
* @param[in] keystore the key store
* @param[in] file_names the file names of the key
* @param[in] key_props the properties of the key
*
* @returns 0 for success or a negative errno in case of an error
*/
static int _keystore_ensure_vp_exists(struct keystore *keystore,
const struct key_filenames *file_names,
struct properties *key_props)
{
char vp[VERIFICATION_PATTERN_LEN];
char *temp;
int rc;
temp = properties_get(key_props, PROP_NAME_KEY_VP);
if (temp != NULL) {
free(temp);
return 0;
}
rc = _keystore_generate_verification_pattern(keystore,
file_names->skey_filename,
vp, sizeof(vp));
if (rc != 0)
return rc;
rc = properties_set(key_props, PROP_NAME_KEY_VP, vp);
if (rc != 0)
return rc;
return 0;
}
/**
* Sets a timestamp to be used as creation/update/reencipher time into
* the specified property
*
* @param[in] properties the properties object
* @param[in] property the name of the property to set
*
* @returns 0 on success, or a negative errno value on error
*/
static int _keystore_set_timestamp_property(struct properties *properties,
const char *property)
{
char *time_str;
struct tm *tm;
time_t t;
int rc;
t = time(NULL);
tm = localtime(&t);
util_assert(tm != NULL, "Internal error: tm is NULL");
time_str = util_zalloc(200);
rc = strftime(time_str, 200, "%F %T", tm);
util_assert(rc > 0, "Internal error: strftime failed");
rc = properties_set(properties, property, time_str);
free(time_str);
return rc;
}
/**
* Sets the default properties of a key, such as key-type, cipher-name, and
* IV-mode
*
* @param[in] key_props the properties object
*/
static int _keystore_set_default_properties(struct properties *key_props)
{
int rc;
rc = properties_set(key_props, PROP_NAME_CIPHER, "paes");
if (rc != 0)
return rc;
rc = properties_set(key_props, PROP_NAME_IV_MODE, "plain64");
if (rc != 0)
return rc;
rc = _keystore_set_timestamp_property(key_props,
PROP_NAME_CREATION_TIME);
if (rc != 0)
return rc;
return 0;
}
/**
* Creates the key properties for a key
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] description textual description of the key (optional, can be NULL)
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] apqns a comma separated list of APQNs associated with this
* key (optional, can be NULL)
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[i] novolscheck if true, the specified Volume(s) are not checked for
* existence or duplicate use
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used.
* @param[in] volume_type the type of volume
* @param[in] key_type the type of the key
* @param[in] kms the name of the KMS plugin, or NULL if no KMS is bound
* @param[out] props the properties object is allocated and returned
*/
static int _keystore_create_info_props(struct keystore *keystore,
const char *name,
const char *description,
const char *volumes, const char *apqns,
bool noapqncheck, bool novolcheck,
size_t sector_size,
const char *volume_type,
const char *key_type,
const char *kms,
struct properties **props)
{
struct volume_check vol_check = { .keystore = keystore, .name = name,
.set = 0, .nocheck = novolcheck };
struct apqn_check apqn_check = { .noonlinecheck = noapqncheck,
.nomsg = 0,
.cardtype = get_card_type_for_keytype(
key_type), };
struct properties *key_props;
char temp[10];
int rc;
*props = NULL;
key_props = properties_new();
rc = _keystore_set_default_properties(key_props);
if (rc != 0)
goto out;
rc = properties_set(key_props, PROP_NAME_DESCRIPTION,
description != NULL ? description : "");
if (rc != 0) {
warnx("Invalid characters in description");
goto out;
}
rc = properties_set2(key_props, PROP_NAME_KEY_TYPE, key_type, true);
if (rc != 0) {
warnx("Invalid characters in key-type");
goto out;
}
rc = _keystore_change_association(key_props, PROP_NAME_VOLUMES,
volumes != NULL ? volumes : "",
"volume", _keystore_volume_check,
&vol_check);
if (rc != 0)
goto out;
rc = _keystore_change_association(key_props, PROP_NAME_APQNS,
apqns != NULL ? apqns : "",
"APQN", _keystore_apqn_check,
&apqn_check);
if (rc != 0)
goto out;
if (!_keystore_valid_sector_size(sector_size)) {
warnx("Invalid sector-size specified");
rc = -EINVAL;
goto out;
}
sprintf(temp, "%lu", sector_size);
rc = properties_set(key_props, PROP_NAME_SECTOR_SIZE,
temp);
if (rc != 0) {
warnx("Invalid characters in sector-size");
goto out;
}
if (volume_type == NULL)
volume_type = DEFAULT_VOLUME_TYPE;
if (!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
rc = -EINVAL;
goto out;
}
rc = properties_set2(key_props, PROP_NAME_VOLUME_TYPE, volume_type,
true);
if (rc != 0) {
warnx("Invalid characters in volume-type");
goto out;
}
if (kms != NULL) {
rc = properties_set(key_props, PROP_NAME_KMS, kms);
if (rc != 0) {
warnx("Invalid characters in KMS");
goto out;
}
}
out:
if (rc == 0)
*props = key_props;
else
properties_free(key_props);
return rc;
}
/**
* Creates an initial .info file for a key
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] info_filename the file name of the key info file
* @param[in] description textual description of the key (optional, can be NULL)
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] apqns a comma separated list of APQNs associated with this
* key (optional, can be NULL)
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used.
* @param[in] volume_type the type of volume
* @param[in] key_type the type of the key
* @param[in] kms the name of the KMS plugin, or NULL if no KMS is bound
*/
static int _keystore_create_info_file(struct keystore *keystore,
const char *name,
const struct key_filenames *filenames,
const char *description,
const char *volumes, const char *apqns,
bool noapqncheck,
size_t sector_size,
const char *volume_type,
const char *key_type,
const char *kms)
{
struct properties *key_props = NULL;
int rc;
rc = _keystore_create_info_props(keystore, name, description, volumes,
apqns, noapqncheck, false, sector_size,
volume_type, key_type, kms,
&key_props);
if (rc != 0)
return rc;
rc = _keystore_ensure_vp_exists(keystore, filenames, key_props);
if (rc != 0) {
warnx("Failed to generate the key verification pattern: %s",
strerror(-rc));
warnx("Make sure that kernel module 'paes_s390' is loaded and "
"that the 'paes' cipher is available");
goto out;
}
rc = properties_save(key_props, filenames->info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
filenames->info_filename, strerror(-rc));
goto out;
}
rc = _keystore_set_file_permission(keystore, filenames->info_filename);
if (rc != 0) {
remove(filenames->info_filename);
goto out;
}
out:
properties_free(key_props);
return rc;
}
/**
* Generates a secure key by random and adds it to the key store
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] description textual description of the key (optional, can be NULL)
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] apqns a comma separated list of APQNs associated with this
* key (optional, can be NULL)
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used.
* @param[in] keybits cryptographical size of the key in bits
* @param[in] xts if true, an XTS key is generated
* @param[in] clear_key_file if not NULL the secure key is generated from the
* clear key contained in the file denoted here.
* if NULL, the secure key is generated by random.
* @param[in] volume_type the type of volume
* @param[in] key_type the type of the key
* @param[in] pkey_fd the file descriptor of /dev/pkey
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_generate_key(struct keystore *keystore, const char *name,
const char *description, const char *volumes,
const char *apqns, bool noapqncheck,
size_t sector_size, size_t keybits, bool xts,
const char *clear_key_file, const char *volume_type,
const char *key_type, int pkey_fd)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
char **apqn_list = NULL;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
util_assert(key_type != NULL, "Internal error: key_type is NULL");
if (!_keystore_valid_key_type(key_type)) {
warnx("Invalid key-type specified");
return -EINVAL;
}
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out_free_key_filenames;
rc = _keystore_ensure_keyfiles_not_exist(&file_names, name);
if (rc != 0)
goto out_free_key_filenames;
rc = cross_check_apqns(apqns, NULL,
get_min_card_level_for_keytype(key_type),
get_min_fw_version_for_keytype(key_type),
get_card_type_for_keytype(key_type),
true, keystore->verbose);
if (rc == -EINVAL)
goto out_free_key_filenames;
if (rc != 0 && rc != -ENOTSUP && noapqncheck == 0) {
warnx("Your master key setup is improper");
goto out_free_key_filenames;
}
if (apqns != NULL)
apqn_list = str_list_split(apqns);
if (clear_key_file == NULL)
rc = generate_secure_key_random(pkey_fd,
file_names.skey_filename,
keybits, xts, key_type,
(const char **)apqn_list,
keystore->verbose);
else
rc = generate_secure_key_clear(pkey_fd,
file_names.skey_filename,
keybits, xts, clear_key_file,
key_type,
(const char **)apqn_list,
keystore->verbose);
if (rc != 0)
goto out_free_props;
rc = _keystore_set_file_permission(keystore, file_names.skey_filename);
if (rc != 0)
goto out_free_props;
rc = _keystore_create_info_file(keystore, name, &file_names,
description, volumes, apqns,
noapqncheck, sector_size, volume_type,
key_type, NULL);
if (rc != 0)
goto out_free_props;
pr_verbose(keystore,
"Successfully generated a secure key in '%s' and key info "
"in '%s'", file_names.skey_filename,
file_names.info_filename);
out_free_props:
if (apqn_list != NULL)
str_list_free_string_array(apqn_list);
if (key_props != NULL)
properties_free(key_props);
if (rc != 0)
remove(file_names.skey_filename);
out_free_key_filenames:
_keystore_free_key_filenames(&file_names);
if (rc != 0)
pr_verbose(keystore, "Failed to generate key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Generates a secure key by using a KMS plugin and adds it to the key store
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] description textual description of the key (optional, can be NULL)
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used.
* @param[in] keybits cryptographical size of the key in bits
* @param[in] xts if true, an XTS key is generated
* @param[in] volume_type the type of volume
* @param[in] key_type the type of the key (can be NULL)
* @param[in] kms_options an array of KMS options specified, or NULL if no
* KMS options have been specified
* @param[in] num_kms_options the number of options in above array
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_generate_key_kms(struct keystore *keystore, const char *name,
const char *description, const char *volumes,
size_t sector_size, size_t keybits, bool xts,
const char *volume_type, const char *key_type,
struct kms_option *kms_options,
size_t num_kms_options)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
struct kms_info *kms_info;
char *apqns = NULL;
int rc, i;
static const char * const key_types[] = {
KEY_TYPE_CCA_AESDATA,
KEY_TYPE_CCA_AESCIPHER,
KEY_TYPE_EP11_AES,
NULL
};
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
kms_info = keystore->kms_info;
if (kms_info->plugin_lib == NULL) {
warnx("The repository is not bound to a KMS plugin");
return -ENOENT;
}
if (key_type == NULL) {
for (i = 0; kms_info->funcs->kms_supports_key_type != NULL &&
key_types[i] != NULL; i++) {
if (kms_info->funcs->kms_supports_key_type(
kms_info->handle, key_types[i])) {
key_type = key_types[i];
break;
}
}
if (key_type == NULL)
key_type = KEY_TYPE_CCA_AESDATA;
}
if (!_keystore_valid_key_type(key_type)) {
warnx("Invalid key-type specified");
return -EINVAL;
}
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out_free_key_filenames;
rc = _keystore_ensure_keyfiles_not_exist(&file_names, name);
if (rc != 0)
goto out_free_key_filenames;
rc = get_kms_apqns_for_key_type(kms_info, key_type, true, &apqns,
keystore->verbose);
if (rc != 0) {
if (rc == -ENOTSUP)
warnx("Key-type not supported by the KMS plugin '%s'",
kms_info->plugin_name);
goto out_free_key_filenames;
}
pr_verbose(keystore, "APQNs for keytype %s: '%s'", key_type, apqns);
rc = _keystore_create_info_props(keystore, name, description, volumes,
apqns, false, false, sector_size,
volume_type, key_type,
kms_info->plugin_name, &key_props);
if (rc != 0)
goto out_free_key_filenames;
rc = generate_kms_key(kms_info, name, key_type, key_props, xts,
keybits, file_names.skey_filename,
kms_options, num_kms_options, keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to generate key '%s': %s",
kms_info->plugin_name, name, strerror(-rc));
print_last_kms_error(kms_info);
goto out_free_props;
}
rc = _keystore_set_file_permission(keystore, file_names.skey_filename);
if (rc != 0)
goto out_free_props;
rc = _keystore_ensure_vp_exists(keystore, &file_names, key_props);
if (rc != 0) {
warnx("Failed to generate the key verification pattern: %s",
strerror(-rc));
warnx("Make sure that kernel module 'paes_s390' is loaded and "
"that the 'paes' cipher is available");
goto out_free_props;
}
rc = properties_save(key_props, file_names.info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names.info_filename, strerror(-rc));
goto out_del_info_file;
}
rc = _keystore_set_file_permission(keystore, file_names.info_filename);
if (rc != 0) {
remove(file_names.info_filename);
goto out_del_info_file;
}
pr_verbose(keystore,
"Successfully generated a secure key with KMS plugin '%s' "
"in '%s' and key info in '%s'", kms_info->plugin_name,
file_names.skey_filename, file_names.info_filename);
out_del_info_file:
if (rc != 0)
remove(file_names.info_filename);
out_free_props:
if (key_props != NULL)
properties_free(key_props);
if (rc != 0)
remove(file_names.skey_filename);
out_free_key_filenames:
_keystore_free_key_filenames(&file_names);
if (apqns != NULL)
free(apqns);
if (rc != 0)
pr_verbose(keystore, "Failed to generate key '%s' with KMS "
"plugin '%s': %s", name, kms_info->plugin_name,
strerror(-rc));
return rc;
}
/**
* Imports a secure key from a file and adds it to the key store
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] description textual description of the key (optional, can be NULL)
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] apqns a comma separated list of APQNs associated with this
* key (optional, can be NULL)
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used.
* @param[in] import_file The name of a secure key containing the key to import
* @param[in] volume_type the type of volume
* @param[in] lib the external library struct
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_import_key(struct keystore *keystore, const char *name,
const char *description, const char *volumes,
const char *apqns, bool noapqncheck, size_t sector_size,
const char *import_file, const char *volume_type,
struct ext_lib *lib)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
size_t secure_key_size;
const char *key_type;
u8 mkvp[MKVP_LENGTH];
int selected = 1;
u8 *secure_key;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
util_assert(import_file != NULL, "Internal error: import_file is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out_free_key_filenames;
rc = _keystore_ensure_keyfiles_not_exist(&file_names, name);
if (rc != 0)
goto out_free_key_filenames;
secure_key = read_secure_key(import_file, &secure_key_size,
keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out_free_key_filenames;
}
key_type = get_key_type(secure_key, secure_key_size);
if (key_type == NULL) {
warnx("Key '%s' is not a valid secure key", name);
free(secure_key);
rc = -EINVAL;
goto out_free_key_filenames;
}
rc = get_master_key_verification_pattern(secure_key, secure_key_size,
mkvp, keystore->verbose);
if (rc != 0) {
warnx("Failed to get the master key verification pattern: %s",
strerror(-rc));
goto out_free_key;
}
rc = cross_check_apqns(apqns, mkvp,
get_min_card_level_for_keytype(key_type),
get_min_fw_version_for_keytype(key_type),
get_card_type_for_keytype(key_type),
true, keystore->verbose);
if (rc == -EINVAL)
goto out_free_key;
if (rc != 0 && rc != -ENOTSUP && noapqncheck == 0) {
warnx("Your master key setup is improper");
goto out_free_key;
}
if (is_cca_aes_cipher_key(secure_key, secure_key_size)) {
if (lib->cca->lib_csulcca == NULL) {
rc = load_cca_library(lib->cca, keystore->verbose);
if (rc != 0)
goto out_free_key;
}
rc = select_cca_adapter_by_mkvp(lib->cca, mkvp, apqns,
FLAG_SEL_CCA_MATCH_CUR_MKVP |
FLAG_SEL_CCA_MATCH_OLD_MKVP,
keystore->verbose);
if (rc == -ENOTSUP) {
rc = 0;
selected = 0;
}
if (rc != 0) {
warnx("No APQN found that is suitable for "
"working with the secure AES key '%s'", name);
rc = 0;
goto out_free_key;
}
rc = restrict_key_export(lib->cca, secure_key, secure_key_size,
keystore->verbose);
if (rc != 0) {
warnx("Failed to export-restrict the imported secure "
"key: %s", strerror(-rc));
if (!selected)
print_msg_for_cca_envvars("secure AES key");
goto out_free_key;
}
rc = check_aes_cipher_key(secure_key, secure_key_size);
if (rc != 0) {
warnx("The secure key to import might not be secure");
printf("%s: Do you want to import it anyway [y/N]? ",
program_invocation_short_name);
if (!prompt_for_yes(keystore->verbose)) {
warnx("Operation aborted");
rc = -ECANCELED;
goto out_free_key;
}
}
}
rc = write_secure_key(file_names.skey_filename, secure_key,
secure_key_size, keystore->verbose);
free(secure_key);
secure_key = NULL;
if (rc != 0)
goto out_free_props;
rc = _keystore_set_file_permission(keystore, file_names.skey_filename);
if (rc != 0)
goto out_free_props;
rc = _keystore_create_info_file(keystore, name, &file_names,
description, volumes, apqns,
noapqncheck, sector_size, volume_type,
key_type, NULL);
if (rc != 0)
goto out_free_props;
pr_verbose(keystore,
"Successfully imported a secure key in '%s' and key info in '%s'",
file_names.skey_filename, file_names.info_filename);
out_free_key:
if (secure_key != NULL)
free(secure_key);
out_free_props:
if (key_props != NULL)
properties_free(key_props);
if (rc != 0)
remove(file_names.skey_filename);
out_free_key_filenames:
_keystore_free_key_filenames(&file_names);
if (rc != 0)
pr_verbose(keystore, "Failed to import key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Changes properties of a key in the keystore.
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] description textual description of the key. If NULL then the
* description is not changed.
* @param[in] volumes a comma separated list of volumes associated with this
* key, or a volume prefixed with '+' or '-' to add or
* remove that volume respectively. If NULL then the
* volumes are not changed.
* @param[in] apqns a comma separated list of APQNs associated with this
* key, or an APQN prefixed with '+' or '-' to add or
* remove that APQN respectively. If NULL then the APQNs
* are not changed.
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] sector_size the sector size to use with dm-crypt. It must be power
* of two and in range 512 - 4096 bytes. 0 means that
* the sector size is not specified and the system
* default is used. Specify -1 if this property should
* not be changed.
* @param[in] volume_type the type of volume. If NULL then the volume type is
* not changed.
* *
* @returns 0 for success or a negative errno in case of an error
*
*/
int keystore_change_key(struct keystore *keystore, const char *name,
const char *description, const char *volumes,
const char *apqns, bool noapqncheck,
long int sector_size, const char *volume_type)
{
struct volume_check vol_check = { .keystore = keystore, .name = name,
.set = 0, .nocheck = 0 };
struct apqn_check apqn_check = { .noonlinecheck = noapqncheck,
.nomsg = 0 };
struct key_filenames file_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
char *upd_volume_type = NULL;
char *apqns_prop, *key_type;
char *upd_volumes = NULL;
size_t secure_key_size;
u8 mkvp[MKVP_LENGTH];
char sect_size[30];
u8 *secure_key;
bool kms_bound;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
key_props = properties_new();
rc = properties_load(key_props, file_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto out;
}
kms_bound = _keystore_is_kms_bound_key(key_props, NULL);
if (description != NULL) {
rc = properties_set(key_props, PROP_NAME_DESCRIPTION,
description);
if (rc != 0) {
warnx("Invalid characters in description");
goto out;
}
}
if (volumes != NULL) {
rc = _keystore_change_association(key_props, PROP_NAME_VOLUMES,
volumes, "volume",
_keystore_volume_check,
&vol_check);
if (rc != 0)
goto out;
upd_volumes = properties_get(key_props, PROP_NAME_VOLUMES);
}
if (apqns != NULL) {
if (kms_bound) {
rc = -EINVAL;
warnx("The APQN association of a KMS-bound key can not "
"be changed");
goto out;
}
rc = _keystore_change_association(key_props, PROP_NAME_APQNS,
apqns, "APQN",
_keystore_apqn_check,
&apqn_check);
if (rc != 0)
goto out;
secure_key = read_secure_key(file_names.skey_filename,
&secure_key_size,
keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
rc = get_master_key_verification_pattern(secure_key,
secure_key_size,
mkvp,
keystore->verbose);
free(secure_key);
if (rc)
goto out;
apqns_prop = properties_get(key_props, PROP_NAME_APQNS);
key_type = properties_get(key_props, PROP_NAME_KEY_TYPE);
rc = cross_check_apqns(apqns_prop, mkvp,
get_min_card_level_for_keytype(key_type),
get_min_fw_version_for_keytype(key_type),
get_card_type_for_keytype(key_type),
true, keystore->verbose);
free(apqns_prop);
free(key_type);
if (rc == -ENOTSUP)
rc = 0;
if (rc != 0 && noapqncheck == 0) {
warnx("Your master key setup is improper");
goto out;
}
}
if (sector_size >= 0) {
if (!_keystore_valid_sector_size(sector_size)) {
warnx("Invalid sector-size specified");
rc = -EINVAL;
goto out;
}
sprintf(sect_size, "%lu", sector_size);
rc = properties_set(key_props, PROP_NAME_SECTOR_SIZE,
sect_size);
if (rc != 0) {
warnx("Invalid characters in sector-size");
goto out;
}
}
if (volume_type != NULL) {
if (!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
rc = -EINVAL;
goto out;
}
rc = properties_set2(key_props, PROP_NAME_VOLUME_TYPE,
volume_type, true);
if (rc != 0) {
warnx("Invalid characters in volume-type");
goto out;
}
upd_volume_type = properties_get(key_props,
PROP_NAME_VOLUME_TYPE);
}
if (kms_bound) {
rc = perform_kms_login(keystore->kms_info, keystore->verbose);
if (rc != 0)
goto out;
rc = set_kms_key_properties(keystore->kms_info, key_props, NULL,
description, upd_volumes,
upd_volume_type, sector_size >= 0 ?
sect_size : NULL,
keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to set key properties "
"for key '%s': %s",
keystore->kms_info->plugin_name, name,
strerror(-rc));
print_last_kms_error(keystore->kms_info);
goto out;
}
}
rc = _keystore_ensure_vp_exists(keystore, &file_names, key_props);
/* ignore return code, vp generation might fail if key is not valid */
rc = _keystore_set_timestamp_property(key_props, PROP_NAME_CHANGE_TIME);
if (rc != 0)
goto out;
rc = properties_save(key_props, file_names.info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names.info_filename, strerror(-rc));
goto out;
}
pr_verbose(keystore, "Successfully changed key '%s'", name);
out:
_keystore_free_key_filenames(&file_names);
if (key_props != NULL)
properties_free(key_props);
if (upd_volumes != NULL)
free(upd_volumes);
if (upd_volume_type != NULL)
free(upd_volume_type);
if (rc != 0)
pr_verbose(keystore, "Failed to change key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Renames a key in the keystore
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] newname the new name of the key
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_rename_key(struct keystore *keystore, const char *name,
const char *newname)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct key_filenames new_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
bool reenc_exists = false;
char *msg;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
util_assert(newname != NULL, "Internal error: newname is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
rc = _keystore_get_key_filenames(keystore, newname, &new_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_not_exist(&new_names, newname);
if (rc != 0)
goto out;
if (rename(file_names.skey_filename, new_names.skey_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to rename '%s': %s",
file_names.skey_filename, strerror(-rc));
goto out;
}
if (rename(file_names.info_filename, new_names.info_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to rename '%s': %s",
file_names.info_filename, strerror(-rc));
goto out_rename_skey;
}
if (_keystore_reencipher_key_exists(&file_names)) {
reenc_exists = true;
if (rename(file_names.renc_filename,
new_names.renc_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to rename '%s': %s",
file_names.renc_filename, strerror(-rc));
goto out_rename_info;
}
}
key_props = properties_new();
rc = properties_load(key_props, new_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", newname);
goto out_rename_info;
}
if (_keystore_is_kms_bound_key(key_props, NULL)) {
rc = perform_kms_login(keystore->kms_info, keystore->verbose);
if (rc != 0)
goto out_rename_info;
rc = set_kms_key_properties(keystore->kms_info, key_props,
newname, NULL, NULL, NULL, NULL,
keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to set key properties "
"for key '%s': %s",
keystore->kms_info->plugin_name, name,
strerror(-rc));
print_last_kms_error(keystore->kms_info);
goto out_rename_info;
}
}
util_asprintf(&msg, "The following volumes are associated with the "
"renamed key '%s'. You should adjust the corresponding "
"crypttab entries and 'cryptsetup plainOpen' commands to "
"use the new name.", newname);
_keystore_msg_for_volumes(msg, key_props, VOLUME_TYPE_PLAIN);
free(msg);
pr_verbose(keystore, "Successfully renamed key '%s' to '%s'", name,
newname);
goto out;
out_rename_info:
if (reenc_exists)
rename(file_names.renc_filename, new_names.renc_filename);
rename(new_names.info_filename, file_names.info_filename);
out_rename_skey:
rename(new_names.skey_filename, file_names.skey_filename);
out:
_keystore_free_key_filenames(&file_names);
_keystore_free_key_filenames(&new_names);
if (key_props != NULL)
properties_free(key_props);
if (rc != 0)
pr_verbose(keystore, "Failed to rename key '%s'to '%s': %s",
name, newname, strerror(-rc));
return rc;
}
/**
* Sets up a util_rec used for displaying key information
*
* @param[in] validation if true the record is used for validate, else it is
* used for display
*
* @returns a pointer to a set up struct util_rec.
*/
static struct util_rec *_keystore_setup_record(bool validation)
{
struct util_rec *rec;
rec = util_rec_new_long("-", ":", REC_KEY, 28, 54);
util_rec_def(rec, REC_KEY, UTIL_REC_ALIGN_LEFT, 54, REC_KEY);
if (validation)
util_rec_def(rec, REC_STATUS, UTIL_REC_ALIGN_LEFT, 54,
REC_STATUS);
util_rec_def(rec, REC_DESCRIPTION, UTIL_REC_ALIGN_LEFT, 54,
REC_DESCRIPTION);
util_rec_def(rec, REC_SEC_KEY_SIZE, UTIL_REC_ALIGN_LEFT, 20,
REC_SEC_KEY_SIZE);
util_rec_def(rec, REC_CLR_KEY_SIZE, UTIL_REC_ALIGN_LEFT, 20,
REC_CLR_KEY_SIZE);
util_rec_def(rec, REC_XTS, UTIL_REC_ALIGN_LEFT, 3, REC_XTS);
util_rec_def(rec, REC_KEY_TYPE, UTIL_REC_ALIGN_LEFT, 54, REC_KEY_TYPE);
if (validation)
util_rec_def(rec, REC_MASTERKEY, UTIL_REC_ALIGN_LEFT, 54,
REC_MASTERKEY);
util_rec_def(rec, REC_VOLUMES, UTIL_REC_ALIGN_LEFT, 54, REC_VOLUMES);
util_rec_def(rec, REC_APQNS, UTIL_REC_ALIGN_LEFT, 54, REC_APQNS);
util_rec_def(rec, REC_KEY_FILE, UTIL_REC_ALIGN_LEFT, 54, REC_KEY_FILE);
util_rec_def(rec, REC_SECTOR_SIZE, UTIL_REC_ALIGN_LEFT, 54,
REC_SECTOR_SIZE);
util_rec_def(rec, REC_VOLUME_TYPE, UTIL_REC_ALIGN_LEFT, 54,
REC_VOLUME_TYPE);
util_rec_def(rec, REC_KEY_VP, UTIL_REC_ALIGN_LEFT, 54, REC_KEY_VP);
util_rec_def(rec, REC_KMS, UTIL_REC_ALIGN_LEFT, 54, REC_KMS);
util_rec_def(rec, REC_KMS_KEY_LABEL, UTIL_REC_ALIGN_LEFT, 54,
REC_KMS_KEY_LABEL);
util_rec_def(rec, REC_CREATION_TIME, UTIL_REC_ALIGN_LEFT, 54,
REC_CREATION_TIME);
util_rec_def(rec, REC_CHANGE_TIME, UTIL_REC_ALIGN_LEFT, 54,
REC_CHANGE_TIME);
util_rec_def(rec, REC_REENC_TIME, UTIL_REC_ALIGN_LEFT, 54,
REC_REENC_TIME);
return rec;
}
static void _keystore_print_record(struct util_rec *rec,
const char *name,
struct properties *properties,
bool validation, const char *skey_filename,
size_t secure_key_size, bool is_xts,
size_t clear_key_bitsize, bool valid,
bool is_old_mk, bool reenc_pending, u8 *mkvp)
{
char temp_vp[VERIFICATION_PATTERN_LEN + 2];
char *kms_xts_key1_label = NULL;
char *kms_xts_key2_label = NULL;
char *kms_key_label = NULL;
char *volumes_argz = NULL;
size_t label_argz_len = 0;
size_t volumes_argz_len;
char *apqns_argz = NULL;
char *label_argz = NULL;
size_t sector_size = 0;
size_t apqns_argz_len;
char *description;
char *volume_type;
char *reencipher;
char *key_type;
char *creation;
char *volumes;
char *change;
char *apqns;
char *temp;
char *kms;
char *vp;
int len;
description = properties_get(properties, PROP_NAME_DESCRIPTION);
volumes = properties_get(properties, PROP_NAME_VOLUMES);
if (volumes != NULL)
util_assert(argz_create_sep(volumes, ',',
&volumes_argz,
&volumes_argz_len) == 0,
"Internal error: argz_create_sep failed");
apqns = properties_get(properties, PROP_NAME_APQNS);
if (apqns != NULL)
util_assert(argz_create_sep(apqns, ',',
&apqns_argz,
&apqns_argz_len) == 0,
"Internal error: argz_create_sep failed");
temp = properties_get(properties, PROP_NAME_SECTOR_SIZE);
if (temp != NULL) {
util_assert(sscanf(temp, "%lu", §or_size) == 1,
"Internal error: sscanf failed");
free(temp);
}
creation = properties_get(properties, PROP_NAME_CREATION_TIME);
change = properties_get(properties, PROP_NAME_CHANGE_TIME);
reencipher = properties_get(properties, PROP_NAME_REENC_TIME);
vp = properties_get(properties, PROP_NAME_KEY_VP);
volume_type = _keystore_get_volume_type(properties);
key_type = properties_get(properties, PROP_NAME_KEY_TYPE);
if (_keystore_is_kms_bound_key(properties, &kms)) {
if (is_xts) {
kms_xts_key1_label = properties_get(properties,
PROP_NAME_KMS_XTS_KEY1_LABEL);
kms_xts_key2_label = properties_get(properties,
PROP_NAME_KMS_XTS_KEY2_LABEL);
if (kms_xts_key1_label != NULL &&
kms_xts_key2_label != NULL) {
label_argz_len = util_asprintf(&label_argz,
"%s%c%s", kms_xts_key1_label, '\0',
kms_xts_key2_label) + 1;
}
} else {
kms_key_label = properties_get(properties,
PROP_NAME_KMS_KEY_LABEL);
if (kms_key_label != NULL) {
label_argz = kms_key_label;
label_argz_len = strlen(label_argz) + 1;
kms_key_label = NULL;
}
}
}
util_rec_set(rec, REC_KEY, name);
if (validation)
util_rec_set(rec, REC_STATUS, valid ? "Valid" : "Invalid");
util_rec_set(rec, REC_DESCRIPTION,
description != NULL ? description : "");
util_rec_set(rec, REC_SEC_KEY_SIZE, "%lu bytes", secure_key_size);
if ((!validation || valid) && clear_key_bitsize != 0)
util_rec_set(rec, REC_CLR_KEY_SIZE, "%lu bits",
clear_key_bitsize);
else
util_rec_set(rec, REC_CLR_KEY_SIZE, "(unknown)");
util_rec_set(rec, REC_XTS, is_xts ? "Yes" : "No");
util_rec_set(rec, REC_KEY_TYPE, key_type);
if (validation) {
if (valid)
util_rec_set(rec, REC_MASTERKEY,
"%s master key (MKVP: %s)",
is_old_mk ? "OLD" : "CURRENT",
printable_mkvp(
get_card_type_for_keytype(key_type),
mkvp));
else
util_rec_set(rec, REC_MASTERKEY,
"(unknown, MKVP: %s)",
printable_mkvp(
get_card_type_for_keytype(key_type),
mkvp));
}
if (volumes_argz != NULL)
util_rec_set_argz(rec, REC_VOLUMES, volumes_argz,
volumes_argz_len);
else
util_rec_set(rec, REC_VOLUMES, "(none)");
if (apqns_argz != NULL)
util_rec_set_argz(rec, REC_APQNS,
apqns_argz, apqns_argz_len);
else
util_rec_set(rec, REC_APQNS, "(none)");
util_rec_set(rec, REC_KEY_FILE, skey_filename);
if (sector_size == 0)
util_rec_set(rec, REC_SECTOR_SIZE, "(system default)");
else
util_rec_set(rec, REC_SECTOR_SIZE, "%lu bytes",
sector_size);
util_rec_set(rec, REC_VOLUME_TYPE, volume_type);
if (vp != NULL) {
len = sprintf(temp_vp, "%.*s%c%.*s",
VERIFICATION_PATTERN_LEN / 2, vp,
'\0', VERIFICATION_PATTERN_LEN / 2,
&vp[VERIFICATION_PATTERN_LEN / 2]);
util_rec_set_argz(rec, REC_KEY_VP, temp_vp, len + 1);
} else {
util_rec_set(rec, REC_KEY_VP, "(not available)");
}
util_rec_set(rec, REC_KMS, kms != NULL ? kms : "(local)");
if (kms != NULL && label_argz != NULL)
util_rec_set_argz(rec, REC_KMS_KEY_LABEL, label_argz,
label_argz_len);
else
util_rec_set(rec, REC_KMS_KEY_LABEL, "(local)");
util_rec_set(rec, REC_CREATION_TIME, creation);
util_rec_set(rec, REC_CHANGE_TIME,
change != NULL ? change : "(never)");
util_rec_set(rec, REC_REENC_TIME, "%s %s",
reencipher != NULL ? reencipher : "(never)",
reenc_pending ? "(re-enciphering pending)" : "");
util_rec_print(rec);
if (description != NULL)
free(description);
if (volumes != NULL)
free(volumes);
if (volumes_argz != NULL)
free(volumes_argz);
if (apqns != NULL)
free(apqns);
if (apqns_argz != NULL)
free(apqns_argz);
if (creation != NULL)
free(creation);
if (change != NULL)
free(change);
if (reencipher != NULL)
free(reencipher);
if (vp != NULL)
free(vp);
if (volume_type != NULL)
free(volume_type);
if (key_type != NULL)
free(key_type);
if (kms != NULL)
free(kms);
if (kms_key_label != NULL)
free(kms_key_label);
if (kms_xts_key1_label != NULL)
free(kms_xts_key1_label);
if (kms_xts_key2_label != NULL)
free(kms_xts_key2_label);
if (label_argz != NULL)
free(label_argz);
}
struct validate_info {
struct util_rec *rec;
int pkey_fd;
bool noapqncheck;
unsigned long int num_valid;
unsigned long int num_invalid;
unsigned long int num_warnings;
};
/**
* Displays the status of the associated APQNs.
*
* @param[in] keystore the key store
* @param[in] properties the properties of the key
* @param[in] mkvp the master key verification pattern of the key
*
* @returns 0 in case of success, 1 if at least one of the APQNs is not
* available or has a master key mismatch
*/
static int _keystore_display_apqn_status(struct keystore *keystore,
struct properties *properties,
u8 *mkvp)
{
int rc, warning = 0;
char *apqns;
char *key_type;
apqns = properties_get(properties, PROP_NAME_APQNS);
if (apqns == NULL)
return 0;
key_type = properties_get(properties, PROP_NAME_KEY_TYPE);
rc = cross_check_apqns(apqns, mkvp,
get_min_card_level_for_keytype(key_type),
get_min_fw_version_for_keytype(key_type),
get_card_type_for_keytype(key_type), true,
keystore->verbose);
if (rc != 0 && rc != -ENOTSUP)
warning = 1;
if (warning)
printf("\n");
free(apqns);
free(key_type);
return warning;
}
/**
* Displays the status of the associated volumes.
*
* @param[in] properties the properties of the key
* @param[in] name the name of the key
*
* @returns 0 in case of success, 1 if at least one of the volumes is not
* available
*/
static int _keystore_display_volume_status(struct properties *properties,
const char *name)
{
int i, warning = 0;
char **volume_list;
char *volumes;
char *ch;
volumes = properties_get(properties, PROP_NAME_VOLUMES);
if (volumes == NULL)
return 0;
volume_list = str_list_split(volumes);
for (i = 0; volume_list[i] != NULL; i++) {
ch = strchr(volume_list[i], ':');
if (ch != NULL)
*ch = '\0';
if (!_keystore_is_block_device(volume_list[i])) {
printf("WARNING: The volume '%s' associated with "
"key '%s' is not available\n", volume_list[i],
name);
warning = 1;
}
}
if (warning)
printf("\n");
free(volumes);
str_list_free_string_array(volume_list);
return warning;
}
/**
* Processing function for the key validate function. Prints validation
* information for the key to be validated.
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct validate_info
*
* @returns 0 if the validation is successful, a negative errno value otherwise
*/
static int _keystore_process_validate(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct validate_info *info = (struct validate_info *)private;
char **apqn_list = NULL;
size_t clear_key_bitsize;
size_t secure_key_size;
u8 mkvp[MKVP_LENGTH];
char *apqns = NULL;
u8 *secure_key = NULL;
int is_old_mk;
int rc, valid;
rc = _keystore_ensure_keyfiles_exist(file_names, name);
if (rc != 0)
goto out;
secure_key = read_secure_key(file_names->skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
apqns = properties_get(properties, PROP_NAME_APQNS);
if (apqns != NULL)
apqn_list = str_list_split(apqns);
rc = validate_secure_key(info->pkey_fd, secure_key, secure_key_size,
&clear_key_bitsize, &is_old_mk,
(const char **)apqn_list, keystore->verbose);
if (rc != 0) {
valid = 0;
info->num_invalid++;
rc = 0;
} else {
info->num_valid++;
valid = 1;
}
rc = get_master_key_verification_pattern(secure_key, secure_key_size,
mkvp, keystore->verbose);
if (rc != 0)
goto out;
_keystore_print_record(info->rec, name, properties, 1,
file_names->skey_filename, secure_key_size,
is_xts_key(secure_key, secure_key_size),
clear_key_bitsize, valid, is_old_mk,
_keystore_reencipher_key_exists(file_names),
mkvp);
if (valid && is_old_mk) {
util_print_indented("WARNING: The secure key is currently "
"enciphered with the OLD master key. "
"To mitigate the danger of data loss "
"re-encipher it with the CURRENT "
"master key\n", 0);
info->num_warnings++;
}
if (info->noapqncheck == 0)
if (_keystore_display_apqn_status(keystore, properties,
mkvp) != 0)
info->num_warnings++;
if (_keystore_display_volume_status(properties, name) != 0)
info->num_warnings++;
out:
if (secure_key != NULL)
free(secure_key);
if (apqns != NULL)
free(apqns);
if (apqn_list != NULL)
str_list_free_string_array(apqn_list);
if (rc != 0)
pr_verbose(keystore, "Failed to validate key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Validates one or multiple keys in the keystore
*
* @param[in] keystore the key store
* @param[in] name_filter the name filter to select the key (can be NULL)
* @param[in] apqn_filter the APQN filter to select the key (can be NULL)
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] pkey_fd the file descriptor of /dev/pkey
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_validate_key(struct keystore *keystore, const char *name_filter,
const char *apqn_filter, bool noapqncheck,
int pkey_fd)
{
struct validate_info info;
struct util_rec *rec;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
rec = _keystore_setup_record(1);
info.pkey_fd = pkey_fd;
info.noapqncheck = noapqncheck;
info.rec = rec;
info.num_valid = 0;
info.num_invalid = 0;
info.num_warnings = 0;
rc = _keystore_process_filtered(keystore, name_filter, NULL,
apqn_filter, NULL, NULL, false, false,
_keystore_process_validate, &info);
util_rec_free(rec);
if (rc != 0) {
pr_verbose(keystore, "Failed to validate keys: %s",
strerror(-rc));
} else {
pr_verbose(keystore, "Successfully validated keys");
printf("%lu keys are valid, %lu keys are invalid, %lu "
"warnings\n", info.num_valid, info.num_invalid,
info.num_warnings);
}
return rc;
}
struct reencipher_params {
bool from_old;
bool to_new;
bool complete;
int inplace; /* -1 = autodetect, 0 = not in-place, 1 = in-place */
};
struct reencipher_info {
struct reencipher_params params;
int pkey_fd;
struct ext_lib *lib;
unsigned long num_reenciphered;
unsigned long num_failed;
unsigned long num_skipped;
};
/**
* Perform the reencipherment of a key
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] lib the external library struct
* @param[in] params reenciphering parameters
* @param[in] secure_key a buffer containing the secure key
* @param[in] secure_key_size the size of the secure key
* @param[in] is_old_mk if true the key is currently re-enciphered with the
* OLD master key
* @param[in] apqns the associated APQNs (or NULL if none)
* @returns 0 if the re-enciphering is successful, a negative errno value
* otherwise, 1 if it was skipped
*/
static int _keystore_perform_reencipher(struct keystore *keystore,
const char *name,
struct ext_lib *lib,
struct reencipher_params *params,
u8 *secure_key, size_t secure_key_size,
bool is_old_mk, const char *apqns)
{
bool selected;
int rc;
if (!params->from_old && !params->to_new) {
/* Autodetect reencipher mode */
if (is_old_mk) {
params->from_old = 1;
util_print_indented("The secure key is currently "
"enciphered with the OLD "
"master key and is being "
"re-enciphered with the CURRENT "
"master key\n", 0);
} else {
params->to_new = 1;
util_print_indented("The secure key is currently "
"enciphered with the CURRENT "
"master key and is being "
"re-enciphered with the NEW "
"master key\n", 0);
}
}
if (params->from_old) {
if (params->inplace == -1)
params->inplace = 1;
pr_verbose(keystore,
"Secure key '%s' will be re-enciphered from OLD "
"to the CURRENT master key", name);
rc = reencipher_secure_key(lib, secure_key, secure_key_size,
apqns, REENCIPHER_OLD_TO_CURRENT,
&selected, keystore->verbose);
if (rc != 0) {
if (rc == -ENODEV) {
warnx("No APQN found that is suitable for "
"re-enciphering this secure AES key");
} else {
warnx("Failed to re-encipher '%s' from OLD to "
"CURRENT master key", name);
if (!selected &&
!is_ep11_aes_key(secure_key,
secure_key_size))
print_msg_for_cca_envvars(
"secure AES key");
}
return rc;
}
}
if (params->to_new) {
pr_verbose(keystore,
"Secure key '%s' will be re-enciphered from "
"CURRENT to the NEW master key", name);
if (params->inplace == -1)
params->inplace = 0;
rc = reencipher_secure_key(lib, secure_key, secure_key_size,
apqns, REENCIPHER_CURRENT_TO_NEW,
&selected, keystore->verbose);
if (rc != 0) {
if (rc == -ENODEV) {
warnx("No APQN found that is suitable for "
"re-enciphering this secure AES key and "
"has the NEW master key loaded");
} else {
warnx("Failed to re-encipher '%s' from CURRENT "
"to NEW master key", name);
if (!selected &&
!is_ep11_aes_key(secure_key,
secure_key_size))
print_msg_for_cca_envvars(
"secure AES key");
}
return rc;
}
}
return 0;
}
/**
* Processing function for the key re-enciphering function.
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key (not used here)
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 if the re-enciphering is successful, a negative errno value
* otherwise
*/
static int _keystore_process_reencipher(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct reencipher_info *info = (struct reencipher_info *)private;
struct reencipher_params params = info->params;
size_t clear_key_bitsize;
size_t secure_key_size;
char **apqn_list = NULL;
u8 *secure_key = NULL;
char *apqns = NULL;
char *out_file;
int is_old_mk;
char *temp;
int rc;
rc = _keystore_ensure_keyfiles_exist(file_names, name);
if (rc != 0)
goto out;
pr_verbose(keystore, "Complete reencipher: %d", params.complete);
pr_verbose(keystore, "In-place reencipher: %d", params.inplace);
if (params.complete) {
if (!_keystore_reencipher_key_exists(file_names)) {
warnx("Staged re-enciphering is not pending for key "
"'%s', skipping",
name);
info->num_skipped++;
rc = 0;
goto out;
}
printf("Completing re-enciphering for key '%s'\n", name);
params.inplace = 1;
}
secure_key = read_secure_key(params.complete ?
file_names->renc_filename :
file_names->skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
apqns = properties_get(properties, PROP_NAME_APQNS);
if (apqns != NULL)
apqn_list = str_list_split(apqns);
rc = validate_secure_key(info->pkey_fd, secure_key, secure_key_size,
&clear_key_bitsize, &is_old_mk,
(const char **)apqn_list, keystore->verbose);
if (rc != 0) {
if (params.complete) {
warnx("Key '%s' is not valid, re-enciphering is not "
"completed", name);
warnx("The new master key might yet have to be set "
"as the CURRENT master key.");
} else {
warnx("Key '%s' is not valid, it is not re-enciphered",
name);
info->num_skipped++;
rc = 0;
}
goto out;
}
if (!params.complete) {
printf("Re-enciphering key '%s'\n", name);
rc = _keystore_perform_reencipher(keystore, name, info->lib,
¶ms, secure_key,
secure_key_size, is_old_mk,
apqns);
if (rc < 0)
goto out;
if (rc > 0) {
info->num_skipped++;
rc = 0;
goto out;
}
}
pr_verbose(keystore, "In-place reencipher: %d", params.inplace);
out_file = params.inplace == 1 ? file_names->skey_filename :
file_names->renc_filename;
rc = write_secure_key(out_file, secure_key,
secure_key_size, keystore->verbose);
if (rc != 0)
goto out;
if (params.complete || params.inplace == 1) {
rc = _keystore_set_timestamp_property(properties,
PROP_NAME_REENC_TIME);
if (rc != 0)
goto out;
rc = _keystore_ensure_vp_exists(keystore, file_names,
properties);
if (rc != 0) {
warnx("Failed to generate the key verification pattern "
"for key '%s': %s", file_names->skey_filename,
strerror(-rc));
warnx("Make sure that kernel module 'paes_s390' is loaded and "
"that the 'paes' cipher is available");
goto out;
}
rc = properties_save(properties, file_names->info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Failed to write key info file '%s': %s",
file_names->info_filename, strerror(-rc));
goto out;
}
util_asprintf(&temp, "The following LUKS2 volumes are "
"encrypted with key '%s'. You should also "
"re-encipher the volume key of those volumes "
"using command 'zkey-cryptsetup reencipher "
"<device>':", name);
_keystore_msg_for_volumes(temp, properties, VOLUME_TYPE_LUKS2);
free(temp);
}
if (params.complete ||
(params.inplace && _keystore_reencipher_key_exists(file_names))) {
if (remove(file_names->renc_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to remove '%s': %s",
file_names->renc_filename, strerror(-rc));
goto out;
}
}
if (params.inplace != 1) {
util_asprintf(&temp, "Staged re-enciphering is initiated for "
"key '%s'. After the NEW master key has been "
"set to become the CURRENT master key run "
"'zkey reencipher' with option '--complete' to "
"complete the re-enciphering process", name);
util_print_indented(temp, 0);
free(temp);
}
info->num_reenciphered++;
out:
if (apqns != NULL)
free(apqns);
if (apqn_list != NULL)
str_list_free_string_array(apqn_list);
if (secure_key != NULL)
free(secure_key);
printf("\n");
if (rc != 0) {
info->num_failed++;
pr_verbose(keystore, "Failed to re-encipher key '%s': %s",
name, strerror(-rc));
rc = 0;
}
return rc;
}
/**
* Reenciphers a key in the keystore
*
* @param[in] keystore the key store
* @param[in] name_filter the name filter to select the key (can be NULL)
* @param[in] apqn_filter the APQN filter to seletc the key (can be NULL)
* @param[in] from_old If true the key is reenciphered from the OLD to the
* CURRENT master key.
* @param[in] to_new If true the key is reenciphered from the CURRENT to
* the OLD master key.
* @param[in] inplace if true, the key will be re-enciphere in-place
* @param[in] staged if true, the key will be re-enciphere not in-place
* @param[in] complete if true, a pending re-encipherment is completed
* @param[in] pkey_fd the file descriptor of /dev/pkey
* @param[in] lib the external library struct
* Note: if both fromOld and toNew are FALSE, then the reencipherement mode is
* detected automatically. If both are TRUE then the key is reenciphered
* from the OLD to the NEW master key.
* Note: if both inplace and staged are FLASE, then the key is re-enciphered
* inplace when for OLD-to-CURRENT, and is reenciphered staged for
* CURRENT-to-NEW.
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_reencipher_key(struct keystore *keystore, const char *name_filter,
const char *apqn_filter,
bool from_old, bool to_new, bool inplace,
bool staged, bool complete, int pkey_fd,
struct ext_lib *lib)
{
struct reencipher_info info;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
info.params.from_old = from_old;
info.params.to_new = to_new;
info.params.inplace = -1;
if (inplace)
info.params.inplace = 1;
if (staged)
info.params.inplace = 0;
info.params.complete = complete;
info.pkey_fd = pkey_fd;
info.lib = lib;
info.num_failed = 0;
info.num_reenciphered = 0;
info.num_skipped = 0;
rc = _keystore_process_filtered(keystore, name_filter, NULL,
apqn_filter, NULL, NULL, false, false,
_keystore_process_reencipher, &info);
if (rc != 0) {
pr_verbose(keystore, "Failed to re-encipher keys: %s",
strerror(-rc));
} else {
pr_verbose(keystore, "Successfully re-enciphered keys");
printf("%lu keys re-enciphered, %lu keys skipped, %lu keys "
"failed to re-encipher\n",
info.num_reenciphered, info.num_skipped,
info.num_failed);
if (info.num_failed > 0)
rc = -EIO;
}
return rc;
}
/**
* Copies (duplicates) a key in the keystore. Any existing volume associations
* are removed from the copy, because a volume can only be associated to one
* key. However, you can set new volume associations using the volumes
* parameter.
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] newname the new name of the key
* @param[in] volumes a comma separated list of volumes associated with this
* key (optional, can be NULL)
* @param[in] local if true copy a KMS-bound key to a local one
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_copy_key(struct keystore *keystore, const char *name,
const char *newname, const char *volumes, bool local)
{
struct volume_check vol_check = { .keystore = keystore, .name = newname,
.set = 0, .nocheck = 0 };
struct key_filenames file_names = { NULL, NULL, NULL };
struct key_filenames new_names = { NULL, NULL, NULL };
struct properties *key_prop = NULL;
size_t secure_key_size;
bool kms_bound = false;
u8 *secure_key;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
util_assert(newname != NULL, "Internal error: newname is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
rc = _keystore_get_key_filenames(keystore, newname, &new_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_not_exist(&new_names, newname);
if (rc != 0)
goto out;
key_prop = properties_new();
rc = properties_load(key_prop, file_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto out;
}
kms_bound = _keystore_is_kms_bound_key(key_prop, NULL);
if (kms_bound && !local) {
rc = -EINVAL;
warnx("Copying a KMS-bound key requires the "
"'--local|-L' option");
goto out;
}
secure_key = read_secure_key(file_names.skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
rc = write_secure_key(new_names.skey_filename, secure_key,
secure_key_size, keystore->verbose);
free(secure_key);
if (rc != 0)
goto out;
rc = _keystore_set_file_permission(keystore, new_names.skey_filename);
if (rc != 0)
goto out;
/*
* Remove any volume association, since a volume can only be associated
* with one key
*/
rc = properties_set(key_prop, PROP_NAME_VOLUMES, "");
if (rc != 0)
goto out;
if (volumes != NULL) {
rc = _keystore_change_association(key_prop, PROP_NAME_VOLUMES,
volumes,
"volume",
_keystore_volume_check,
&vol_check);
if (rc != 0)
goto out;
}
rc = properties_remove(key_prop, PROP_NAME_CHANGE_TIME);
if (rc != 0 && rc != -ENOENT)
goto out;
rc = properties_remove(key_prop, PROP_NAME_REENC_TIME);
if (rc != 0 && rc != -ENOENT)
goto out;
rc = _keystore_set_timestamp_property(key_prop,
PROP_NAME_CREATION_TIME);
if (rc != 0)
goto out;
if (kms_bound) {
rc = _keystore_kms_key_unbind(keystore, key_prop);
if (rc != 0)
goto out;
}
rc = properties_save(key_prop, new_names.info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
new_names.info_filename, strerror(-rc));
remove(new_names.skey_filename);
goto out;
}
rc = _keystore_set_file_permission(keystore, new_names.info_filename);
if (rc != 0)
goto out;
pr_verbose(keystore, "Successfully copied key '%s' to '%s'", name,
newname);
out:
if (rc != 0) {
remove(new_names.skey_filename);
remove(new_names.info_filename);
}
_keystore_free_key_filenames(&file_names);
_keystore_free_key_filenames(&new_names);
if (key_prop != NULL)
properties_free(key_prop);
if (rc != 0)
pr_verbose(keystore, "Failed to copy key '%s'to '%s': %s",
name, newname, strerror(-rc));
return rc;
}
/**
* Exports a key from the keystore to a file
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] export_file the name of the file to export the key to
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_export_key(struct keystore *keystore, const char *name,
const char *export_file)
{
struct key_filenames file_names = { NULL, NULL, NULL };
size_t secure_key_size;
u8 *secure_key;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
util_assert(export_file != NULL, "Internal error: export_file is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
secure_key = read_secure_key(file_names.skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
rc = write_secure_key(export_file, secure_key,
secure_key_size, keystore->verbose);
free(secure_key);
pr_verbose(keystore, "Successfully exported key '%s' to '%s'", name,
export_file);
out:
_keystore_free_key_filenames(&file_names);
if (rc != 0)
pr_verbose(keystore, "Failed to export key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Prompts the user to confirm deletion of a key
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] file_names the file names of the key
*
* @returnd 0 if the user confirmed the deletion, a negative errno value
* otherwise
*/
static int _keystore_prompt_for_remove(struct keystore *keystore,
const char *name,
struct key_filenames *file_names)
{
struct properties *key_prop;
char *msg;
int rc;
key_prop = properties_new();
rc = properties_load(key_prop, file_names->info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto out;
}
util_asprintf(&msg, "When you remove key '%s' the following volumes "
"will no longer be usable:", name);
_keystore_msg_for_volumes(msg, key_prop, VOLUME_TYPE_PLAIN);
free(msg);
printf("%s: Remove key '%s' [y/N]? ", program_invocation_short_name,
name);
if (!prompt_for_yes(keystore->verbose)) {
warnx("Operation aborted");
rc = -ECANCELED;
goto out;
}
out:
properties_free(key_prop);
return rc;
}
/**
* Removes a key from the keystore
*
* @param[in] keystore the key store
* @param[in] name the name of the key
* @param[in] quiet if true no confirmation prompt is shown
* @param[in] kms_options an array of KMS options specified, or NULL if no
* KMS options have been specified
* @param[in] num_kms_options the number of options in above array
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_remove_key(struct keystore *keystore, const char *name,
bool quiet, struct kms_option *kms_options,
size_t num_kms_options)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct properties *key_props = NULL;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
if (!quiet) {
if (_keystore_prompt_for_remove(keystore, name,
&file_names) != 0)
goto out;
}
key_props = properties_new();
rc = properties_load(key_props, file_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto out;
}
if (_keystore_is_kms_bound_key(key_props, NULL)) {
rc = perform_kms_login(keystore->kms_info, keystore->verbose);
if (rc != 0)
goto out;
rc = remove_kms_key(keystore->kms_info, key_props,
kms_options, num_kms_options,
keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to remove key '%s': %s",
keystore->kms_info->plugin_name, name,
strerror(-rc));
print_last_kms_error(keystore->kms_info);
goto out;
}
}
if (remove(file_names.skey_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to remove '%s': %s",
file_names.skey_filename, strerror(-rc));
goto out;
}
if (remove(file_names.info_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to remove '%s': %s",
file_names.info_filename, strerror(-rc));
}
if (_keystore_reencipher_key_exists(&file_names)) {
if (remove(file_names.renc_filename) != 0) {
rc = -errno;
pr_verbose(keystore, "Failed to remove '%s': %s",
file_names.renc_filename, strerror(-rc));
}
}
pr_verbose(keystore, "Successfully removed key '%s'", name);
out:
_keystore_free_key_filenames(&file_names);
if (key_props != NULL)
properties_free(key_props);
if (rc != 0)
pr_verbose(keystore, "Failed to remove key '%s': %s",
name, strerror(-rc));
return rc;
}
/**
* Processing function for the key display function.
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 if the display is successful, a negative errno value otherwise
*/
static int _keystore_display_key(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct util_rec *rec = (struct util_rec *)private;
u8 *secure_key;
size_t secure_key_size, clear_key_bitsize = 0;
int rc = 0;
secure_key = read_secure_key(file_names->skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL)
return -EIO;
if (secure_key_size < MIN_SECURE_KEY_SIZE) {
pr_verbose(keystore,
"Size of secure key is too small: %lu expected %lu",
secure_key_size, MIN_SECURE_KEY_SIZE);
rc = -EIO;
goto out;
}
get_key_bit_size(secure_key, secure_key_size, &clear_key_bitsize);
_keystore_print_record(rec, name, properties, 0,
file_names->skey_filename, secure_key_size,
is_xts_key(secure_key, secure_key_size),
clear_key_bitsize, 0, 0,
_keystore_reencipher_key_exists(file_names),
NULL);
out:
free(secure_key);
return rc;
}
/**
* Lists keys in the keystore that matches the filters
*
* @param[in] keystore the key store
* @param[in] name_filter the name filter. Can contain wild cards.
* NULL means no name filter.
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* The ':dm-name' part of the volume is optional
* for the volume filter. If not specified, the filter
* checks the volume part only.
* NULL means no volume filter.
* @param[in] apqn_filter the APQN filter. Can contain wild cards, and
* mutliple APQN filters separated by commas.
* NULL means no APQN filter.
* @param[in] volume_type The volume type. NULL means no volume type filter.
* @param[in] key_type The key type. NULL means no key type filter.
* @param[in] local if true, only local keys are listed
* @param[in] kms_bound if true, only KMS-bound keys are listed
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_list_keys(struct keystore *keystore, const char *name_filter,
const char *volume_filter, const char *apqn_filter,
const char *volume_type, const char *key_type,
bool local, bool kms_bound)
{
struct util_rec *rec;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
if (volume_type != NULL &&
!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
return -EINVAL;
}
if (key_type != NULL &&
!_keystore_valid_key_type(key_type)) {
warnx("Invalid key-type specified");
return -EINVAL;
}
rec = _keystore_setup_record(0);
rc = _keystore_process_filtered(keystore, name_filter, volume_filter,
apqn_filter, volume_type, key_type,
local, kms_bound,
_keystore_display_key, rec);
util_rec_free(rec);
if (rc != 0)
pr_verbose(keystore, "Failed to list keys: %s",
strerror(-rc));
else
pr_verbose(keystore, "Successfully listed keys");
return rc;
}
/**
* Executes a command via system().
*
* @param[in] cmd the command to execute
* @param[in] msg_cmd the short command name (for messages)
*
* @returns the exit code of the command execution, or -1 in case of an error
*/
static int _keystore_execute_cmd(const char *cmd,
const char *msg_cmd)
{
int rc;
rc = setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin", 1);
if (rc < 0)
return rc;
rc = system(cmd);
if (WIFEXITED(rc)) {
rc = WEXITSTATUS(rc);
if (rc != 0)
printf("%s exit code: %d\n", msg_cmd, rc);
} else {
rc = -EIO;
warnx("%s terminated abnormally", msg_cmd);
}
return rc;
}
struct crypt_info {
bool execute;
bool batch_mode;
const char *keyfile;
size_t keyfile_offset;
size_t keyfile_size;
size_t tries;
bool open;
bool format;
char **volume_filter;
int (*process_func)(struct keystore *keystore,
const char *volume,
const char *dmname,
const char *cipher_spec,
const char *key_file_name,
size_t key_file_size,
size_t sector_size,
const char *volume_type,
struct crypt_info *info);
};
/**
* Processing function for the cryptsetup function. Builds a cryptsetup command
* line and optionally executes it.
*
* @param[in] keystore the keystore (not used here)
* @param[in] volume the volume to mount
* @param[in] dmname the debice mapper name
* @param[in] cipher_spec the cipher specification
* @param[in] key_file_name the key file name
* @param[in] key_file_size the size of the key file in bytes
* @param[in] sector_size the sector size in bytes or 0 if not specified
* @param[in] volume_type the volume type
* @param[in] info processing info
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_process_cryptsetup(struct keystore *keystore,
const char *volume,
const char *dmname,
const char *cipher_spec,
const char *key_file_name,
size_t key_file_size,
size_t sector_size,
const char *volume_type,
struct crypt_info *info)
{
char *keyfile_opt = NULL, *offset_opt = NULL;
char *size_opt = NULL, *tries_opt = NULL;
char *common_passphrase_options;
size_t common_len;
char temp[100];
int rc = 0;
char *cmd;
sprintf(temp, "--sector-size %lu ", sector_size);
if (info->keyfile) {
util_asprintf(&keyfile_opt, "--key-file '%s' ", info->keyfile);
if (info->keyfile_offset > 0)
util_asprintf(&offset_opt, "--keyfile-offset %lu ",
info->keyfile_offset);
if (info->keyfile_size > 0)
util_asprintf(&size_opt, "--keyfile-size %lu ",
info->keyfile_size);
}
if (info->tries > 0)
util_asprintf(&tries_opt, "--tries %lu ", info->tries);
util_asprintf(&common_passphrase_options, "%s%s%s%s",
keyfile_opt != NULL ? keyfile_opt : "",
offset_opt != NULL ? offset_opt : "",
size_opt != NULL ? size_opt : "",
tries_opt != NULL ? tries_opt : "");
common_len = strlen(common_passphrase_options);
free(keyfile_opt);
free(offset_opt);
free(size_opt);
free(tries_opt);
if (strcasecmp(volume_type, VOLUME_TYPE_PLAIN) == 0) {
if (info->format)
return 0;
util_asprintf(&cmd,
"cryptsetup plainOpen %s%s--key-file '%s' "
"--key-size %lu --cipher %s %s%s %s",
info->batch_mode ? "-q " : "",
keystore->verbose ? "-v " : "", key_file_name,
key_file_size * 8, cipher_spec,
sector_size > 0 ? temp : "", volume, dmname);
if (info->execute) {
printf("Executing: %s\n", cmd);
rc = _keystore_execute_cmd(cmd, "cryptsetup");
} else {
printf("%s\n", cmd);
}
} else if (strcasecmp(volume_type, VOLUME_TYPE_LUKS2) == 0) {
if (info->open) {
util_asprintf(&cmd,
"cryptsetup luksOpen %s%s%s%s %s",
info->batch_mode ? "-q " : "",
keystore->verbose ? "-v " : "",
common_len > 0 ?
common_passphrase_options : "",
volume, dmname);
if (info->execute) {
printf("Executing: %s\n", cmd);
rc = _keystore_execute_cmd(cmd, "cryptsetup");
} else {
printf("%s\n", cmd);
}
} else {
/*
* Use PBKDF2 as key derivation function for LUKS2
* volumes. LUKS2 uses Argon2i as default, but this
* might cause out-of-memory errors when multiple LUKS2
* volumes are opened automatically via /etc/crypttab
*/
util_asprintf(&cmd,
"cryptsetup luksFormat %s%s--type luks2 "
"--master-key-file '%s' --key-size %lu "
"--cipher %s --pbkdf pbkdf2 %s%s%s",
info->batch_mode ? "-q " : "",
keystore->verbose ? "-v " : "",
key_file_name, key_file_size * 8,
cipher_spec, common_len > 0 ?
common_passphrase_options : "",
sector_size > 0 ? temp : "", volume);
if (info->execute) {
printf("Executing: %s\n", cmd);
rc = _keystore_execute_cmd(cmd, "cryptsetup");
} else {
printf("%s\n", cmd);
}
free(cmd);
if (rc != 0)
return rc;
util_asprintf(&cmd,
"zkey-cryptsetup setvp %s %s%s", volume,
common_len > 0 ?
common_passphrase_options : "",
keystore->verbose ? "-V" : "");
if (info->execute) {
printf("Executing: %s\n", cmd);
rc = _keystore_execute_cmd(cmd,
"zkey-cryptsetup");
} else {
printf("%s\n", cmd);
}
}
} else {
return -EINVAL;
}
free(common_passphrase_options);
free(cmd);
return rc;
}
/**
* Processing function for the crypttab function. Builds a crypttab entry
* and prints it.
*
* @param[in] keystore the keystore (not used here)
* @param[in] volume the volume to mount
* @param[in] dmname the debice mapper name
* @param[in] cipher_spec the cipher specification
* @param[in] key_file_name the key file name
* @param[in] key_file_size the size of the key file in bytes
* @param[in] sector_size the sector size in bytes or 0 if not specified
* @param[in] volume_type the volume type
* @param[in] info processing info (not used here)
*
* @returns 0 if successful, a negative errno value otherwise
*/
static int _keystore_process_crypttab(struct keystore *UNUSED(keystore),
const char *volume,
const char *dmname,
const char *cipher_spec,
const char *key_file_name,
size_t key_file_size,
size_t sector_size,
const char *volume_type,
struct crypt_info *info)
{
char temp[1000];
if (strcasecmp(volume_type, VOLUME_TYPE_PLAIN) == 0) {
if (sector_size > 0) {
sprintf(temp,
"WARNING: volume '%s' is using a sector size "
"of %lu. At the time this utility was "
"developed, systemd's support of crypttab did "
"not support to specify a sector size with "
"plain dm-crypt devices. The generated "
"crypttab entry might or might not work, and "
"might need manual adoptions.", volume,
sector_size);
util_print_indented(temp, 0);
}
sprintf(temp, ",sector-size=%lu", sector_size);
printf("%s\t%s\t%s\tplain,cipher=%s,size=%lu%s\n",
dmname, volume, key_file_name, cipher_spec,
key_file_size * 8, sector_size > 0 ? temp : "");
} else if (strcasecmp(volume_type, VOLUME_TYPE_LUKS2) == 0) {
printf("%s\t%s\t%s\tluks", dmname, volume,
info->keyfile != NULL ? info->keyfile : "none");
if (info->keyfile != NULL) {
if (info->keyfile_offset > 0)
printf(",keyfile-offset=%lu",
info->keyfile_offset);
if (info->keyfile_size > 0)
printf(",keyfile-size=%lu", info->keyfile_size);
}
if (info->tries > 0)
printf(",tries=%lu", info->tries);
printf("\n");
} else {
return -EINVAL;
}
return 0;
}
/**
* Builds a cipher specification for cryptsetup/crypttab
*
* @param properties the key properties
* @param is_xts if true, the key is an XTS key
*
* @returns the cipher spec string (must be freed by the caller)
*/
static char *_keystore_build_cipher_spec(struct properties *properties,
bool is_xts)
{
char *cipher_spec = NULL;
char *cipher = NULL;
char *ivmode = NULL;
cipher = properties_get(properties, PROP_NAME_CIPHER);
if (cipher == NULL)
goto out;
ivmode = properties_get(properties, PROP_NAME_IV_MODE);
if (ivmode == NULL)
goto out;
util_asprintf(&cipher_spec, "%s-%s-%s", cipher, is_xts ? "xts" : "cbc",
ivmode);
out:
if (cipher != NULL)
free(cipher);
if (ivmode != NULL)
free(ivmode);
return cipher_spec;
}
/**
* Processing function for the cryptsetup and crypttab functions.
* Extracts the required information and calls the secondary processing function
* contained in struct crypt_info.
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct crypt_info
*
* @returns 0 if the validation is successful, a negative errno value otherwise
*/
static int _keystore_process_crypt(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct crypt_info *info = (struct crypt_info *)private;
char **volume_list = NULL;
char *cipher_spec = NULL;
char *volume_type = NULL;
size_t secure_key_size;
size_t sector_size = 0;
char *volumes = NULL;
u8 *secure_key = NULL;
char *dmname;
char *temp;
int rc = 0;
char *vol;
char *ch;
int i;
secure_key = read_secure_key(file_names->skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL)
return -EIO;
cipher_spec = _keystore_build_cipher_spec(properties,
is_xts_key(secure_key,
secure_key_size));
if (cipher_spec == NULL) {
rc = -EINVAL;
goto out;
}
volumes = properties_get(properties, PROP_NAME_VOLUMES);
if (volumes == NULL)
return -EINVAL;
volume_list = str_list_split(volumes);
temp = properties_get(properties, PROP_NAME_SECTOR_SIZE);
if (temp != NULL) {
util_assert(sscanf(temp, "%lu", §or_size) == 1,
"Internal error: sscanf failed");
free(temp);
}
volume_type = _keystore_get_volume_type(properties);
for (i = 0; volume_list[i] != NULL && rc == 0; i++) {
vol = volume_list[i];
if (_keystore_match_filter(vol, info->volume_filter,
NULL) != 0) {
ch = strchr(vol, ':');
if (ch == NULL) {
warnx("Volume does not contain a dm-name part."
" Key: '%s'", name);
rc = -EINVAL;
break;
}
*ch = '\0';
dmname = ch + 1;
rc = info->process_func(keystore, vol, dmname,
cipher_spec, file_names->skey_filename,
secure_key_size, sector_size,
volume_type, info);
if (rc != 0)
break;
}
}
out:
if (volumes != NULL)
free(volumes);
if (volume_list != NULL)
str_list_free_string_array(volume_list);
if (cipher_spec != NULL)
free(cipher_spec);
if (volume_type != NULL)
free(volume_type);
if (secure_key != NULL)
free(secure_key);
return rc;
}
/**
* Generates cryptsetup commands for one or multiple volumes.
*
* @param[in] keystore the key store
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* The ':dm-name' part of the volume is optional
* for the volume filter. If not specified, the filter
* checks the volume part only.
* @param[in] execute If TRUE the cryptsetup command is executed,
* otherwise it is printed to stdout
* @param[in] volume_type the type of volume to generate cryptsetup cmds for
* @param[in] keyfile If non-NULL, specifies the name of the file to
* read the passphrase from.
* @param[in] keyfile_offset the offset in bytes for reading from keyfile
* @param[in] keyfile_size the size in bytes for reading from keyfile
* @param[in] tries the number of tries for passphrase entry
* @param[in] batch_mode If TRUE, suppress cryptsetup confirmation questions
* @param[in] open If TRUE, generate luksOpen/plainOpen commands
* @param[in] format If TRUE, generate luksFormat commands
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_cryptsetup(struct keystore *keystore, const char *volume_filter,
bool execute, const char *volume_type,
const char *keyfile, size_t keyfile_offset,
size_t keyfile_size, size_t tries, bool batch_mode,
bool open, bool format)
{
struct crypt_info info = { 0 };
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
if (volume_filter == NULL)
volume_filter = "*";
if (volume_type != NULL &&
!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
return -EINVAL;
}
info.execute = execute;
info.open = open;
info.format = format;
info.batch_mode = batch_mode;
info.keyfile = keyfile;
info.keyfile_offset = keyfile_offset;
info.keyfile_size = keyfile_size;
info.tries = tries;
info.volume_filter = str_list_split(volume_filter);
info.process_func = _keystore_process_cryptsetup;
rc = _keystore_process_filtered(keystore, NULL, volume_filter, NULL,
volume_type, NULL, false, false,
_keystore_process_crypt, &info);
str_list_free_string_array(info.volume_filter);
if (rc < 0)
pr_verbose(keystore, "Cryptsetup failed with: %s",
strerror(-rc));
else if (rc > 0)
pr_verbose(keystore, "Cryptsetup failed with: %d", rc);
else
pr_verbose(keystore,
"Successfully generated cryptsetup commands");
return rc;
}
/**
* Generates crypttab entries for one or multiple volumes.
*
* @param[in] keystore the key store
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* The ':dm-name' part of the volume is optional
* for the volume filter. If not specified, the filter
* checks the volume part only.
* @param[in] volume_type the type of volume to generate crypttab entries for
* @param[in] keyfile If non-NULL, specifies the name of the file to
* read the passphrase from.
* @param[in] keyfile_offset the offset in bytes for reading from keyfile
* @param[in] keyfile_size the size in bytes for reading from keyfile
* @param[in] tries the number of tries for passphrase entry
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_crypttab(struct keystore *keystore, const char *volume_filter,
const char *volume_type, const char *keyfile,
size_t keyfile_offset, size_t keyfile_size, size_t tries)
{
struct crypt_info info = { 0 };
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
if (volume_filter == NULL)
volume_filter = "*";
if (volume_type != NULL &&
!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
return -EINVAL;
}
info.keyfile = keyfile;
info.keyfile_offset = keyfile_offset;
info.keyfile_size = keyfile_size;
info.tries = tries;
info.volume_filter = str_list_split(volume_filter);
info.process_func = _keystore_process_crypttab;
rc = _keystore_process_filtered(keystore, NULL, volume_filter, NULL,
volume_type, NULL, false, false,
_keystore_process_crypt, &info);
str_list_free_string_array(info.volume_filter);
if (rc != 0)
pr_verbose(keystore, "Cryptsetup failed with: %s",
strerror(-rc));
else
pr_verbose(keystore, "Successfully generated crypttab entries");
return rc;
}
/**
* Converts a secure keys in the keystore
*
* @param[in] keystore the key store
* @param[in] name the name of the key to convert
* @param[in] key_type the type of the key to convert it to
* @param[in] noapqncheck if true, the specified APQN(s) are not checked for
* existence and type.
* @param[in] pkey_fd the file descriptor of /dev/pkey
* @param[in] lib the external library struct
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_convert_key(struct keystore *keystore, const char *name,
const char *key_type, bool noapqncheck, bool quiet,
int pkey_fd, struct ext_lib *lib)
{
struct key_filenames file_names = { NULL, NULL, NULL };
u8 output_key[2 * MAX_SECURE_KEY_SIZE];
struct properties *properties = NULL;
int rc, min_level, selected = 1;
unsigned int output_key_size;
char *cur_key_type = NULL;
char **apqn_list = NULL;
size_t secure_key_size;
u8 *secure_key = NULL;
u8 mkvp[MKVP_LENGTH];
char *apqns = NULL;
char *temp;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(name != NULL, "Internal error: name is NULL");
rc = _keystore_get_key_filenames(keystore, name, &file_names);
if (rc != 0)
goto out;
rc = _keystore_ensure_keyfiles_exist(&file_names, name);
if (rc != 0)
goto out;
properties = properties_new();
rc = properties_load(properties, file_names.info_filename, 1);
if (rc != 0) {
warnx("Key '%s' does not exist or is invalid", name);
goto out;
}
if (_keystore_is_kms_bound_key(properties, NULL)) {
rc = -EINVAL;
warnx("A KMS-bound key can not be converted");
goto out;
}
cur_key_type = _keystore_get_key_type(properties);
if (strcasecmp(cur_key_type, key_type) == 0) {
warnx("The secure key '%s' is already of type %s", name,
cur_key_type);
rc = 0;
goto out;
}
if (strcasecmp(cur_key_type, KEY_TYPE_CCA_AESDATA) != 0) {
warnx("Only secure keys of type %s can "
"be converted. The secure key '%s' is of type %s",
KEY_TYPE_CCA_AESDATA, name, cur_key_type);
rc = 0;
goto out;
}
secure_key = read_secure_key(file_names.skey_filename,
&secure_key_size, keystore->verbose);
if (secure_key == NULL) {
rc = -ENOENT;
goto out;
}
min_level = get_min_card_level_for_keytype(key_type);
if (min_level < 0) {
warnx("Invalid key-type specified: %s", key_type);
rc = -EINVAL;
goto out;
}
apqns = properties_get(properties, PROP_NAME_APQNS);
if (apqns != NULL)
apqn_list = str_list_split(apqns);
rc = cross_check_apqns(apqns, NULL, min_level,
get_min_fw_version_for_keytype(key_type),
get_card_type_for_keytype(key_type),
true, keystore->verbose);
if (rc == -EINVAL)
goto out;
if (rc != 0 && rc != -ENOTSUP && !noapqncheck) {
warnx("Your master key setup is improper for converting key "
"'%s'", name);
goto out;
}
rc = validate_secure_key(pkey_fd, secure_key, secure_key_size,
NULL, NULL, (const char **)apqn_list,
keystore->verbose);
if (rc != 0)
goto out;
rc = get_master_key_verification_pattern(secure_key, secure_key_size,
mkvp, keystore->verbose);
if (rc)
goto out;
rc = select_cca_adapter_by_mkvp(lib->cca, mkvp, apqns,
FLAG_SEL_CCA_MATCH_CUR_MKVP,
keystore->verbose);
if (rc == -ENOTSUP) {
rc = 0;
selected = 0;
}
if (rc != 0) {
warnx("No APQN found that is suitable for "
"converting the secure AES key '%s'", name);
goto out;
}
if (!quiet) {
util_print_indented("ATTENTION: Converting a secure key is "
"irreversible, and might have an effect "
"on the volumes encrypted with it!", 0);
_keystore_msg_for_volumes("The following volumes are encrypted "
"with this key:", properties, NULL);
printf("%s: Convert key '%s [y/N]'? ",
program_invocation_short_name, name);
if (!prompt_for_yes(keystore->verbose)) {
warnx("Operation aborted");
rc = -ECANCELED;
goto out;
}
}
memset(output_key, 0, sizeof(output_key));
output_key_size = sizeof(output_key);
rc = convert_aes_data_to_cipher_key(lib->cca, secure_key,
secure_key_size, output_key,
&output_key_size,
keystore->verbose);
if (rc != 0) {
warnx("Converting the secure key '%s' from %s to %s has failed",
name, KEY_TYPE_CCA_AESDATA, key_type);
if (!selected)
print_msg_for_cca_envvars("secure AES key");
goto out;
}
rc = restrict_key_export(lib->cca, output_key, output_key_size,
keystore->verbose);
if (rc != 0) {
warnx("Export restricting the converted secure key '%s' has "
"failed", name);
if (!selected)
print_msg_for_cca_envvars("secure AES key");
goto out;
}
rc = properties_set2(properties, PROP_NAME_KEY_TYPE, key_type, true);
if (rc != 0) {
warnx("Invalid characters in key-type");
goto out;
}
rc = properties_save(properties, file_names.info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Failed to write key info file '%s': %s",
file_names.info_filename, strerror(-rc));
goto out;
}
rc = write_secure_key(file_names.skey_filename, output_key,
output_key_size, keystore->verbose);
if (rc != 0)
goto out;
pr_verbose(keystore, "Secure key '%s' was converted successfully",
name);
util_asprintf(&temp, "The following LUKS2 volumes are "
"encrypted with key '%s'. These volumes still contain "
"the secure AES volume key of type CCA-AESDATA. To "
"change the secure AES volume key in the LUKS2 header, "
"run command 'zkey-cryptsetup setkey <device> "
"--master-key-file %s':", name,
file_names.skey_filename);
_keystore_msg_for_volumes(temp, properties, VOLUME_TYPE_LUKS2);
free(temp);
util_asprintf(&temp, "The following plain mode volumes are "
"encrypted with key '%s'. You must adapt the crypttab "
"entries for this volumes and change the key size "
"parameter to 'size=%u' or run command 'zkey crypttab "
"--volumes <device>' for each volume to re-generate the "
"crypttab entries:", name, output_key_size * 8, name);
_keystore_msg_for_volumes(temp, properties, VOLUME_TYPE_PLAIN);
free(temp);
out:
_keystore_free_key_filenames(&file_names);
if (properties != NULL)
properties_free(properties);
if (secure_key != NULL)
free(secure_key);
if (apqns != NULL)
free(apqns);
if (apqn_list != NULL)
str_list_free_string_array(apqn_list);
if (cur_key_type != NULL)
free(cur_key_type);
if (rc != 0)
pr_verbose(keystore, "Failed to convert key '%s': %s",
name, strerror(-rc));
return rc;
}
struct kms_process {
process_key_t process_func;
void *process_private;
};
struct kms_set_prop {
const char *prop_name;
const char *prop_value;
unsigned long num_keys;
};
/**
* Processing function for setting properties of KMS-bound keys
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key (not used here)
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 for success, or a negative errno value in case of an error
*/
static int _keystore_process_kms_key_set_prop(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct kms_set_prop *set_prop = private;
int rc;
pr_verbose(keystore, "Setting property for KMS-bound key '%s'", name);
if (set_prop->prop_value != NULL) {
rc = properties_set(properties, set_prop->prop_name,
set_prop->prop_value);
if (rc != 0) {
pr_verbose(keystore, "Invalid characters in property: "
"%s: %s", set_prop->prop_name,
set_prop->prop_value);
goto out;
}
} else {
rc = properties_remove(properties, set_prop->prop_name);
if (rc != 0 && rc != -ENOENT) {
pr_verbose(keystore, "Failed to remove property: "
"%s: %s", set_prop->prop_name,
strerror(-rc));
goto out;
}
}
rc = properties_save(properties, file_names->info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names->info_filename, strerror(-rc));
goto out;
}
set_prop->num_keys++;
out:
return rc;
}
/**
* Iterates over all keys stored in the keystore. For every key that is bound
* to a KMS plugin the specified property is set to the specified value.
* If value is NULL, then the property is removed from the key.
*
* @param[in] keystore the keystore
* @param[in] key_type the key type. NULL means no key type filter.
* @param[in] prop_name the name of the property to set
* @param[in] prop_value the value of the property to set or NULL if the proerty
* is to be removed.
*
* @returns 0 for success, or a negative errno value in case of an error
*/
int keystore_kms_keys_set_property(struct keystore *keystore,
const char *key_type,
const char *prop_name,
const char *prop_value)
{
struct kms_set_prop set_prop;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(prop_name != NULL, "Internal error: prop_name is NULL");
set_prop.prop_name = prop_name;
set_prop.prop_value = prop_value;
set_prop.num_keys = 0;
rc = _keystore_process_filtered(keystore, NULL, NULL, NULL, NULL,
key_type, false, true,
_keystore_process_kms_key_set_prop,
&set_prop);
if (rc != 0)
pr_verbose(keystore, "Failed to set properties of kms keys: %s",
strerror(-rc));
else
pr_verbose(keystore, "Successfully set properties of %lu kms "
"keys", set_prop.num_keys);
return rc;
}
static const char * const kms_props[] = {
PROP_NAME_KMS,
PROP_NAME_KMS_KEY_ID,
PROP_NAME_KMS_KEY_LABEL,
PROP_NAME_KMS_XTS_KEY1_ID,
PROP_NAME_KMS_XTS_KEY1_LABEL,
PROP_NAME_KMS_XTS_KEY2_ID,
PROP_NAME_KMS_XTS_KEY2_LABEL,
NULL,
};
/**
* Unbinds the key by removing the KMS specific properties
*
* @param[in] keystore the keystore
* @param[in] properties the properties object of the key
*
* @returns 0 for success, or a negative errno value in case of an error
*/
static int _keystore_kms_key_unbind(struct keystore *keystore,
struct properties *properties)
{
int i, rc;
for (i = 0; kms_props[i] != NULL; i++) {
rc = properties_remove(properties, kms_props[i]);
if (rc != 0 && rc != -ENOENT) {
pr_verbose(keystore, "Failed to remove property: "
"%s: %s", kms_props[i], strerror(-rc));
return rc;
}
}
return 0;
}
/**
* Processing function for unbinding of KMS-bound keys
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 for success, or a negative errno value in case of an error
*/
static int _keystore_process_kms_key_unbind(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
unsigned long *num_keys = private;
int rc;
pr_verbose(keystore, "Unbinding KMS-bound key '%s'", name);
rc = _keystore_kms_key_unbind(keystore, properties);
if (rc != 0)
goto out;
rc = properties_save(properties, file_names->info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names->info_filename, strerror(-rc));
goto out;
}
(*num_keys)++;
out:
return rc;
}
/**
* Iterates over all keys stored in the keystore. For every key that is bound
* to a KMS plugin the KMS specific properties are deleted, and thus these keys
* are unbound from the KMS plugin.
*
* @param[in] keystore the keystore
*
* @returns 0 for success, or a negative errno value in case of an error
*/
int keystore_kms_keys_unbind(struct keystore *keystore)
{
unsigned long num_keys = 0;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
rc = _keystore_process_filtered(keystore, NULL, NULL, NULL, NULL,
NULL, false, true,
_keystore_process_kms_key_unbind,
&num_keys);
if (rc != 0)
pr_verbose(keystore, "Failed to unbinds kms keys: %s",
strerror(-rc));
else
pr_verbose(keystore, "Successfully unbound of %lu kms keys",
num_keys);
return rc;
}
struct kms_msg_for_key {
const char *msg;
unsigned long num_keys;
};
/**
* Processing function for issuing a message for KMS-bound keys
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key (not used here)
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 for success, or a negative errno value in case of an error
*/
static int _keystore_process_kms_msg_for_key(struct keystore *UNUSED(keystore),
const char *name,
struct properties *
UNUSED(properties),
struct key_filenames *
UNUSED(file_names),
void *private)
{
struct kms_msg_for_key *msg_for_key = private;
if (msg_for_key->num_keys == 0)
util_print_indented(msg_for_key->msg, 0);
printf(" %s\n", name);
msg_for_key->num_keys++;
return 0;
}
/**
* Iterates over all keys stored in the keystore. Every key that is bound
* to a KMS plugin and has the specified key type is listed together with the
* message. If no KMS-bound keys with the specified key type exist in the
* keystore, then no message is printed, and -ENOENT is returned.
*
* @param[in] keystore the keystore
* @param[in] key_type the key type. NULL means no key type filter.
* @param[in] msg the message to print
*
* @returns 0 for success, or a negative errno value in case of an error.
* -ENOENT if no key macthed
*/
int keystore_msg_for_kms_key(struct keystore *keystore, const char *key_type,
const char *msg)
{
struct kms_msg_for_key msg_for_key;
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
util_assert(msg != NULL, "Internal error: msg is NULL");
msg_for_key.msg = msg;
msg_for_key.num_keys = 0;
rc = _keystore_process_filtered(keystore, NULL, NULL, NULL, NULL,
key_type, false, true,
_keystore_process_kms_msg_for_key,
&msg_for_key);
if (rc != 0)
return rc;
return msg_for_key.num_keys == 0 ? -ENOENT : 0;
}
struct kms_import {
struct keystore *keystore;
bool batch_mode;
bool novolcheck;
unsigned long num_imported;
unsigned long num_skipped;
unsigned long num_failed;
};
/**
* Callback used with the keystore_import_kms_keys() function. Called for each
* key.
*
* @param[in] key1_id the key-ID of the key (1st key of an XTS key)
* @param[in] key1_label the label of the key (1st key of an XTS key)
* @param[in] key2_id the key-ID of the 2nd XTS key, NULL if not XTS
* @param[in] key2_label the label of the 2nd XTS key, NULL if not XTS
* @param[in] xts if true, this is an XTS key pair
* @param[in] name the zkey name of the key
* @param[in] key_type the type of the key (CCA-AESDATA, etc)
* @param[in] key_bits the key size in bits
* @param[in] description the description of the key (can be NULL)
* @param[in] cipher the cipher of the key (can be NULL)
* @param[in] iv_mode the IV-mode of the key (can be NULL)
* @param[in] volumes the associated volumes of the key (can be NULL)
* @param[in] volume_type the volume type of the volume (can be NULL)
* @param[in] sector_size the sector size of the volume (0 means default)
* @param[in] addl_info_argz an argz string containing additional KMS plugin
* specific infos to be displayed, or NULL if none.
* @param[in] addl_info_len length of the argz string in addl_info_argz
* @param[in] private_data the private data pointer
*
* @returns 0 on success, or a negative errno in case of an error.
*/
static int _keystore_process_kms_import(const char *key1_id,
const char *key1_label,
const char *key2_id,
const char *key2_label,
bool xts, const char *name,
const char *UNUSED(key_type),
size_t UNUSED(key_bits),
const char *description,
const char *UNUSED(cipher),
const char *UNUSED(iv_mode),
const char *volumes,
const char *volume_type,
size_t sector_size,
const char *UNUSED(addl_info_argz),
size_t UNUSED(addl_info_len),
void *private_data)
{
struct key_filenames file_names = { NULL, NULL, NULL };
struct kms_import *import_data = private_data;
u8 secure_key[2 * MAX_SECURE_KEY_SIZE];
struct properties *key_props = NULL;
char vp[VERIFICATION_PATTERN_LEN];
const char *key_name = name;
struct keystore *keystore;
size_t alt_name_len = 0;
size_t secure_key_size;
bool fatal_err = false;
char *alt_name = NULL;
const char *key_type;
char *apqns = NULL;
int rc;
keystore = import_data->keystore;
rc = _keystore_get_key_filenames(keystore, key_name, &file_names);
if (rc != 0)
goto out;
check_duplicate_key:
rc = _keystore_ensure_keyfiles_not_exist(&file_names, key_name);
if (rc == -EEXIST) {
if (import_data->batch_mode) {
rc = 1;
goto out;
}
printf("%s: Do you want to enter an alternate name [y/N]? ",
program_invocation_short_name);
if (!prompt_for_yes(keystore->verbose)) {
rc = 1;
goto out;
}
prompt_alt_name:
printf("%s: Alternate name: ", program_invocation_short_name);
rc = getline(&alt_name, &alt_name_len, stdin);
if (rc <= 1) {
rc = 1;
goto out;
}
if (alt_name[strlen(alt_name) - 1] == '\n')
alt_name[strlen(alt_name) - 1] = '\0';
key_name = alt_name;
_keystore_free_key_filenames(&file_names);
rc = _keystore_get_key_filenames(keystore, key_name,
&file_names);
if (rc != 0)
goto prompt_alt_name;
goto check_duplicate_key;
} else if (rc != 0) {
goto out;
}
secure_key_size = sizeof(secure_key);
rc = import_kms_key(keystore->kms_info, key1_id, key2_id, xts, key_name,
secure_key, &secure_key_size, keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to import key '%s': %s",
keystore->kms_info->plugin_name, key_name, strerror(-rc));
print_last_kms_error(keystore->kms_info);
if (rc == -ENOTSUP)
fatal_err = true;
goto out;
}
key_type = get_key_type(secure_key, secure_key_size);
if (key_type == NULL) {
warnx("Key '%s' is not a valid secure key", key_name);
rc = -EINVAL;
goto out;
}
rc = get_kms_apqns_for_key_type(keystore->kms_info, key_type, true,
&apqns, keystore->verbose);
if (rc != 0) {
if (rc == -ENOTSUP)
warnx("Key-type not supported by the KMS plugin '%s'",
keystore->kms_info->plugin_name);
goto out;
}
pr_verbose(keystore, "APQNs for keytype %s: '%s'", key_type, apqns);
rc = _keystore_create_info_props(keystore, key_name, description,
volumes, apqns, false,
import_data->novolcheck,
sector_size, volume_type, key_type,
keystore->kms_info->plugin_name,
&key_props);
if (rc != 0)
goto out;
rc = properties_set(key_props, xts ? PROP_NAME_KMS_XTS_KEY1_ID :
PROP_NAME_KMS_KEY_ID, key1_id);
if (rc != 0) {
pr_verbose(keystore, "Failed to set key id of key #1: %s",
strerror(-rc));
goto out;
}
rc = properties_set(key_props, xts ? PROP_NAME_KMS_XTS_KEY1_LABEL :
PROP_NAME_KMS_KEY_LABEL, key1_label);
if (rc != 0) {
pr_verbose(keystore, "Failed to set key label of key #1: %s",
strerror(-rc));
goto out;
}
if (xts) {
rc = properties_set(key_props, PROP_NAME_KMS_XTS_KEY2_ID,
key2_id);
if (rc != 0) {
pr_verbose(keystore, "Failed to set key id of key #2: "
"%s", strerror(-rc));
goto out;
}
rc = properties_set(key_props, PROP_NAME_KMS_XTS_KEY2_LABEL,
key2_label);
if (rc != 0) {
pr_verbose(keystore, "Failed to set key label of key "
"#2: %s", strerror(-rc));
goto out;
}
}
rc = write_secure_key(file_names.skey_filename, secure_key,
secure_key_size, keystore->verbose);
if (rc != 0)
goto out;
rc = _keystore_set_file_permission(keystore, file_names.skey_filename);
if (rc != 0)
goto out_remove;
rc = generate_key_verification_pattern(secure_key, secure_key_size,
vp, sizeof(vp),
keystore->verbose);
if (rc != 0) {
warnx("Failed to generate the key verification pattern: %s",
strerror(-rc));
warnx("Make sure that kernel module 'paes_s390' is loaded and "
"that the 'paes' cipher is available");
fatal_err = true;
goto out_remove;
}
rc = properties_set(key_props, PROP_NAME_KEY_VP, vp);
if (rc != 0) {
pr_verbose(keystore, "Failed to set verification pattern of "
"key: %s", strerror(-rc));
goto out_remove;
}
rc = properties_save(key_props, file_names.info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names.info_filename, strerror(-rc));
goto out;
}
rc = _keystore_set_file_permission(keystore, file_names.info_filename);
if (rc != 0) {
remove(file_names.info_filename);
goto out_remove;
}
out_remove:
if (rc != 0) {
remove(file_names.skey_filename);
remove(file_names.info_filename);
}
out:
if (rc == 0) {
printf("Successfully imported key '%s'\n", key_name);
import_data->num_imported++;
} else if (rc < 0) {
warnx("Failed to import key '%s': %s", key_name, strerror(-rc));
import_data->num_failed++;
} else {
warnx("Skipping key '%s'", key_name);
import_data->num_skipped++;
}
_keystore_free_key_filenames(&file_names);
if (alt_name != NULL)
free(alt_name);
if (apqns != NULL)
free(apqns);
if (key_props != NULL)
properties_free(key_props);
return fatal_err ? rc : 0;
}
/**
* Imports secure keys from the KMS and adds it to the key store
*
* @param[in] keystore the key store
* @param[in] label_filter the KMS label filter. Can contain wild cards.
* NULL means no name filter.
* @param[in] name_filter the name filter. Can contain wild cards.
* NULL means no name filter.
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* If the filter does not contain the ':dm-name'
* part, then the volumes are matched without the
* dm-name part. If the filter contains the
* ':dm-name' part, then the filter is matched
* including the dm-name part.
* NULL means no volume filter.
* @param[in] volume_type If not NULL, specifies the volume type.
* @param[in] kms_options an array of KMS options specified, or NULL if no
* KMS options have been specified
* @param[in] num_kms_options the number of options in above array
* @param[in] batch_mode if true, suppress alternate name prompts if a key
* with an already existing name is to be imported.
* @param[in] novolcheck if true, do not check the associated volumes for
* existence and duplicate use
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_import_kms_keys(struct keystore *keystore,
const char *label_filter,
const char *name_filter,
const char *volume_filter,
const char *volume_type,
struct kms_option *kms_options,
size_t num_kms_options,
bool batch_mode, bool novolcheck)
{
struct kms_import import_data = { 0 };
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
if (keystore->kms_info->plugin_lib == NULL) {
warnx("The repository is not bound to a KMS plugin");
return -ENOENT;
}
if (volume_type != NULL &&
!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
return -EINVAL;
}
import_data.keystore = keystore;
import_data.batch_mode = batch_mode;
import_data.novolcheck = novolcheck;
import_data.num_imported = 0;
import_data.num_skipped = 0;
import_data.num_failed = 0;
rc = process_kms_keys(keystore->kms_info, label_filter, name_filter,
volume_filter, volume_type,
kms_options, num_kms_options,
_keystore_process_kms_import, &import_data,
keystore->verbose);
if (rc != 0) {
pr_verbose(keystore, "Failed to import kms keys: %s",
strerror(-rc));
} else {
printf("%lu keys imported, %lu keys skipped, %lu keys "
"failed to import\n",
import_data.num_imported, import_data.num_skipped,
import_data.num_failed);
if (import_data.num_failed > 0)
rc = -EIO;
}
return rc;
}
struct kms_refresh {
bool refresh_properties;
bool novolcheck;
unsigned long num_refreshed;
unsigned long num_failed;
};
/**
* Processing function for the key refresh function.
*
* @param[in] keystore the keystore
* @param[in] name the name of the key
* @param[in] properties the properties object of the key
* @param[in] file_names the file names used by this key
* @param[in] private private data: struct reencipher_info
*
* @returns 0 if the display is successful, a negative errno value otherwise
*/
static int _keystore_refresh_kms_key(struct keystore *keystore,
const char *name,
struct properties *properties,
struct key_filenames *file_names,
void *private)
{
struct volume_check vol_check = { .keystore = keystore, .name = name,
.set = 1, .nocheck = 0 };
char *description = NULL, *cipher = NULL, *iv_mode = NULL;
struct kms_refresh *refresh_data = private;
char *volumes = NULL, *volume_type = NULL;
ssize_t sector_size = -1;
bool fatal_err = false;
char sect_size[30];
char *msg;
int rc;
vol_check.nocheck = refresh_data->novolcheck;
rc = refresh_kms_key(keystore->kms_info, properties,
&description, &cipher, &iv_mode, &volumes,
&volume_type, §or_size,
file_names->skey_filename, keystore->verbose);
if (rc != 0) {
warnx("KMS plugin '%s' failed to refresh key '%s': %s",
keystore->kms_info->plugin_name, name, strerror(-rc));
print_last_kms_error(keystore->kms_info);
if (rc == -ENOTSUP)
fatal_err = true;
goto out;
}
if (!refresh_data->refresh_properties)
goto save_props;
if (description != NULL) {
rc = properties_set(properties, PROP_NAME_DESCRIPTION,
description);
if (rc != 0) {
warnx("Invalid characters in description");
goto out;
}
}
if (volumes != NULL) {
rc = _keystore_change_association(properties, PROP_NAME_VOLUMES,
volumes, "volume",
_keystore_volume_check,
&vol_check);
if (rc != 0)
goto out;
}
if (sector_size >= 0) {
if (!_keystore_valid_sector_size(sector_size)) {
warnx("Invalid sector-size specified");
rc = -EINVAL;
goto out;
}
sprintf(sect_size, "%lu", sector_size);
rc = properties_set(properties, PROP_NAME_SECTOR_SIZE,
sect_size);
if (rc != 0) {
warnx("Invalid characters in sector-size");
goto out;
}
}
if (volume_type != NULL) {
if (!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
rc = -EINVAL;
goto out;
}
rc = properties_set2(properties, PROP_NAME_VOLUME_TYPE,
volume_type, true);
if (rc != 0) {
warnx("Invalid characters in volume-type");
goto out;
}
}
save_props:
rc = _keystore_set_timestamp_property(properties,
PROP_NAME_CHANGE_TIME);
if (rc != 0) {
warnx("Failed to set the update timestamp property");
goto out;
}
rc = properties_save(properties, file_names->info_filename, 1);
if (rc != 0) {
pr_verbose(keystore,
"Key info file '%s' could not be written: %s",
file_names->info_filename, strerror(-rc));
goto out;
}
out:
if (rc == 0) {
printf("Successfully refreshed key '%s'\n", name);
refresh_data->num_refreshed++;
util_asprintf(&msg, "The following LUKS2 volumes are "
"encrypted with key '%s'. To update the secure "
"AES volume key in the LUKS2 header, run command "
"'zkey-cryptsetup setkey <device> "
"--master-key-file %s':", name,
file_names->skey_filename);
_keystore_msg_for_volumes(msg, properties, VOLUME_TYPE_LUKS2);
free(msg);
} else {
warnx("Failed to refresh key '%s': %s", name, strerror(-rc));
refresh_data->num_failed++;
}
if (description != NULL)
free(description);
if (cipher != NULL)
free(cipher);
if (iv_mode != NULL)
free(iv_mode);
if (volumes != NULL)
free(volumes);
if (volume_type != NULL)
free(volume_type);
return fatal_err ? rc : 0;
}
/**
* Refreshes secure KMS-bound secure key and updates them from the KMS
*
* @param[in] keystore the key store
* @param[in] name_filter the name filter. Can contain wild cards.
* NULL means no name filter.
* @param[in] volume_filter the volume filter. Can contain wild cards, and
* mutliple volume filters separated by commas.
* If the filter does not contain the ':dm-name'
* part, then the volumes are matched without the
* dm-name part. If the filter contains the
* ':dm-name' part, then the filter is matched
* including the dm-name part.
* NULL means no volume filter.
* @param[in] volume_type If not NULL, specifies the volume type.
* @param[in] key_type The key type. NULL means no key type filter.
* @param[in] refresh_properties if true, also refresh the key's properties
* @param[in] novolcheck if true, do not check the associated volumes for
* existence and duplicate use
*
* @returns 0 for success or a negative errno in case of an error
*/
int keystore_refresh_kms_keys(struct keystore *keystore,
const char *name_filter,
const char *volume_filter,
const char *volume_type, const char *key_type,
bool refresh_properties, bool novolcheck)
{
struct kms_refresh refresh_data = { 0 };
int rc;
util_assert(keystore != NULL, "Internal error: keystore is NULL");
if (keystore->kms_info->plugin_lib == NULL) {
warnx("The repository is not bound to a KMS plugin");
return -ENOENT;
}
if (volume_type != NULL &&
!_keystore_valid_volume_type(volume_type)) {
warnx("Invalid volume-type specified");
return -EINVAL;
}
if (key_type != NULL &&
!_keystore_valid_key_type(key_type)) {
warnx("Invalid key-type specified");
return -EINVAL;
}
refresh_data.refresh_properties = refresh_properties;
refresh_data.novolcheck = novolcheck;
refresh_data.num_refreshed = 0;
refresh_data.num_failed = 0;
rc = _keystore_process_filtered(keystore, name_filter, volume_filter,
NULL, volume_type, key_type, false,
true, _keystore_refresh_kms_key,
&refresh_data);
if (rc != 0) {
pr_verbose(keystore, "Failed to refresh kms keys: %s",
strerror(-rc));
} else {
printf("%lu keys refreshed, %lu keys failed to refresh\n",
refresh_data.num_refreshed, refresh_data.num_failed);
if (refresh_data.num_failed > 0)
rc = -EIO;
}
return rc;
}
/**
* Frees a keystore object
*
* @param[in] keystore the key store
*/
void keystore_free(struct keystore *keystore)
{
util_assert(keystore != NULL, "Internal error: keystore is NULL");
_keystore_unlock_repository(keystore);
free(keystore->directory);
free(keystore);
}
|