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
//! Keys, their associated signatures, and some useful methods.
//!
//! A [`KeyAmalgamation`] is similar to a [`ComponentAmalgamation`],
//! but a `KeyAmalgamation` includes some additional functionality
//! that is needed to correctly implement a [`Key`] component's
//! semantics. In particular, unlike other components where the
//! binding signature stores the component's meta-data, a Primary Key
//! doesn't have a binding signature (it is the thing that other
//! components are bound to!), and, as a consequence, the associated
//! meta-data is stored elsewhere.
//!
//! Unfortunately, a primary Key's meta-data is usually not stored on
//! a direct key signature, which would be convenient as it is located
//! at the same place as a binding signature would be, but on the
//! primary User ID's binding signature. This requires some
//! acrobatics on the implementation side to realize the correct
//! semantics. In particular, a `Key` needs to memorize its role
//! (i.e., whether it is a primary key or a subkey) in order to know
//! whether to consider its own self signatures or the primary User
//! ID's self signatures when looking for its meta-data.
//!
//! Ideally, a `KeyAmalgamation`'s role would be encoded in its type.
//! This increases safety, and reduces the run-time overhead.
//! However, we want [`Cert::keys`] to return an iterator over all
//! keys; we don't want the user to have to specially handle the
//! primary key when that fact is not relevant. This means that
//! `Cert::keys` has to erase the returned `Key`s' roles: all items in
//! an iterator must have the same type. To support this, we have to
//! keep track of a `KeyAmalgamation`'s role at run-time.
//!
//! But, just because we need to erase a `KeyAmalgamation`'s role to
//! implement `Cert::keys` doesn't mean that we have to always erase
//! it. To achieve this, we use three data types:
//! [`PrimaryKeyAmalgamation`], [`SubordinateKeyAmalgamation`], and
//! [`ErasedKeyAmalgamation`]. The first two encode the role
//! information in their type, and the last one stores it at run time.
//! We provide conversion functions to convert the static type
//! information into dynamic type information, and vice versa.
//!
//! Note: `KeyBundle`s and `KeyAmalgamation`s have a notable
//! difference: whereas a `KeyBundle`'s role is a marker, a
//! `KeyAmalgamation`'s role determines its semantics. A consequence
//! of this is that it is not possible to convert a
//! `PrimaryKeyAmalgamation` into a `SubordinateAmalgamation`s, or
//! vice versa even though we support changing a `KeyBundle`'s role:
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # use std::convert::TryInto;
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::cert::prelude::*;
//! # use openpgp::packet::prelude::*;
//! # let (cert, _) = CertBuilder::new()
//! # .add_userid("Alice")
//! # .add_signing_subkey()
//! # .add_transport_encryption_subkey()
//! # .generate()?;
//! // This works:
//! cert.primary_key().bundle().role_as_subordinate();
//!
//! // But this doesn't:
//! let ka: ErasedKeyAmalgamation<_> = cert.keys().nth(0).expect("primary key");
//! let ka: openpgp::Result<SubordinateKeyAmalgamation<key::PublicParts>> = ka.try_into();
//! assert!(ka.is_err());
//! # Ok(()) }
//! ```
//!
//! The use of the prefix `Erased` instead of `Unspecified`
//! (cf. [`KeyRole::UnspecifiedRole`]) emphasizes this.
//!
//! # Selecting Keys
//!
//! It is essential to choose the right keys, and to make sure that
//! they are appropriate. Below, we present some guidelines for the most
//! common situations.
//!
//! ## Encrypting and Signing Messages
//!
//! As a general rule of thumb, when encrypting or signing a message,
//! you want to use keys that are alive, not revoked, and have the
//! appropriate capabilities right now. For example, the following
//! code shows how to find a key, which is appropriate for signing a
//! message:
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use openpgp::types::RevocationStatus;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! # let (cert, _) =
//! # CertBuilder::general_purpose(None, Some("alice@example.org"))
//! # .generate()?;
//! # let mut i = 0;
//! let p = &StandardPolicy::new();
//!
//! let cert = cert.with_policy(p, None)?;
//!
//! if let RevocationStatus::Revoked(_) = cert.revocation_status() {
//! // The certificate is revoked, don't use any keys from it.
//! # unreachable!();
//! } else if let Err(_) = cert.alive() {
//! // The certificate is not alive, don't use any keys from it.
//! # unreachable!();
//! } else {
//! for ka in cert.keys() {
//! if let RevocationStatus::Revoked(_) = ka.revocation_status() {
//! // The key is revoked.
//! # unreachable!();
//! } else if let Err(_) = ka.alive() {
//! // The key is not alive.
//! # unreachable!();
//! } else if ! ka.for_signing() {
//! // The key is not signing capable.
//! } else {
//! // Use it!
//! # i += 1;
//! }
//! }
//! }
//! # assert_eq!(i, 1);
//! # Ok(())
//! # }
//! ```
//!
//! ## Verifying a Message
//!
//! When verifying a message, you only want to use keys that were
//! alive, not revoked, and signing capable *when the message was
//! signed*. These are the keys that the signer would have used, and
//! they reflect the signer's policy when they made the signature.
//! (See the [`Policy` discussion] for an explanation.)
//!
//! For version 4 Signature packets, the `Signature Creation Time`
//! subpacket indicates when the signature was allegedly created. For
//! the purpose of finding the key to verify the signature, this time
//! stamp should be trusted: if the key is authenticated and the
//! signature is valid, then the time stamp is valid; if the signature
//! is not valid, then forging the time stamp won't help an attacker.
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use openpgp::types::RevocationStatus;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! let p = &StandardPolicy::new();
//!
//! # let (cert, _) =
//! # CertBuilder::general_purpose(None, Some("alice@example.org"))
//! # .generate()?;
//! # let timestamp = None;
//! # let issuer = cert.with_policy(p, None)?.keys()
//! # .for_signing().nth(0).unwrap().fingerprint();
//! # let mut i = 0;
//! let cert = cert.with_policy(p, timestamp)?;
//! if let RevocationStatus::Revoked(_) = cert.revocation_status() {
//! // The certificate is revoked, don't use any keys from it.
//! # unreachable!();
//! } else if let Err(_) = cert.alive() {
//! // The certificate is not alive, don't use any keys from it.
//! # unreachable!();
//! } else {
//! for ka in cert.keys().key_handle(issuer) {
//! if let RevocationStatus::Revoked(_) = ka.revocation_status() {
//! // The key is revoked, don't use it!
//! # unreachable!();
//! } else if let Err(_) = ka.alive() {
//! // The key was not alive when the signature was made!
//! // Something fishy is going on.
//! # unreachable!();
//! } else if ! ka.for_signing() {
//! // The key was not signing capable! Better be safe
//! // than sorry.
//! # unreachable!();
//! } else {
//! // Try verifying the message with this key.
//! # i += 1;
//! }
//! }
//! }
//! # assert_eq!(i, 1);
//! # Ok(())
//! # }
//! ```
//!
//! ## Decrypting a Message
//!
//! When decrypting a message, it seems like one ought to only use keys
//! that were alive, not revoked, and encryption-capable when the
//! message was encrypted. Unfortunately, we don't know when a
//! message was encrypted. But anyway, due to the slow propagation of
//! revocation certificates, we can't assume that senders won't
//! mistakenly use a revoked key.
//!
//! However, wanting to decrypt a message encrypted using an expired
//! or revoked key is reasonable. If someone is trying to decrypt a
//! message using an expired key, then they are the certificate
//! holder, and probably attempting to access archived data using a
//! key that they themselves revoked! We don't want to prevent that.
//!
//! We do, however, want to check whether a key is really encryption
//! capable. [This discussion] explains why using a signing key to
//! decrypt a message can be dangerous. Since we need a binding
//! signature to determine this, but we don't have the time that the
//! message was encrypted, we need a workaround. One approach would
//! be to check whether the key is encryption capable now. Since a
//! key's key flags don't typically change, this will correctly filter
//! out keys that are not encryption capable. But, it will skip keys
//! whose self signature has expired. But that is not a problem
//! either: no one sets self signatures to expire; if anything, they
//! set keys to expire. Thus, this will not result in incorrectly
//! failing to decrypt messages in practice, and is a reasonable
//! approach.
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! let p = &StandardPolicy::new();
//!
//! # let (cert, _) =
//! # CertBuilder::general_purpose(None, Some("alice@example.org"))
//! # .generate()?;
//! let decryption_keys = cert.keys().with_policy(p, None)
//! .for_storage_encryption().for_transport_encryption()
//! .collect::<Vec<_>>();
//! # Ok(())
//! # }
//! ```
//!
//! [`ComponentAmalgamation`]: super::ComponentAmalgamation
//! [`Key`]: crate::packet::key
//! [`Cert::keys`]: super::super::Cert::keys()
//! [`PrimaryKeyAmalgamation`]: super::PrimaryKeyAmalgamation
//! [`SubordinateKeyAmalgamation`]: super::SubordinateKeyAmalgamation
//! [`ErasedKeyAmalgamation`]: super::ErasedKeyAmalgamation
//! [`KeyRole::UnspecifiedRole`]: crate::packet::key::KeyRole
//! [`Policy` discussion]: super
//! [This discussion]: https://crypto.stackexchange.com/a/12138
use std::time;
use std::time::SystemTime;
use std::ops::Deref;
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::convert::TryInto;
use anyhow::Context;
use crate::{
Cert,
cert::bundle::KeyBundle,
cert::amalgamation::{
ComponentAmalgamation,
key::signature::subpacket::SubpacketValue,
ValidAmalgamation,
ValidateAmalgamation,
},
cert::ValidCert,
crypto::Signer,
Error,
packet::Key,
packet::key,
packet::Signature,
packet::signature,
packet::signature::subpacket::SubpacketTag,
policy::Policy,
Result,
seal,
types::{
KeyFlags,
RevocationKey,
RevocationStatus,
SignatureType,
},
};
mod iter;
pub use iter::{
KeyAmalgamationIter,
ValidKeyAmalgamationIter,
};
/// Whether the key is a primary key.
///
/// This trait is an implementation detail. It exists so that we can
/// have a blanket implementation of [`ValidAmalgamation`] for
/// [`ValidKeyAmalgamation`], for instance, even though we only have
/// specialized implementations of `PrimaryKey`.
///
/// [`ValidAmalgamation`]: super::ValidAmalgamation
///
/// # Sealed trait
///
/// This trait is [sealed] and cannot be implemented for types outside this crate.
/// Therefore it can be extended in a non-breaking way.
/// If you want to implement the trait inside the crate
/// you also need to implement the `seal::Sealed` marker trait.
///
/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
pub trait PrimaryKey<'a, P, R>: seal::Sealed
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
{
/// Returns whether the key amalgamation is a primary key
/// amalgamation.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// // This works if the type is concrete:
/// let ka: PrimaryKeyAmalgamation<_> = cert.primary_key();
/// assert!(ka.primary());
///
/// // Or if it has been erased:
/// for (i, ka) in cert.keys().enumerate() {
/// let ka: ErasedKeyAmalgamation<_> = ka;
/// if i == 0 {
/// // The primary key is always the first key returned by
/// // `Cert::keys`.
/// assert!(ka.primary());
/// } else {
/// // The rest are subkeys.
/// assert!(! ka.primary());
/// }
/// }
/// # Ok(()) }
/// ```
fn primary(&self) -> bool;
}
/// A key, and its associated data, and useful methods.
///
/// A `KeyAmalgamation` is like a [`ComponentAmalgamation`], but
/// specialized for keys. Due to the requirement to keep track of the
/// key's role when it is erased ([see the module's documentation] for
/// more details), this is a different data structure rather than a
/// specialized type alias.
///
/// Generally, you won't use this type directly, but instead use
/// [`PrimaryKeyAmalgamation`], [`SubordinateKeyAmalgamation`], or
/// [`ErasedKeyAmalgamation`].
///
/// A `KeyAmalgamation` is returned by [`Cert::primary_key`], and
/// [`Cert::keys`].
///
/// `KeyAmalgamation` implements [`ValidateAmalgamation`], which
/// allows you to turn a `KeyAmalgamation` into a
/// [`ValidKeyAmalgamation`] using [`KeyAmalgamation::with_policy`].
///
/// # Examples
///
/// Iterating over all keys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// for ka in cert.keys() {
/// let ka: ErasedKeyAmalgamation<_> = ka;
/// }
/// # Ok(())
/// # }
/// ```
///
/// Getting the primary key:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// let ka: PrimaryKeyAmalgamation<_> = cert.primary_key();
/// # Ok(())
/// # }
/// ```
///
/// Iterating over just the subkeys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// // We can skip the primary key (it's always first):
/// for ka in cert.keys().skip(1) {
/// let ka: ErasedKeyAmalgamation<_> = ka;
/// }
///
/// // Or use `subkeys`, which returns a more accurate type:
/// for ka in cert.keys().subkeys() {
/// let ka: SubordinateKeyAmalgamation<_> = ka;
/// }
/// # Ok(())
/// # }
/// ```
///
/// [`ComponentAmalgamation`]: super::ComponentAmalgamation
/// [see the module's documentation]: self
/// [`Cert::primary_key`]: crate::cert::Cert::primary_key()
/// [`Cert::keys`]: crate::cert::Cert::keys()
/// [`ValidateAmalgamation`]: super::ValidateAmalgamation
/// [`KeyAmalgamation::with_policy`]: super::ValidateAmalgamation::with_policy()
#[derive(Debug)]
pub struct KeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
{
ca: ComponentAmalgamation<'a, Key<P, R>>,
primary: R2,
}
assert_send_and_sync!(KeyAmalgamation<'_, P, R, R2>
where P: key::KeyParts,
R: key::KeyRole,
R2,
);
// derive(Clone) doesn't work with generic parameters that don't
// implement clone. But, we don't need to require that C implements
// Clone, because we're not cloning C, just the reference.
//
// See: https://github.com/rust-lang/rust/issues/26925
impl<'a, P, R, R2> Clone for KeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
{
fn clone(&self) -> Self {
Self {
ca: self.ca.clone(),
primary: self.primary,
}
}
}
/// A primary key amalgamation.
///
/// A specialized version of [`KeyAmalgamation`].
///
pub type PrimaryKeyAmalgamation<'a, P>
= KeyAmalgamation<'a, P, key::PrimaryRole, ()>;
/// A subordinate key amalgamation.
///
/// A specialized version of [`KeyAmalgamation`].
///
pub type SubordinateKeyAmalgamation<'a, P>
= KeyAmalgamation<'a, P, key::SubordinateRole, ()>;
/// An amalgamation whose role is not known at compile time.
///
/// A specialized version of [`KeyAmalgamation`].
///
/// Unlike a [`Key`] or a [`KeyBundle`] with an unspecified role, an
/// `ErasedKeyAmalgamation` remembers its role; it is just not exposed
/// to the type system. For details, see the [module-level
/// documentation].
///
/// [`Key`]: crate::packet::key
/// [`KeyBundle`]: super::super::bundle
/// [module-level documentation]: self
pub type ErasedKeyAmalgamation<'a, P>
= KeyAmalgamation<'a, P, key::UnspecifiedRole, bool>;
impl<'a, P, R, R2> Deref for KeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
{
type Target = ComponentAmalgamation<'a, Key<P, R>>;
fn deref(&self) -> &Self::Target {
&self.ca
}
}
impl<'a, P> seal::Sealed
for PrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::PrimaryRole>>
for PrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = ValidPrimaryKeyAmalgamation<'a, P>;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
-> Result<Self::V>
where T: Into<Option<time::SystemTime>>
{
let ka : ErasedKeyAmalgamation<P> = self.into();
Ok(ka.with_policy(policy, time)?
.try_into().expect("conversion is symmetric"))
}
}
impl<'a, P> seal::Sealed
for SubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::SubordinateRole>>
for SubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = ValidSubordinateKeyAmalgamation<'a, P>;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
-> Result<Self::V>
where T: Into<Option<time::SystemTime>>
{
let ka : ErasedKeyAmalgamation<P> = self.into();
Ok(ka.with_policy(policy, time)?
.try_into().expect("conversion is symmetric"))
}
}
impl<'a, P> seal::Sealed
for ErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::UnspecifiedRole>>
for ErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = ValidErasedKeyAmalgamation<'a, P>;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
-> Result<Self::V>
where T: Into<Option<time::SystemTime>>
{
let time = time.into().unwrap_or_else(crate::now);
// We need to make sure the certificate is okay. This means
// checking the primary key. But, be careful: we don't need
// to double check.
if ! self.primary() {
let pka = PrimaryKeyAmalgamation::new(self.cert());
pka.with_policy(policy, time).context("primary key")?;
}
let binding_signature = self.binding_signature(policy, time)?;
let cert = self.ca.cert();
let vka = ValidErasedKeyAmalgamation {
ka: KeyAmalgamation {
ca: self.ca.parts_into_public(),
primary: self.primary,
},
// We need some black magic to avoid infinite
// recursion: a ValidCert must be valid for the
// specified policy and reference time. A ValidCert
// is consider valid if the primary key is valid.
// ValidCert::with_policy checks that by calling this
// function. So, if we call ValidCert::with_policy
// here we'll recurse infinitely.
//
// But, hope is not lost! We know that if we get
// here, we've already checked that the primary key is
// valid (see above), or that we're in the process of
// evaluating the primary key's validity and we just
// need to check the user's policy. So, it is safe to
// create a ValidCert from scratch.
cert: ValidCert {
cert,
policy,
time,
},
binding_signature
};
policy.key(&vka)?;
Ok(ValidErasedKeyAmalgamation {
ka: KeyAmalgamation {
ca: P::convert_key_amalgamation(
vka.ka.ca.parts_into_unspecified()).expect("roundtrip"),
primary: vka.ka.primary,
},
cert: vka.cert,
binding_signature,
})
}
}
impl<'a, P> PrimaryKey<'a, P, key::PrimaryRole>
for PrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
true
}
}
impl<'a, P> PrimaryKey<'a, P, key::SubordinateRole>
for SubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
false
}
}
impl<'a, P> PrimaryKey<'a, P, key::UnspecifiedRole>
for ErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
self.primary
}
}
impl<'a, P: 'a + key::KeyParts> From<PrimaryKeyAmalgamation<'a, P>>
for ErasedKeyAmalgamation<'a, P>
{
fn from(ka: PrimaryKeyAmalgamation<'a, P>) -> Self {
ErasedKeyAmalgamation {
ca: ka.ca.role_into_unspecified(),
primary: true,
}
}
}
impl<'a, P: 'a + key::KeyParts> From<SubordinateKeyAmalgamation<'a, P>>
for ErasedKeyAmalgamation<'a, P>
{
fn from(ka: SubordinateKeyAmalgamation<'a, P>) -> Self {
ErasedKeyAmalgamation {
ca: ka.ca.role_into_unspecified(),
primary: false,
}
}
}
// We can infallibly convert part X to part Y for everything but
// Public -> Secret and Unspecified -> Secret.
macro_rules! impl_conversion {
($s:ident, $primary:expr, $p1:path, $p2:path) => {
impl<'a> From<$s<'a, $p1>>
for ErasedKeyAmalgamation<'a, $p2>
{
fn from(ka: $s<'a, $p1>) -> Self {
ErasedKeyAmalgamation {
ca: ka.ca.into(),
primary: $primary,
}
}
}
}
}
impl_conversion!(PrimaryKeyAmalgamation, true,
key::SecretParts, key::PublicParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
key::SecretParts, key::UnspecifiedParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
key::PublicParts, key::UnspecifiedParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
key::UnspecifiedParts, key::PublicParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
key::SecretParts, key::PublicParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
key::SecretParts, key::UnspecifiedParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
key::PublicParts, key::UnspecifiedParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
key::UnspecifiedParts, key::PublicParts);
impl<'a, P, P2> TryFrom<ErasedKeyAmalgamation<'a, P>>
for PrimaryKeyAmalgamation<'a, P2>
where P: 'a + key::KeyParts,
P2: 'a + key::KeyParts,
{
type Error = anyhow::Error;
fn try_from(ka: ErasedKeyAmalgamation<'a, P>) -> Result<Self> {
if ka.primary {
Ok(Self {
ca: P2::convert_key_amalgamation(
ka.ca.role_into_primary().parts_into_unspecified())?,
primary: (),
})
} else {
Err(Error::InvalidArgument(
"can't convert a SubordinateKeyAmalgamation \
to a PrimaryKeyAmalgamation".into()).into())
}
}
}
impl<'a, P, P2> TryFrom<ErasedKeyAmalgamation<'a, P>>
for SubordinateKeyAmalgamation<'a, P2>
where P: 'a + key::KeyParts,
P2: 'a + key::KeyParts,
{
type Error = anyhow::Error;
fn try_from(ka: ErasedKeyAmalgamation<'a, P>) -> Result<Self> {
if ka.primary {
Err(Error::InvalidArgument(
"can't convert a PrimaryKeyAmalgamation \
to a SubordinateKeyAmalgamation".into()).into())
} else {
Ok(Self {
ca: P2::convert_key_amalgamation(
ka.ca.role_into_subordinate().parts_into_unspecified())?,
primary: (),
})
}
}
}
impl<'a> PrimaryKeyAmalgamation<'a, key::PublicParts> {
pub(crate) fn new(cert: &'a Cert) -> Self {
PrimaryKeyAmalgamation {
ca: ComponentAmalgamation::new(cert, &cert.primary),
primary: (),
}
}
}
impl<'a, P: 'a + key::KeyParts> SubordinateKeyAmalgamation<'a, P> {
pub(crate) fn new(
cert: &'a Cert, bundle: &'a KeyBundle<P, key::SubordinateRole>)
-> Self
{
SubordinateKeyAmalgamation {
ca: ComponentAmalgamation::new(cert, bundle),
primary: (),
}
}
}
impl<'a, P: 'a + key::KeyParts> ErasedKeyAmalgamation<'a, P> {
/// Returns the key's binding signature as of the reference time,
/// if any.
///
/// Note: this function is not exported. Users of this interface
/// should instead do: `ka.with_policy(policy,
/// time)?.binding_signature()`.
fn binding_signature<T>(&self, policy: &'a dyn Policy, time: T)
-> Result<&'a Signature>
where T: Into<Option<time::SystemTime>>
{
let time = time.into().unwrap_or_else(crate::now);
if self.primary {
self.cert().primary_userid_relaxed(policy, time, false)
.map(|u| u.binding_signature())
.or_else(|e0| {
// Lookup of the primary user id binding failed.
// Look for direct key signatures.
self.cert().primary_key().bundle()
.binding_signature(policy, time)
.map_err(|e1| {
// Both lookups failed. Keep the more
// meaningful error.
if let Some(Error::NoBindingSignature(_))
= e1.downcast_ref()
{
e0 // Return the original error.
} else {
e1
}
})
})
} else {
self.bundle().binding_signature(policy, time)
}
}
}
impl<'a, P, R, R2> KeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
{
/// Returns the `KeyAmalgamation`'s `ComponentAmalgamation`.
pub fn component_amalgamation(&self)
-> &ComponentAmalgamation<'a, Key<P, R>> {
&self.ca
}
/// Returns the `KeyAmalgamation`'s key.
///
/// Normally, a type implementing `KeyAmalgamation` eventually
/// derefs to a `Key`, however, this method provides a more
/// accurate lifetime. See the documentation for
/// `ComponentAmalgamation::component` for an explanation.
pub fn key(&self) -> &'a Key<P, R> {
self.ca.component()
}
}
impl<'a, P, R, R2> KeyAmalgamation<'a, P, R, R2>
where Self: PrimaryKey<'a, P, R>,
P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
{
/// Returns the third-party certifications issued by the specified
/// key, and valid at the specified time.
///
/// This function returns the certifications issued by the
/// specified key. Specifically, it returns a certification if:
///
/// - it is well formed,
/// - it is live with respect to the reference time,
/// - it conforms to the policy, and
/// - the signature is cryptographically valid.
///
/// This method is implemented on a [`KeyAmalgamation`] and not
/// a [`ValidKeyAmalgamation`], because a third-party
/// certification does not require the key to be self signed.
///
/// # Examples
///
/// Alice has certified that a certificate belongs to Bob on two
/// occasions. Whereas
/// [`KeyAmalgamation::valid_certifications_by_key`] returns
/// both certifications,
/// [`KeyAmalgamation::active_certifications_by_key`] only
/// returns the most recent certification.
///
/// ```rust
/// use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// # use openpgp::packet::signature::SignatureBuilder;
/// # use openpgp::packet::UserID;
/// use openpgp::policy::StandardPolicy;
/// # use openpgp::types::SignatureType;
///
/// const P: &StandardPolicy = &StandardPolicy::new();
///
/// # fn main() -> openpgp::Result<()> {
/// # let epoch = std::time::SystemTime::now()
/// # - std::time::Duration::new(100, 0);
/// # let t0 = epoch;
/// #
/// # let (alice, _) = CertBuilder::new()
/// # .set_creation_time(t0)
/// # .add_userid("<alice@example.org>")
/// # .generate()
/// # .unwrap();
/// let alice: Cert = // ...
/// # alice;
/// #
/// # let bob_userid = "<bob@example.org>";
/// # let (bob, _) = CertBuilder::new()
/// # .set_creation_time(t0)
/// # .add_userid(bob_userid)
/// # .generate()
/// # .unwrap();
/// let bob: Cert = // ...
/// # bob;
///
/// # // Alice has not certified Bob's User ID.
/// # let ka = bob.primary_key();
/// # assert_eq!(
/// # ka.active_certifications_by_key(
/// # P, t0, alice.primary_key().key()).count(),
/// # 0);
/// #
/// # // Have Alice certify Bob's certificate.
/// # let mut alice_signer = alice
/// # .keys()
/// # .with_policy(P, None)
/// # .for_certification()
/// # .next().expect("have a certification-capable key")
/// # .key()
/// # .clone()
/// # .parts_into_secret().expect("have unencrypted key material")
/// # .into_keypair().expect("have unencrypted key material");
/// #
/// # let mut bob = bob;
/// # for i in 1..=2usize {
/// # let ti = t0 + std::time::Duration::new(i as u64, 0);
/// #
/// # let certification = SignatureBuilder::new(SignatureType::DirectKey)
/// # .set_signature_creation_time(ti)?
/// # .sign_direct_key(
/// # &mut alice_signer,
/// # bob.primary_key().key())?;
/// # bob = bob.insert_packets(certification)?;
/// #
/// # let ka = bob.primary_key();
/// # assert_eq!(
/// # ka.valid_certifications_by_key(
/// # P, ti, alice.primary_key().key()).count(),
/// # i);
/// #
/// # assert_eq!(
/// # ka.active_certifications_by_key(
/// # P, ti, alice.primary_key().key()).count(),
/// # 1);
/// # }
/// let bob_pk = bob.primary_key();
///
/// let valid_certifications = bob_pk.valid_certifications_by_key(
/// P, None, alice.primary_key().key());
/// // Alice certified Bob's certificate twice.
/// assert_eq!(valid_certifications.count(), 2);
///
/// let active_certifications = bob_pk.active_certifications_by_key(
/// P, None, alice.primary_key().key());
/// // But only the most recent one is active.
/// assert_eq!(active_certifications.count(), 1);
/// # Ok(()) }
/// ```
pub fn valid_certifications_by_key<T, PK>(&self,
policy: &'a dyn Policy,
reference_time: T,
issuer: PK)
-> impl Iterator<Item=&Signature> + Send + Sync
where
T: Into<Option<time::SystemTime>>,
PK: Into<&'a Key<key::PublicParts,
key::UnspecifiedRole>>,
{
let reference_time = reference_time.into();
let issuer = issuer.into();
let primary = self.primary();
self.valid_certifications_by_key_(
policy, reference_time, issuer, false,
self.certifications(),
move |sig| {
if primary {
sig.clone().verify_direct_key(
issuer,
self.component().role_as_primary())
} else {
sig.clone().verify_subkey_binding(
issuer,
self.cert.primary_key().key(),
self.component().role_as_subordinate())
}
})
}
/// Returns any active third-party certifications issued by the
/// specified key.
///
/// This function is like
/// [`KeyAmalgamation::valid_certifications_by_key`], but it
/// only returns active certifications. Active certifications are
/// the most recent valid certifications with respect to the
/// reference time.
///
/// Although there is normally only a single active certification,
/// there can be multiple certifications with the same timestamp.
/// In this case, all of them are returned.
///
/// Unlike self-signatures, multiple third-party certifications
/// issued by the same key at the same time can be sensible. For
/// instance, Alice may fully trust a CA for user IDs in a
/// particular domain, and partially trust it for everything else.
/// This can only be expressed using multiple certifications.
///
/// This method is implemented on a [`KeyAmalgamation`] and not
/// a [`ValidKeyAmalgamation`], because a third-party
/// certification does not require the user ID to be self signed.
///
/// # Examples
///
/// See the examples for
/// [`KeyAmalgamation::valid_certifications_by_key`].
pub fn active_certifications_by_key<T, PK>(&self,
policy: &'a dyn Policy,
reference_time: T,
issuer: PK)
-> impl Iterator<Item=&Signature> + Send + Sync
where
T: Into<Option<time::SystemTime>>,
PK: Into<&'a Key<key::PublicParts,
key::UnspecifiedRole>>,
{
let reference_time = reference_time.into();
let issuer = issuer.into();
let primary = self.primary();
self.valid_certifications_by_key_(
policy, reference_time, issuer, true,
self.certifications(),
move |sig| {
if primary {
sig.clone().verify_direct_key(
issuer,
self.component().role_as_primary())
} else {
sig.clone().verify_subkey_binding(
issuer,
self.cert.primary_key().key(),
&self.component().role_as_subordinate())
}
})
}
/// Returns the third-party revocations issued by the specified
/// key, and valid at the specified time.
///
/// This function returns the revocations issued by the specified
/// key. Specifically, it returns a revocation if:
///
/// - it is well formed,
/// - it is a [hard revocation](crate::types::RevocationType),
/// or it is live with respect to the reference time,
/// - it conforms to the policy, and
/// - the signature is cryptographically valid.
///
/// This method is implemented on a [`KeyAmalgamation`] and not
/// a [`ValidKeyAmalgamation`], because a third-party
/// revocation does not require the key to be self signed.
///
/// # Examples
///
/// Alice revoked Bob's certificate.
///
/// ```rust
/// use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// # use openpgp::Packet;
/// # use openpgp::packet::signature::SignatureBuilder;
/// # use openpgp::packet::UserID;
/// use openpgp::policy::StandardPolicy;
/// # use openpgp::types::ReasonForRevocation;
/// # use openpgp::types::SignatureType;
///
/// const P: &StandardPolicy = &StandardPolicy::new();
///
/// # fn main() -> openpgp::Result<()> {
/// # let epoch = std::time::SystemTime::now()
/// # - std::time::Duration::new(100, 0);
/// # let t0 = epoch;
/// # let t1 = epoch + std::time::Duration::new(1, 0);
/// #
/// # let (alice, _) = CertBuilder::new()
/// # .set_creation_time(t0)
/// # .add_userid("<alice@example.org>")
/// # .generate()
/// # .unwrap();
/// let alice: Cert = // ...
/// # alice;
/// #
/// # let bob_userid = "<bob@example.org>";
/// # let (bob, _) = CertBuilder::new()
/// # .set_creation_time(t0)
/// # .add_userid(bob_userid)
/// # .generate()
/// # .unwrap();
/// let bob: Cert = // ...
/// # bob;
///
/// # // Have Alice certify Bob's certificate.
/// # let mut alice_signer = alice
/// # .keys()
/// # .with_policy(P, None)
/// # .for_certification()
/// # .next().expect("have a certification-capable key")
/// # .key()
/// # .clone()
/// # .parts_into_secret().expect("have unencrypted key material")
/// # .into_keypair().expect("have unencrypted key material");
/// #
/// # let certification = SignatureBuilder::new(SignatureType::KeyRevocation)
/// # .set_signature_creation_time(t1)?
/// # .set_reason_for_revocation(
/// # ReasonForRevocation::KeyRetired, b"")?
/// # .sign_direct_key(
/// # &mut alice_signer,
/// # bob.primary_key().key())?;
/// # let bob = bob.insert_packets(certification)?;
/// let ka = bob.primary_key();
///
/// let revs = ka.valid_third_party_revocations_by_key(
/// P, None, alice.primary_key().key());
/// // Alice revoked Bob's certificate.
/// assert_eq!(revs.count(), 1);
/// # Ok(()) }
/// ```
pub fn valid_third_party_revocations_by_key<T, PK>(&self,
policy: &'a dyn Policy,
reference_time: T,
issuer: PK)
-> impl Iterator<Item=&Signature> + Send + Sync
where
T: Into<Option<time::SystemTime>>,
PK: Into<&'a Key<key::PublicParts,
key::UnspecifiedRole>>,
{
let issuer = issuer.into();
let reference_time = reference_time.into();
let primary = self.primary();
self.valid_certifications_by_key_(
policy, reference_time, issuer, false,
self.other_revocations(),
move |sig| {
if primary {
sig.clone().verify_primary_key_revocation(
issuer,
self.component().role_as_primary())
} else {
sig.clone().verify_subkey_revocation(
issuer,
self.cert.primary_key().key(),
&self.component().role_as_subordinate())
}
})
}
}
/// A `KeyAmalgamation` plus a `Policy` and a reference time.
///
/// In the same way that a [`ValidComponentAmalgamation`] extends a
/// [`ComponentAmalgamation`], a `ValidKeyAmalgamation` extends a
/// [`KeyAmalgamation`]: a `ValidKeyAmalgamation` combines a
/// `KeyAmalgamation`, a [`Policy`], and a reference time. This
/// allows it to implement the [`ValidAmalgamation`] trait, which
/// provides methods like [`ValidAmalgamation::binding_signature`] that require a
/// `Policy` and a reference time. Although `KeyAmalgamation` could
/// implement these methods by requiring that the caller explicitly
/// pass them in, embedding them in the `ValidKeyAmalgamation` helps
/// ensure that multipart operations, even those that span multiple
/// functions, use the same `Policy` and reference time.
///
/// A `ValidKeyAmalgamation` can be obtained by transforming a
/// `KeyAmalgamation` using [`ValidateAmalgamation::with_policy`]. A
/// [`KeyAmalgamationIter`] can also be changed to yield
/// `ValidKeyAmalgamation`s.
///
/// A `ValidKeyAmalgamation` is guaranteed to come from a valid
/// certificate, and have a valid and live *binding* signature at the
/// specified reference time. Note: this only means that the binding
/// signatures are live; it says nothing about whether the
/// *certificate* or the *`Key`* is live and non-revoked. If you care
/// about those things, you need to check them separately.
///
/// # Examples:
///
/// Find all non-revoked, live, signing-capable keys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::RevocationStatus;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) = CertBuilder::new()
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate().unwrap();
/// // `with_policy` ensures that the certificate and any components
/// // that it returns have valid *binding signatures*. But, we still
/// // need to check that the certificate and `Key` are not revoked,
/// // and live.
/// //
/// // Note: `ValidKeyAmalgamation::revocation_status`, etc. use the
/// // embedded policy and timestamp. Even though we used `None` for
/// // the timestamp (i.e., now), they are guaranteed to use the same
/// // timestamp, because `with_policy` eagerly transforms it into
/// // the current time.
/// let cert = cert.with_policy(p, None)?;
/// if let RevocationStatus::Revoked(_revs) = cert.revocation_status() {
/// // Revoked by the certificate holder. (If we care about
/// // designated revokers, then we need to check those
/// // ourselves.)
/// # unreachable!();
/// } else if let Err(_err) = cert.alive() {
/// // Certificate was created in the future or is expired.
/// # unreachable!();
/// } else {
/// // `ValidCert::keys` returns `ValidKeyAmalgamation`s.
/// for ka in cert.keys() {
/// if let RevocationStatus::Revoked(_revs) = ka.revocation_status() {
/// // Revoked by the key owner. (If we care about
/// // designated revokers, then we need to check those
/// // ourselves.)
/// # unreachable!();
/// } else if let Err(_err) = ka.alive() {
/// // Key was created in the future or is expired.
/// # unreachable!();
/// } else if ! ka.for_signing() {
/// // We're looking for a signing-capable key, skip this one.
/// } else {
/// // Use it!
/// }
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [`ValidComponentAmalgamation`]: super::ValidComponentAmalgamation
/// [`ComponentAmalgamation`]: super::ComponentAmalgamation
/// [`Policy`]: crate::policy::Policy
/// [`ValidAmalgamation`]: super::ValidAmalgamation
/// [`ValidAmalgamation::binding_signature`]: super::ValidAmalgamation::binding_signature()
/// [`ValidateAmalgamation::with_policy`]: super::ValidateAmalgamation::with_policy
#[derive(Debug, Clone)]
pub struct ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
{
// Ouch, ouch, ouch! ka is a `KeyAmalgamation`, which contains a
// reference to a `Cert`. `cert` is a `ValidCert` and contains a
// reference to the same `Cert`! We do this so that
// `ValidKeyAmalgamation` can deref to a `KeyAmalgamation` and
// `ValidKeyAmalgamation::cert` can return a `&ValidCert`.
ka: KeyAmalgamation<'a, P, R, R2>,
cert: ValidCert<'a>,
// The binding signature at time `time`. (This is just a cache.)
binding_signature: &'a Signature,
}
assert_send_and_sync!(ValidKeyAmalgamation<'_, P, R, R2>
where P: key::KeyParts,
R: key::KeyRole,
R2: Copy,
);
/// A Valid primary Key, and its associated data.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidPrimaryKeyAmalgamation<'a, P>
= ValidKeyAmalgamation<'a, P, key::PrimaryRole, ()>;
/// A Valid subkey, and its associated data.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidSubordinateKeyAmalgamation<'a, P>
= ValidKeyAmalgamation<'a, P, key::SubordinateRole, ()>;
/// A valid key whose role is not known at compile time.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidErasedKeyAmalgamation<'a, P>
= ValidKeyAmalgamation<'a, P, key::UnspecifiedRole, bool>;
impl<'a, P, R, R2> Deref for ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
{
type Target = KeyAmalgamation<'a, P, R, R2>;
fn deref(&self) -> &Self::Target {
&self.ka
}
}
impl<'a, P, R, R2> From<ValidKeyAmalgamation<'a, P, R, R2>>
for KeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
{
fn from(vka: ValidKeyAmalgamation<'a, P, R, R2>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
vka.ka
}
}
impl<'a, P: 'a + key::KeyParts> From<ValidPrimaryKeyAmalgamation<'a, P>>
for ValidErasedKeyAmalgamation<'a, P>
{
fn from(vka: ValidPrimaryKeyAmalgamation<'a, P>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.into(),
cert: vka.cert,
binding_signature: vka.binding_signature,
}
}
}
impl<'a, P: 'a + key::KeyParts> From<&ValidPrimaryKeyAmalgamation<'a, P>>
for ValidErasedKeyAmalgamation<'a, P>
{
fn from(vka: &ValidPrimaryKeyAmalgamation<'a, P>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.clone().into(),
cert: vka.cert.clone(),
binding_signature: vka.binding_signature,
}
}
}
impl<'a, P: 'a + key::KeyParts> From<ValidSubordinateKeyAmalgamation<'a, P>>
for ValidErasedKeyAmalgamation<'a, P>
{
fn from(vka: ValidSubordinateKeyAmalgamation<'a, P>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.into(),
cert: vka.cert,
binding_signature: vka.binding_signature,
}
}
}
impl<'a, P: 'a + key::KeyParts> From<&ValidSubordinateKeyAmalgamation<'a, P>>
for ValidErasedKeyAmalgamation<'a, P>
{
fn from(vka: &ValidSubordinateKeyAmalgamation<'a, P>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.clone().into(),
cert: vka.cert.clone(),
binding_signature: vka.binding_signature,
}
}
}
// We can infallibly convert part X to part Y for everything but
// Public -> Secret and Unspecified -> Secret.
macro_rules! impl_conversion {
($s:ident, $p1:path, $p2:path) => {
impl<'a> From<$s<'a, $p1>>
for ValidErasedKeyAmalgamation<'a, $p2>
{
fn from(vka: $s<'a, $p1>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.into(),
cert: vka.cert,
binding_signature: vka.binding_signature,
}
}
}
impl<'a> From<&$s<'a, $p1>>
for ValidErasedKeyAmalgamation<'a, $p2>
{
fn from(vka: &$s<'a, $p1>) -> Self {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
ValidErasedKeyAmalgamation {
ka: vka.ka.clone().into(),
cert: vka.cert.clone(),
binding_signature: vka.binding_signature,
}
}
}
}
}
impl_conversion!(ValidPrimaryKeyAmalgamation,
key::SecretParts, key::PublicParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
key::SecretParts, key::UnspecifiedParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
key::PublicParts, key::UnspecifiedParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
key::UnspecifiedParts, key::PublicParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
key::SecretParts, key::PublicParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
key::SecretParts, key::UnspecifiedParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
key::PublicParts, key::UnspecifiedParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
key::UnspecifiedParts, key::PublicParts);
impl<'a, P, P2> TryFrom<ValidErasedKeyAmalgamation<'a, P>>
for ValidPrimaryKeyAmalgamation<'a, P2>
where P: 'a + key::KeyParts,
P2: 'a + key::KeyParts,
{
type Error = anyhow::Error;
fn try_from(vka: ValidErasedKeyAmalgamation<'a, P>) -> Result<Self> {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
Ok(ValidPrimaryKeyAmalgamation {
ka: vka.ka.try_into()?,
cert: vka.cert,
binding_signature: vka.binding_signature,
})
}
}
impl<'a, P, P2> TryFrom<ValidErasedKeyAmalgamation<'a, P>>
for ValidSubordinateKeyAmalgamation<'a, P2>
where P: 'a + key::KeyParts,
P2: 'a + key::KeyParts,
{
type Error = anyhow::Error;
fn try_from(vka: ValidErasedKeyAmalgamation<'a, P>) -> Result<Self> {
Ok(ValidSubordinateKeyAmalgamation {
ka: vka.ka.try_into()?,
cert: vka.cert,
binding_signature: vka.binding_signature,
})
}
}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::PrimaryRole>>
for ValidPrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = Self;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized
{
assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
self.ka.with_policy(policy, time)
.map(|vka| {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
vka
})
}
}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::SubordinateRole>>
for ValidSubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = Self;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized
{
assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
self.ka.with_policy(policy, time)
.map(|vka| {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
vka
})
}
}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::UnspecifiedRole>>
for ValidErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
type V = Self;
fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized
{
assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
self.ka.with_policy(policy, time)
.map(|vka| {
assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
vka
})
}
}
impl<'a, P, R, R2> seal::Sealed for ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
Self: PrimaryKey<'a, P, R>,
{}
impl<'a, P, R, R2> ValidAmalgamation<'a, Key<P, R>>
for ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
Self: PrimaryKey<'a, P, R>,
{
fn cert(&self) -> &ValidCert<'a> {
assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
&self.cert
}
fn time(&self) -> SystemTime {
self.cert.time()
}
fn policy(&self) -> &'a dyn Policy {
assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
self.cert.policy()
}
fn binding_signature(&self) -> &'a Signature {
self.binding_signature
}
fn revocation_status(&self) -> RevocationStatus<'a> {
if self.primary() {
self.cert.revocation_status()
} else {
self.bundle()._revocation_status(self.policy(), self.time(),
true, Some(self.binding_signature))
}
}
fn revocation_keys(&self)
-> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>
{
let mut keys = std::collections::HashSet::new();
let policy = self.policy();
let pk_sec = self.cert().primary_key().hash_algo_security();
// All valid self-signatures.
let sec = self.hash_algo_security;
self.self_signatures()
.filter(move |sig| {
policy.signature(sig, sec).is_ok()
})
// All direct-key signatures.
.chain(self.cert().primary_key()
.self_signatures()
.filter(|sig| {
policy.signature(sig, pk_sec).is_ok()
}))
.flat_map(|sig| sig.revocation_keys())
.for_each(|rk| { keys.insert(rk); });
Box::new(keys.into_iter())
}
}
impl<'a, P> PrimaryKey<'a, P, key::PrimaryRole>
for ValidPrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
true
}
}
impl<'a, P> PrimaryKey<'a, P, key::SubordinateRole>
for ValidSubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
false
}
}
impl<'a, P> PrimaryKey<'a, P, key::UnspecifiedRole>
for ValidErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
fn primary(&self) -> bool {
self.ka.primary
}
}
impl<'a, P, R, R2> ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
Self: ValidAmalgamation<'a, Key<P, R>>,
Self: PrimaryKey<'a, P, R>,
{
/// Returns whether the key is alive as of the amalgamation's
/// reference time.
///
/// A `ValidKeyAmalgamation` is guaranteed to have a live binding
/// signature. This is independent of whether the component is
/// live.
///
/// If the certificate is not alive as of the reference time, no
/// subkey can be alive.
///
/// This function considers both the binding signature and the
/// direct key signature. Information in the binding signature
/// takes precedence over the direct key signature. See [Section
/// 5.2.3.3 of RFC 4880].
///
/// [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
///
/// For a definition of liveness, see the [`key_alive`] method.
///
/// [`key_alive`]: crate::packet::signature::subpacket::SubpacketAreas::key_alive()
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) = CertBuilder::new()
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate()?;
/// let ka = cert.primary_key().with_policy(p, None)?;
/// if let Err(_err) = ka.alive() {
/// // Not alive.
/// # unreachable!();
/// }
/// # Ok(()) }
/// ```
pub fn alive(&self) -> Result<()>
{
if ! self.primary() {
// First, check the certificate.
self.cert().alive()
.context("The certificate is not live")?;
}
let sig = {
let binding : &Signature = self.binding_signature();
if binding.key_validity_period().is_some() {
Some(binding)
} else {
self.direct_key_signature().ok()
}
};
if let Some(sig) = sig {
sig.key_alive(self.key(), self.time())
.with_context(|| if self.primary() {
"The primary key is not live"
} else {
"The subkey is not live"
})
} else {
// There is no key expiration time on the binding
// signature. This key does not expire.
Ok(())
}
}
/// Returns the wrapped `KeyAmalgamation`.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) = CertBuilder::new()
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate()?;
/// let ka = cert.primary_key();
///
/// // `with_policy` takes ownership of `ka`.
/// let vka = ka.with_policy(p, None)?;
///
/// // And here we get it back:
/// let ka = vka.into_key_amalgamation();
/// # Ok(()) }
/// ```
pub fn into_key_amalgamation(self) -> KeyAmalgamation<'a, P, R, R2> {
self.ka
}
}
impl<'a, P, R, R2> ValidKeyAmalgamation<'a, P, R, R2>
where P: key::KeyParts,
R: key::KeyRole,
R2: Copy,
Self: PrimaryKey<'a, P, R>,
{
/// Returns the key's primary key binding signature, if any.
///
/// The [primary key binding signature] is embedded inside of a
/// subkey binding signature. It is made by the subkey to
/// indicate that it should be associated with the primary key.
/// This prevents an attack in which an attacker creates a
/// certificate, and associates the victim's subkey with it
/// thereby creating confusion about the certificate that issued a
/// signature.
///
/// [primary key binding signature]: https://datatracker.ietf.org/doc/html/rfc4880#section-5.2.1
///
/// Not all keys have primary key binding signatures. First,
/// primary keys don't have them, because they don't need them.
/// Second, encrypt-capable subkeys don't have them because they
/// are not (usually) able to issue signatures.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # const P: &StandardPolicy = &StandardPolicy::new();
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// let vc = cert.with_policy(P, None)?;
///
/// assert!(vc.primary_key().primary_key_binding_signature().is_none());
///
/// // A signing key has to have a primary key binding signature.
/// for ka in vc.keys().for_signing() {
/// assert!(ka.primary_key_binding_signature().is_some());
/// }
///
/// // Encryption keys normally can't have a primary key binding
/// // signature, because they can't issue signatures.
/// for ka in vc.keys().for_transport_encryption() {
/// assert!(ka.primary_key_binding_signature().is_none());
/// }
/// # Ok(())
/// # }
/// ```
pub fn primary_key_binding_signature(&self) -> Option<&Signature> {
let subkey = if self.primary() {
// A primary key has no backsig.
return None;
} else {
self.key().role_as_subordinate()
};
let pk = self.cert().primary_key().key();
for backsig in
self.binding_signature.subpackets(SubpacketTag::EmbeddedSignature)
{
if let SubpacketValue::EmbeddedSignature(sig) =
backsig.value()
{
if sig.verify_primary_key_binding(pk, subkey).is_ok() {
// Mark the subpacket as authenticated by the
// embedded signature.
backsig.set_authenticated(true);
return Some(sig);
}
} else {
unreachable!("subpackets(EmbeddedSignature) returns \
EmbeddedSignatures");
}
}
None
}
}
impl<'a, P> ValidPrimaryKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
/// Sets the key to expire in delta seconds.
///
/// Note: the time is relative to the key's creation time, not the
/// current time!
///
/// This function exists to facilitate testing, which is why it is
/// not exported.
#[cfg(test)]
pub(crate) fn set_validity_period_as_of(&self,
primary_signer: &mut dyn Signer,
expiration: Option<time::Duration>,
now: time::SystemTime)
-> Result<Vec<Signature>>
{
ValidErasedKeyAmalgamation::<P>::from(self)
.set_validity_period_as_of(primary_signer, None, expiration, now)
}
/// Creates signatures that cause the key to expire at the specified time.
///
/// This function creates new binding signatures that cause the
/// key to expire at the specified time when integrated into the
/// certificate. For the primary key, it is necessary to
/// create a new self-signature for each non-revoked User ID, and
/// to create a direct key signature. This is needed, because the
/// primary User ID is first consulted when determining the
/// primary key's expiration time, and certificates can be
/// distributed with a possibly empty subset of User IDs.
///
/// Setting a key's expiry time means updating an existing binding
/// signature---when looking up information, only one binding
/// signature is normally considered, and we don't want to drop
/// the other information stored in the current binding signature.
/// This function uses the binding signature determined by
/// `ValidKeyAmalgamation`'s policy and reference time for this.
///
/// # Examples
///
/// ```
/// use std::time;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
/// # let (cert, _) = CertBuilder::new()
/// # .set_creation_time(t)
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate()?;
/// let vc = cert.with_policy(p, None)?;
///
/// // Assert that the primary key is not expired.
/// assert!(vc.primary_key().alive().is_ok());
///
/// // Make the primary key expire in a week.
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(7 * 24 * 60 * 60);
///
/// // We assume that the secret key material is available, and not
/// // password protected.
/// let mut signer = vc.primary_key()
/// .key().clone().parts_into_secret()?.into_keypair()?;
///
/// let sigs = vc.primary_key().set_expiration_time(&mut signer, Some(t))?;
/// let cert = cert.insert_packets(sigs)?;
///
/// // The primary key isn't expired yet.
/// let vc = cert.with_policy(p, None)?;
/// assert!(vc.primary_key().alive().is_ok());
///
/// // But in two weeks, it will be...
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
/// let vc = cert.with_policy(p, t)?;
/// assert!(vc.primary_key().alive().is_err());
/// # Ok(()) }
pub fn set_expiration_time(&self,
primary_signer: &mut dyn Signer,
expiration: Option<time::SystemTime>)
-> Result<Vec<Signature>>
{
ValidErasedKeyAmalgamation::<P>::from(self)
.set_expiration_time(primary_signer, None, expiration)
}
}
impl<'a, P> ValidSubordinateKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
/// Creates signatures that cause the key to expire at the specified time.
///
/// This function creates new binding signatures that cause the
/// key to expire at the specified time when integrated into the
/// certificate. For subkeys, a single `Signature` is returned.
///
/// Setting a key's expiry time means updating an existing binding
/// signature---when looking up information, only one binding
/// signature is normally considered, and we don't want to drop
/// the other information stored in the current binding signature.
/// This function uses the binding signature determined by
/// `ValidKeyAmalgamation`'s policy and reference time for this.
///
/// When updating the expiration time of signing-capable subkeys,
/// we need to create a new [primary key binding signature].
/// Therefore, we need a signer for the subkey. If
/// `subkey_signer` is `None`, and this is a signing-capable
/// subkey, this function fails with [`Error::InvalidArgument`].
/// Likewise, this function fails if `subkey_signer` is not `None`
/// when updating the expiration of an non signing-capable subkey.
///
/// [primary key binding signature]: https://tools.ietf.org/html/rfc4880#section-5.2.1
/// [`Error::InvalidArgument`]: super::super::super::Error::InvalidArgument
///
/// # Examples
///
/// ```
/// use std::time;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
/// # let (cert, _) = CertBuilder::new()
/// # .set_creation_time(t)
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate()?;
/// let vc = cert.with_policy(p, None)?;
///
/// // Assert that the keys are not expired.
/// for ka in vc.keys() {
/// assert!(ka.alive().is_ok());
/// }
///
/// // Make the keys expire in a week.
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(7 * 24 * 60 * 60);
///
/// // We assume that the secret key material is available, and not
/// // password protected.
/// let mut primary_signer = vc.primary_key()
/// .key().clone().parts_into_secret()?.into_keypair()?;
/// let mut signing_subkey_signer = vc.keys().for_signing().nth(0).unwrap()
/// .key().clone().parts_into_secret()?.into_keypair()?;
///
/// let mut sigs = Vec::new();
/// for ka in vc.keys() {
/// if ! ka.for_signing() {
/// // Non-signing-capable subkeys are easy to update.
/// sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
/// None, Some(t))?);
/// } else {
/// // Signing-capable subkeys need to create a primary
/// // key binding signature with the subkey:
/// assert!(ka.set_expiration_time(&mut primary_signer,
/// None, Some(t)).is_err());
///
/// // Here, we need the subkey's signer:
/// sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
/// Some(&mut signing_subkey_signer),
/// Some(t))?);
/// }
/// }
/// let cert = cert.insert_packets(sigs)?;
///
/// // They aren't expired yet.
/// let vc = cert.with_policy(p, None)?;
/// for ka in vc.keys() {
/// assert!(ka.alive().is_ok());
/// }
///
/// // But in two weeks, they will be...
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
/// let vc = cert.with_policy(p, t)?;
/// for ka in vc.keys() {
/// assert!(ka.alive().is_err());
/// }
/// # Ok(()) }
pub fn set_expiration_time(&self,
primary_signer: &mut dyn Signer,
subkey_signer: Option<&mut dyn Signer>,
expiration: Option<time::SystemTime>)
-> Result<Vec<Signature>>
{
ValidErasedKeyAmalgamation::<P>::from(self)
.set_expiration_time(primary_signer, subkey_signer, expiration)
}
}
impl<'a, P> ValidErasedKeyAmalgamation<'a, P>
where P: 'a + key::KeyParts
{
/// Sets the key to expire in delta seconds.
///
/// Note: the time is relative to the key's creation time, not the
/// current time!
///
/// This function exists to facilitate testing, which is why it is
/// not exported.
pub(crate) fn set_validity_period_as_of(&self,
primary_signer: &mut dyn Signer,
subkey_signer:
Option<&mut dyn Signer>,
expiration: Option<time::Duration>,
now: time::SystemTime)
-> Result<Vec<Signature>>
{
let mut sigs = Vec::new();
// There are two cases to consider. If we are extending the
// validity of the primary key, we also need to create new
// binding signatures for all userids.
if self.primary() {
// First, update or create a direct key signature.
let template = self.direct_key_signature()
.map(|sig| {
signature::SignatureBuilder::from(sig.clone())
})
.unwrap_or_else(|_| {
let mut template = signature::SignatureBuilder::from(
self.binding_signature().clone())
.set_type(SignatureType::DirectKey);
// We're creating a direct signature from a User
// ID self signature. Remove irrelevant packets.
use SubpacketTag::*;
let ha = template.hashed_area_mut();
ha.remove_all(ExportableCertification);
ha.remove_all(Revocable);
ha.remove_all(TrustSignature);
ha.remove_all(RegularExpression);
ha.remove_all(PrimaryUserID);
ha.remove_all(SignersUserID);
ha.remove_all(ReasonForRevocation);
ha.remove_all(SignatureTarget);
ha.remove_all(EmbeddedSignature);
template
});
let mut builder = template
.set_signature_creation_time(now)?
.set_key_validity_period(expiration)?;
builder.hashed_area_mut().remove_all(
signature::subpacket::SubpacketTag::PrimaryUserID);
// Generate the signature.
sigs.push(builder.sign_direct_key(primary_signer, None)?);
// Second, generate a new binding signature for every
// userid. We need to be careful not to change the
// primary userid, so we make it explicit using the
// primary userid subpacket.
for userid in self.cert().userids().revoked(false) {
// To extend the validity of the subkey, create a new
// binding signature with updated key validity period.
let binding_signature = userid.binding_signature();
let builder = signature::SignatureBuilder::from(binding_signature.clone())
.set_signature_creation_time(now)?
.set_key_validity_period(expiration)?
.set_primary_userid(
self.cert().primary_userid().map(|primary| {
userid.userid() == primary.userid()
}).unwrap_or(false))?;
sigs.push(builder.sign_userid_binding(primary_signer,
self.cert().primary_key().component(),
&userid)?);
}
} else {
// To extend the validity of the subkey, create a new
// binding signature with updated key validity period.
let backsig = if self.for_certification() || self.for_signing()
|| self.for_authentication()
{
if let Some(subkey_signer) = subkey_signer {
Some(signature::SignatureBuilder::new(
SignatureType::PrimaryKeyBinding)
.set_signature_creation_time(now)?
.set_hash_algo(self.binding_signature.hash_algo())
.sign_primary_key_binding(
subkey_signer,
&self.cert().primary_key(),
self.key().role_as_subordinate())?)
} else {
return Err(Error::InvalidArgument(
"Changing expiration of signing-capable subkeys \
requires subkey signer".into()).into());
}
} else {
if subkey_signer.is_some() {
return Err(Error::InvalidArgument(
"Subkey signer given but subkey is not signing-capable"
.into()).into());
}
None
};
let mut sig =
signature::SignatureBuilder::from(
self.binding_signature().clone())
.set_signature_creation_time(now)?
.set_key_validity_period(expiration)?;
if let Some(bs) = backsig {
sig = sig.set_embedded_signature(bs)?;
}
sigs.push(sig.sign_subkey_binding(
primary_signer,
self.cert().primary_key().component(),
self.key().role_as_subordinate())?);
}
Ok(sigs)
}
/// Creates signatures that cause the key to expire at the specified time.
///
/// This function creates new binding signatures that cause the
/// key to expire at the specified time when integrated into the
/// certificate. For subkeys, only a single `Signature` is
/// returned. For the primary key, however, it is necessary to
/// create a new self-signature for each non-revoked User ID, and
/// to create a direct key signature. This is needed, because the
/// primary User ID is first consulted when determining the
/// primary key's expiration time, and certificates can be
/// distributed with a possibly empty subset of User IDs.
///
/// Setting a key's expiry time means updating an existing binding
/// signature---when looking up information, only one binding
/// signature is normally considered, and we don't want to drop
/// the other information stored in the current binding signature.
/// This function uses the binding signature determined by
/// `ValidKeyAmalgamation`'s policy and reference time for this.
///
/// When updating the expiration time of signing-capable subkeys,
/// we need to create a new [primary key binding signature].
/// Therefore, we need a signer for the subkey. If
/// `subkey_signer` is `None`, and this is a signing-capable
/// subkey, this function fails with [`Error::InvalidArgument`].
/// Likewise, this function fails if `subkey_signer` is not `None`
/// when updating the expiration of the primary key, or an non
/// signing-capable subkey.
///
/// [primary key binding signature]: https://tools.ietf.org/html/rfc4880#section-5.2.1
/// [`Error::InvalidArgument`]: super::super::super::Error::InvalidArgument
///
/// # Examples
///
/// ```
/// use std::time;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
/// # let (cert, _) = CertBuilder::new()
/// # .set_creation_time(t)
/// # .add_userid("Alice")
/// # .add_signing_subkey()
/// # .add_transport_encryption_subkey()
/// # .generate()?;
/// let vc = cert.with_policy(p, None)?;
///
/// // Assert that the keys are not expired.
/// for ka in vc.keys() {
/// assert!(ka.alive().is_ok());
/// }
///
/// // Make the keys expire in a week.
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(7 * 24 * 60 * 60);
///
/// // We assume that the secret key material is available, and not
/// // password protected.
/// let mut primary_signer = vc.primary_key()
/// .key().clone().parts_into_secret()?.into_keypair()?;
/// let mut signing_subkey_signer = vc.keys().for_signing().nth(0).unwrap()
/// .key().clone().parts_into_secret()?.into_keypair()?;
///
/// let mut sigs = Vec::new();
/// for ka in vc.keys() {
/// if ! ka.for_signing() {
/// // Non-signing-capable subkeys are easy to update.
/// sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
/// None, Some(t))?);
/// } else {
/// // Signing-capable subkeys need to create a primary
/// // key binding signature with the subkey:
/// assert!(ka.set_expiration_time(&mut primary_signer,
/// None, Some(t)).is_err());
///
/// // Here, we need the subkey's signer:
/// sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
/// Some(&mut signing_subkey_signer),
/// Some(t))?);
/// }
/// }
/// let cert = cert.insert_packets(sigs)?;
///
/// // They aren't expired yet.
/// let vc = cert.with_policy(p, None)?;
/// for ka in vc.keys() {
/// assert!(ka.alive().is_ok());
/// }
///
/// // But in two weeks, they will be...
/// let t = time::SystemTime::now()
/// + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
/// let vc = cert.with_policy(p, t)?;
/// for ka in vc.keys() {
/// assert!(ka.alive().is_err());
/// }
/// # Ok(()) }
pub fn set_expiration_time(&self,
primary_signer: &mut dyn Signer,
subkey_signer: Option<&mut dyn Signer>,
expiration: Option<time::SystemTime>)
-> Result<Vec<Signature>>
{
let expiration =
if let Some(e) = expiration.map(crate::types::normalize_systemtime)
{
let ct = self.creation_time();
match e.duration_since(ct) {
Ok(v) => Some(v),
Err(_) => return Err(Error::InvalidArgument(
format!("Expiration time {:?} predates creation time \
{:?}", e, ct)).into()),
}
} else {
None
};
self.set_validity_period_as_of(primary_signer, subkey_signer,
expiration, crate::now())
}
}
impl<'a, P, R, R2> ValidKeyAmalgamation<'a, P, R, R2>
where P: 'a + key::KeyParts,
R: 'a + key::KeyRole,
R2: Copy,
Self: ValidAmalgamation<'a, Key<P, R>>
{
/// Returns the key's `Key Flags`.
///
/// A Key's [`Key Flags`] holds information about the key. As of
/// RFC 4880, this information is primarily concerned with the
/// key's capabilities (e.g., whether it may be used for signing).
/// The other information that has been defined is: whether the
/// key has been split using something like [SSS], and whether the
/// primary key material is held by multiple parties. In
/// practice, the latter two flags are ignored.
///
/// As per [Section 5.2.3.3 of RFC 4880], when looking for the
/// `Key Flags`, the key's binding signature is first consulted
/// (in the case of the primary Key, this is the binding signature
/// of the primary User ID). If the `Key Flags` subpacket is not
/// present, then the direct key signature is consulted.
///
/// Since the key flags are taken from the active self signature,
/// a key's flags may change depending on the policy and the
/// reference time.
///
/// To increase compatibility with early v4 certificates, if there
/// is no key flags subpacket on the considered signatures, we
/// infer the key flags from the key's role and public key
/// algorithm.
///
/// [`Key Flags`]: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
/// [SSS]: https://de.wikipedia.org/wiki/Shamir%E2%80%99s_Secret_Sharing
/// [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::{Policy, StandardPolicy};
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let p: &dyn Policy = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let cert = cert.with_policy(p, None)?;
/// let ka = cert.primary_key();
/// println!("Primary Key's Key Flags: {:?}", ka.key_flags());
/// # assert!(ka.key_flags().unwrap().for_certification());
/// # Ok(()) }
/// ```
pub fn key_flags(&self) -> Option<KeyFlags> {
self.map(|s| s.key_flags())
.or_else(|| {
// There is no key flags subpacket. Match on the key
// role and algorithm and synthesize one. We do this
// to better support very early v4 certificates, where
// either the binding signature is a v3 signature and
// cannot contain subpackets, or it is a v4 signature,
// but the key's capabilities were implied by the
// public key algorithm.
use crate::types::PublicKeyAlgorithm;
// XXX: We cannot know whether this is a primary key
// or not because of
// https://gitlab.com/sequoia-pgp/sequoia/-/issues/1036
let is_primary = false;
// We only match on public key algorithms used at the
// time.
#[allow(deprecated)]
match (is_primary, self.key().pk_algo()) {
(true, PublicKeyAlgorithm::RSAEncryptSign) =>
Some(KeyFlags::empty()
.set_certification()
.set_transport_encryption()
.set_storage_encryption()
.set_signing()),
(true, _) =>
Some(KeyFlags::empty()
.set_certification()
.set_signing()),
(false, PublicKeyAlgorithm::RSAEncryptSign) =>
Some(KeyFlags::empty()
.set_transport_encryption()
.set_storage_encryption()
.set_signing()),
(false,
| PublicKeyAlgorithm::RSASign
| PublicKeyAlgorithm::DSA) =>
Some(KeyFlags::empty().set_signing()),
(false,
| PublicKeyAlgorithm::RSAEncrypt
| PublicKeyAlgorithm::ElGamalEncrypt
| PublicKeyAlgorithm::ElGamalEncryptSign) =>
Some(KeyFlags::empty()
.set_transport_encryption()
.set_storage_encryption()),
// Be conservative: newer algorithms don't get to
// benefit from implicit key flags.
(false, _) => None,
}
})
}
/// Returns whether the key has at least one of the specified key
/// flags.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that may be used for transport encryption (data in
/// motion) *or* storage encryption (data at rest):
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::KeyFlags;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.has_any_key_flag(KeyFlags::empty()
/// .set_storage_encryption()
/// .set_transport_encryption())
/// {
/// // `ka` is encryption capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn has_any_key_flag<F>(&self, flags: F) -> bool
where F: Borrow<KeyFlags>
{
let our_flags = self.key_flags().unwrap_or_else(KeyFlags::empty);
!(&our_flags & flags.borrow()).is_empty()
}
/// Returns whether the key is certification capable.
///
/// Note: [Section 12.1 of RFC 4880] says that the primary key is
/// certification capable independent of the `Key Flags`
/// subpacket:
///
/// > In a V4 key, the primary key MUST be a key capable of
/// > certification.
///
/// This function only reflects what is stored in the `Key Flags`
/// packet; it does not implicitly set this flag. In practice,
/// there are keys whose primary key's `Key Flags` do not have the
/// certification capable flag set. Some versions of netpgp, for
/// instance, create keys like this. Sequoia's higher-level
/// functionality correctly handles these keys by always
/// considering the primary key to be certification capable.
/// Users of this interface should too.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that are certification capable:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.primary() || ka.for_certification() {
/// // `ka` is certification capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [Section 12.1 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn for_certification(&self) -> bool {
self.has_any_key_flag(KeyFlags::empty().set_certification())
}
/// Returns whether the key is signing capable.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that are signing capable:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.for_signing() {
/// // `ka` is signing capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn for_signing(&self) -> bool {
self.has_any_key_flag(KeyFlags::empty().set_signing())
}
/// Returns whether the key is authentication capable.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that are authentication capable:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.for_authentication() {
/// // `ka` is authentication capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn for_authentication(&self) -> bool
{
self.has_any_key_flag(KeyFlags::empty().set_authentication())
}
/// Returns whether the key is storage-encryption capable.
///
/// OpenPGP distinguishes two types of encryption keys: those for
/// storage ([data at rest]) and those for transport ([data in
/// transit]). Most OpenPGP implementations, however, don't
/// distinguish between them in practice. Instead, when they
/// create a new encryption key, they just set both flags.
/// Likewise, when encrypting a message, it is not typically
/// possible to indicate the type of protection that is needed.
/// Sequoia supports creating keys with only one of these flags
/// set, and makes it easy to select the right type of key when
/// encrypting messages.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that are storage-encryption capable:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.for_storage_encryption() {
/// // `ka` is storage-encryption capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [data at rest]: https://en.wikipedia.org/wiki/Data_at_rest
/// [data in transit]: https://en.wikipedia.org/wiki/Data_in_transit
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn for_storage_encryption(&self) -> bool
{
self.has_any_key_flag(KeyFlags::empty().set_storage_encryption())
}
/// Returns whether the key is transport-encryption capable.
///
/// OpenPGP distinguishes two types of encryption keys: those for
/// storage ([data at rest]) and those for transport ([data in
/// transit]). Most OpenPGP implementations, however, don't
/// distinguish between them in practice. Instead, when they
/// create a new encryption key, they just set both flags.
/// Likewise, when encrypting a message, it is not typically
/// possible to indicate the type of protection that is needed.
/// Sequoia supports creating keys with only one of these flags
/// set, and makes it easy to select the right type of key when
/// encrypting messages.
///
/// The key flags are looked up as described in
/// [`ValidKeyAmalgamation::key_flags`].
///
/// # Examples
///
/// Finds keys that are transport-encryption capable:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for ka in cert.keys().with_policy(p, None) {
/// if ka.for_transport_encryption() {
/// // `ka` is transport-encryption capable.
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [data at rest]: https://en.wikipedia.org/wiki/Data_at_rest
/// [data in transit]: https://en.wikipedia.org/wiki/Data_in_transit
/// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
pub fn for_transport_encryption(&self) -> bool
{
self.has_any_key_flag(KeyFlags::empty().set_transport_encryption())
}
/// Returns how long the key is live.
///
/// This returns how long the key is live relative to its creation
/// time. Use [`ValidKeyAmalgamation::key_expiration_time`] to
/// get the key's absolute expiry time.
///
/// This function considers both the binding signature and the
/// direct key signature. Information in the binding signature
/// takes precedence over the direct key signature. See [Section
/// 5.2.3.3 of RFC 4880].
///
/// # Examples
///
/// ```
/// use std::time;
/// use std::convert::TryInto;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::Timestamp;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// // OpenPGP Timestamps have a one-second resolution. Since we
/// // want to round trip the time, round it down.
/// let now: Timestamp = time::SystemTime::now().try_into()?;
/// let now: time::SystemTime = now.try_into()?;
///
/// let a_week = time::Duration::from_secs(7 * 24 * 60 * 60);
///
/// let (cert, _) =
/// CertBuilder::general_purpose(None, Some("alice@example.org"))
/// .set_creation_time(now)
/// .set_validity_period(a_week)
/// .generate()?;
///
/// assert_eq!(cert.primary_key().with_policy(p, None)?.key_validity_period(),
/// Some(a_week));
/// # Ok(()) }
/// ```
///
/// [`ValidKeyAmalgamation::key_expiration_time`]: ValidKeyAmalgamation::key_expiration_time()
/// [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
pub fn key_validity_period(&self) -> Option<std::time::Duration> {
self.map(|s| s.key_validity_period())
}
/// Returns the key's expiration time.
///
/// If this function returns `None`, the key does not expire.
///
/// This returns the key's expiration time. Use
/// [`ValidKeyAmalgamation::key_validity_period`] to get the
/// duration of the key's lifetime.
///
/// This function considers both the binding signature and the
/// direct key signature. Information in the binding signature
/// takes precedence over the direct key signature. See [Section
/// 5.2.3.3 of RFC 4880].
///
/// # Examples
///
/// ```
/// use std::time;
/// use std::convert::TryInto;
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::Timestamp;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// // OpenPGP Timestamps have a one-second resolution. Since we
/// // want to round trip the time, round it down.
/// let now: Timestamp = time::SystemTime::now().try_into()?;
/// let now: time::SystemTime = now.try_into()?;
//
/// let a_week = time::Duration::from_secs(7 * 24 * 60 * 60);
/// let a_week_later = now + a_week;
///
/// let (cert, _) =
/// CertBuilder::general_purpose(None, Some("alice@example.org"))
/// .set_creation_time(now)
/// .set_validity_period(a_week)
/// .generate()?;
///
/// assert_eq!(cert.primary_key().with_policy(p, None)?.key_expiration_time(),
/// Some(a_week_later));
/// # Ok(()) }
/// ```
///
/// [`ValidKeyAmalgamation::key_validity_period`]: ValidKeyAmalgamation::key_validity_period()
/// [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
pub fn key_expiration_time(&self) -> Option<time::SystemTime> {
match self.key_validity_period() {
Some(vp) if vp.as_secs() > 0 => Some(self.key().creation_time() + vp),
_ => None,
}
}
// NOTE: If you add a method to ValidKeyAmalgamation that takes
// ownership of self, then don't forget to write a forwarder for
// it for ValidPrimaryKeyAmalgamation.
}
#[cfg(test)]
mod test {
use std::time::Duration;
use std::time::UNIX_EPOCH;
use crate::policy::StandardPolicy as P;
use crate::cert::prelude::*;
use crate::packet::Packet;
use crate::packet::signature::SignatureBuilder;
use crate::types::ReasonForRevocation;
use crate::types::RevocationType;
use super::*;
#[test]
fn expire_subkeys() {
let p = &P::new();
// Timeline:
//
// -1: Key created with no key expiration.
// 0: Setkeys set to expire in 1 year
// 1: Subkeys expire
let now = crate::now();
let a_year = time::Duration::from_secs(365 * 24 * 60 * 60);
let in_a_year = now + a_year;
let in_two_years = now + 2 * a_year;
let (cert, _) = CertBuilder::new()
.set_creation_time(now - a_year)
.add_signing_subkey()
.add_transport_encryption_subkey()
.generate().unwrap();
for ka in cert.keys().with_policy(p, None) {
assert!(ka.alive().is_ok());
}
let mut primary_signer = cert.primary_key().key().clone()
.parts_into_secret().unwrap().into_keypair().unwrap();
let mut signing_subkey_signer = cert.with_policy(p, None).unwrap()
.keys().for_signing().next().unwrap()
.key().clone().parts_into_secret().unwrap()
.into_keypair().unwrap();
// Only expire the subkeys.
let sigs = cert.keys().subkeys().with_policy(p, None)
.flat_map(|ka| {
if ! ka.for_signing() {
ka.set_expiration_time(&mut primary_signer,
None,
Some(in_a_year)).unwrap()
} else {
ka.set_expiration_time(&mut primary_signer,
Some(&mut signing_subkey_signer),
Some(in_a_year)).unwrap()
}
.into_iter()
.map(Into::into)
})
.collect::<Vec<Packet>>();
let cert = cert.insert_packets(sigs).unwrap();
for ka in cert.keys().with_policy(p, None) {
assert!(ka.alive().is_ok());
}
// Primary should not be expired two years from now.
assert!(cert.primary_key().with_policy(p, in_two_years).unwrap()
.alive().is_ok());
// But the subkeys should be.
for ka in cert.keys().subkeys().with_policy(p, in_two_years) {
assert!(ka.alive().is_err());
}
}
/// Test that subkeys of expired certificates are also considered
/// expired.
#[test]
fn issue_564() -> Result<()> {
use crate::parse::Parse;
use crate::packet::signature::subpacket::SubpacketTag;
let p = &P::new();
let cert = Cert::from_bytes(crate::tests::key("testy.pgp"))?;
assert!(cert.with_policy(p, None)?.alive().is_err());
let subkey = cert.with_policy(p, None)?.keys().nth(1).unwrap();
assert!(subkey.binding_signature().hashed_area()
.subpacket(SubpacketTag::KeyExpirationTime).is_none());
assert!(subkey.alive().is_err());
Ok(())
}
/// When setting the primary key's validity period, we create a
/// direct key signature. Check that this works even when the
/// original certificate doesn't have a direct key signature.
#[test]
fn set_expiry_on_certificate_without_direct_signature() -> Result<()> {
use crate::policy::StandardPolicy;
let p = &StandardPolicy::new();
let (cert, _) =
CertBuilder::general_purpose(None, Some("alice@example.org"))
.set_validity_period(None)
.generate()?;
// Remove the direct key signatures.
let cert = Cert::from_packets(Vec::from(cert)
.into_iter()
.filter(|p| ! matches!(
p,
Packet::Signature(s) if s.typ() == SignatureType::DirectKey
)))?;
let vc = cert.with_policy(p, None)?;
// Assert that the keys are not expired.
for ka in vc.keys() {
assert!(ka.alive().is_ok());
}
// Make the primary key expire in a week.
let t = crate::now()
+ time::Duration::from_secs(7 * 24 * 60 * 60);
let mut signer = vc
.primary_key().key().clone().parts_into_secret()?
.into_keypair()?;
let sigs = vc.primary_key()
.set_expiration_time(&mut signer, Some(t))?;
assert!(sigs.iter().any(|s| {
s.typ() == SignatureType::DirectKey
}));
let cert = cert.insert_packets(sigs)?;
// Make sure the primary key *and* all subkeys expire in a
// week: the subkeys inherit the KeyExpirationTime subpacket
// from the direct key signature.
for ka in cert.keys() {
let ka = ka.with_policy(p, None)?;
assert!(ka.alive().is_ok());
let ka = ka.with_policy(p, t + std::time::Duration::new(1, 0))?;
assert!(ka.alive().is_err());
}
Ok(())
}
#[test]
fn key_amalgamation_certifications_by_key() -> Result<()> {
// Alice and Bob certify Carol's certificate. We then check
// that valid_certifications_by_key and
// active_certifications_by_key return them.
let p = &crate::policy::StandardPolicy::new();
// $ date -u -d '2024-01-02 13:00' +%s
let t0 = UNIX_EPOCH + Duration::new(1704200400, 0);
// $ date -u -d '2024-01-02 14:00' +%s
let t1 = UNIX_EPOCH + Duration::new(1704204000, 0);
// $ date -u -d '2024-01-02 15:00' +%s
let t2 = UNIX_EPOCH + Duration::new(1704207600, 0);
let (alice, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid("<alice@example.example>")
.generate()
.unwrap();
let alice_primary = alice.primary_key().key();
let (bob, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid("<bob@example.example>")
.generate()
.unwrap();
let bob_primary = bob.primary_key().key();
let carol_userid = "<carol@example.example>";
let (carol, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid(carol_userid)
.generate()
.unwrap();
let ka = alice.primary_key();
assert_eq!(
ka.valid_certifications_by_key(p, None, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, None, alice_primary).count(),
0);
// Alice has not certified Bob's User ID.
let ka = bob.primary_key();
assert_eq!(
ka.valid_certifications_by_key(p, None, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, None, alice_primary).count(),
0);
// Alice has not certified Carol's User ID.
let ka = carol.primary_key();
assert_eq!(
ka.valid_certifications_by_key(p, None, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, None, alice_primary).count(),
0);
// Have Alice certify Carol's certificate at t1.
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::DirectKey)
.set_signature_creation_time(t1)?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.certifications().count(), 1);
assert_eq!(
ka.valid_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, alice_primary).count(),
1);
assert_eq!(
ka.active_certifications_by_key(p, t1, alice_primary).count(),
1);
assert_eq!(
ka.valid_certifications_by_key(p, t1, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t1, bob_primary).count(),
0);
// Have Alice certify Carol's certificate at t1 (again).
// Since both certifications were created at t1, they should
// both be returned.
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::DirectKey)
.set_signature_creation_time(t1)?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.certifications().count(), 2);
assert_eq!(
ka.valid_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.valid_certifications_by_key(p, t2, alice_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t2, alice_primary).count(),
2);
assert_eq!(
ka.valid_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, bob_primary).count(),
0);
// Have Alice certify Carol's certificate at t2. Now we only
// have one active certification.
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::DirectKey)
.set_signature_creation_time(t2)?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.certifications().count(), 3);
assert_eq!(
ka.valid_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.valid_certifications_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.active_certifications_by_key(p, t2, alice_primary).count(),
1);
assert_eq!(
ka.valid_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, bob_primary).count(),
0);
// Have Bob certify Carol's certificate at t1 and have it expire at t2.
let mut bob_signer = bob.primary_key()
.key()
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::DirectKey)
.set_signature_creation_time(t1)?
.set_signature_validity_period(t2.duration_since(t1)?)?
.sign_direct_key(
&mut bob_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.certifications().count(), 4);
assert_eq!(
ka.valid_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.valid_certifications_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.active_certifications_by_key(p, t2, alice_primary).count(),
1);
assert_eq!(
ka.valid_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, bob_primary).count(),
1);
assert_eq!(
ka.active_certifications_by_key(p, t1, bob_primary).count(),
1);
// It expired.
assert_eq!(
ka.valid_certifications_by_key(p, t2, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t2, bob_primary).count(),
0);
// Have Bob certify Carol's certificate at t1 again. This
// time don't have it expire.
let mut bob_signer = bob.primary_key()
.key()
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::DirectKey)
.set_signature_creation_time(t1)?
.sign_direct_key(
&mut bob_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.certifications().count(), 5);
assert_eq!(
ka.valid_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, alice_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.valid_certifications_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.active_certifications_by_key(p, t2, alice_primary).count(),
1);
assert_eq!(
ka.valid_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.active_certifications_by_key(p, t0, bob_primary).count(),
0);
assert_eq!(
ka.valid_certifications_by_key(p, t1, bob_primary).count(),
2);
assert_eq!(
ka.active_certifications_by_key(p, t1, bob_primary).count(),
2);
// One of the certifications expired.
assert_eq!(
ka.valid_certifications_by_key(p, t2, bob_primary).count(),
1);
assert_eq!(
ka.active_certifications_by_key(p, t2, bob_primary).count(),
1);
Ok(())
}
fn key_amalgamation_valid_third_party_revocations_by_key(
reason: ReasonForRevocation)
-> Result<()>
{
// Hard revocations are returned independent of the reference
// time and independent of their expiration. They are always
// live.
let soft = reason.revocation_type() == RevocationType::Soft;
// Alice and Bob revoke Carol's certificate. We then check
// that valid_third_party_revocations_by_key returns them.
let p = &crate::policy::StandardPolicy::new();
// $ date -u -d '2024-01-02 13:00' +%s
let t0 = UNIX_EPOCH + Duration::new(1704200400, 0);
// $ date -u -d '2024-01-02 14:00' +%s
let t1 = UNIX_EPOCH + Duration::new(1704204000, 0);
// $ date -u -d '2024-01-02 15:00' +%s
let t2 = UNIX_EPOCH + Duration::new(1704207600, 0);
let (alice, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid("<alice@example.example>")
.generate()
.unwrap();
let alice_primary = alice.primary_key().key();
let (bob, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid("<bob@example.example>")
.generate()
.unwrap();
let bob_primary = bob.primary_key().key();
let carol_userid = "<carol@example.example>";
let (carol, _) = CertBuilder::new()
.set_creation_time(t0)
.add_userid(carol_userid)
.generate()
.unwrap();
let ka = alice.primary_key();
assert_eq!(
ka.valid_third_party_revocations_by_key(p, None, alice_primary).count(),
0);
// Alice has not revoked Bob's certificate.
let ka = bob.primary_key();
assert_eq!(
ka.valid_third_party_revocations_by_key(p, None, alice_primary).count(),
0);
// Alice has not revoked Carol's certificate.
let ka = carol.primary_key();
assert_eq!(
ka.valid_third_party_revocations_by_key(p, None, alice_primary).count(),
0);
// Have Alice revoke Carol's revoke at t1.
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let rev = SignatureBuilder::new(SignatureType::KeyRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(
reason, b"")?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(rev)?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.other_revocations().count(), 1);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, alice_primary).count(),
if soft { 0 } else { 1 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, alice_primary).count(),
1);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, bob_primary).count(),
0);
// Have Alice revoke Carol's certificate at t1 (again).
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let rev = SignatureBuilder::new(SignatureType::KeyRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(reason, b"")?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(rev)?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.other_revocations().count(), 2);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, alice_primary).count(),
if soft { 0 } else { 2 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, alice_primary).count(),
2);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, alice_primary).count(),
2);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, bob_primary).count(),
0);
// Have Alice revoke Carol's certificate at t2.
let mut alice_signer = alice_primary
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let rev = SignatureBuilder::new(SignatureType::KeyRevocation)
.set_signature_creation_time(t2)?
.set_reason_for_revocation(reason, b"")?
.sign_direct_key(
&mut alice_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(rev)?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.other_revocations().count(), 3);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, alice_primary).count(),
if soft { 0 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, alice_primary).count(),
if soft { 2 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, bob_primary).count(),
0);
// Have Bob revoke Carol's certificate at t1 and have it expire at t2.
let mut bob_signer = bob.primary_key()
.key()
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let rev = SignatureBuilder::new(SignatureType::KeyRevocation)
.set_signature_creation_time(t1)?
.set_signature_validity_period(t2.duration_since(t1)?)?
.set_reason_for_revocation(reason, b"")?
.sign_direct_key(
&mut bob_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(rev)?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(ka.other_revocations().count(), 4);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, alice_primary).count(),
if soft { 0 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, alice_primary).count(),
if soft { 2 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, bob_primary).count(),
if soft { 0 } else { 1 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, bob_primary).count(),
1);
// It expired.
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, bob_primary).count(),
if soft { 0 } else { 1 });
// Have Bob revoke Carol's certificate at t1 again. This
// time don't have it expire.
let mut bob_signer = bob.primary_key()
.key()
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let rev = SignatureBuilder::new(SignatureType::KeyRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(reason, b"")?
.sign_direct_key(
&mut bob_signer,
carol.primary_key().key())?;
let carol = carol.insert_packets(rev)?;
// Check that it is returned.
let ka = carol.primary_key();
assert_eq!(
ka.other_revocations().count(), 5);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, alice_primary).count(),
if soft { 0 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, alice_primary).count(),
if soft { 2 } else { 3 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, alice_primary).count(),
3);
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t0, bob_primary).count(),
if soft { 0 } else { 2 });
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t1, bob_primary).count(),
2);
// One of the revocations expired.
assert_eq!(
ka.valid_third_party_revocations_by_key(p, t2, bob_primary).count(),
if soft { 1 } else { 2 });
Ok(())
}
#[test]
fn key_amalgamation_valid_third_party_revocations_by_key_soft()
-> Result<()>
{
key_amalgamation_valid_third_party_revocations_by_key(
ReasonForRevocation::KeyRetired)
}
#[test]
fn key_amalgamation_valid_third_party_revocations_by_key_hard()
-> Result<()>
{
key_amalgamation_valid_third_party_revocations_by_key(
ReasonForRevocation::KeyCompromised)
}
}