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
//! Components, their associated signatures, and some useful methods.
//!
//! Whereas a [`ComponentBundle`] owns a `Component` and its
//! associated [`Signature`]s, a [`ComponentAmalgamation`] references
//! a `ComponentBundle` and its containing [`Cert`]. This additional
//! context means that a `ComponentAmalgamation` can implement more of
//! OpenPGP's high-level semantics than a `ComponentBundle` can. For
//! instance, most of the information about a primary key, such as its
//! capabilities, is on the primary User ID's binding signature. A
//! `ComponentAmalgamation` can find the certificate's primary User
//! ID; a `ComponentBundle` can't. Similarly, when looking up a
//! subpacket, if it isn't present in the component's binding
//! signature, then an OpenPGP implementation [is supposed to] consult
//! the certificate's direct key signatures. A
//! `ComponentAmalgamation` has access to this information; a
//! `ComponentBundle` doesn't.
//!
//! Given the limitations of a `ComponentBundle`, it would seem more
//! useful to just change it to include a reference to its containing
//! certificate. That change would make `ComponentAmalgamation`s
//! redundant. Unfortunately, this isn't possible, because it would
//! result in a self-referential data structure, which Rust doesn't
//! allow. To understand how this arises, consider a certificate `C`,
//! which contains a `ComponentBundle` `B`. If `B` contains a
//! reference to `C`, then `C` references itself, because `C` contains
//! `B`!
//!
//! ```text
//! Cert:[ Bundle:[ &Cert ] ]
//! ^ |
//! `------------'
//! ```
//!
//! # Policy
//!
//! Although a `ComponentAmalgamation` contains the information
//! necessary to realize high-level OpenPGP functionality, components
//! can have multiple self signatures, and functions that consult the
//! binding signature need to determine the best one to use. There
//! are two main concerns here.
//!
//! First, we need to protect the user from forgeries. As attacks
//! improve, cryptographic algorithms that were once considered secure
//! now provide insufficient security margins. For instance, in 2007
//! it was possible to find [MD5 collisions] using just a few seconds
//! of computing time on a desktop computer. Sequoia provides a
//! flexible mechanism, called [`Policy`] objects, that allow users to
//! implement this type of filtering: before a self signature is used,
//! a policy object is queried to determine whether the `Signature`
//! should be rejected. If so, then it is skipped.
//!
//! Second, we need an algorithm to determine the most appropriate
//! self signature. Obvious non-candidate self signatures are self
//! signatures whose creation time is in the future. We don't assume
//! that these self signatures are bad per se, but that they represent
//! a policy that should go into effect some time in the future.
//!
//! We extend this idea of a self signature representing a policy for
//! a certain period of time to all self signatures. In particular,
//! Sequoia takes the view that *a binding signature represents a
//! policy that is valid from its creation time until its expiry*.
//! Thus, when considering what self signature to use, we need a
//! reference time. Given the reference time, we then use the self
//! signature that was in effect at that time, i.e., the most recent,
//! non-expired, non-revoked self signature that was created at or
//! prior to the reference time. In other words, we ignore self
//! signatures created after the reference time. We take the position
//! that if the certificate holder wants a new policy to apply to
//! existing signatures, then the new self signature should be
//! backdated, and existing self signatures revoked, if necessary.
//!
//! Consider evaluating a signature over a document. Sequoia's
//! [streaming verifier] uses the signature's creation time as the
//! reference time. Thus, if the signature was created on June 9th,
//! 2011, then, when evaluating that signature, the streaming verifier
//! uses a self signature that was live at that time, since that was
//! the self signature that represented the signer's policy at the
//! time the signature over the document was created.
//!
//! A consequence of this approach is that even if the self signature
//! were considered expired at the time the signature was evaluated
//! (e.g., "now"), this fact doesn't invalidate the signature. That
//! is, a self signature's lifetime does not impact a signature's
//! lifetime; a signature's lifetime is defined by its own creation
//! time and expiry. Similarly, a key's lifetime is defined by its
//! own creation time and expiry.
//!
//! This interpretation of lifetimes removes a major disadvantage that
//! comes with fast rotation of subkeys: if an implementation binds
//! the lifetime of signatures to the signing key, and the key
//! expires, then old signatures are considered invalid. Consider a
//! user who generates a new signature subkey each week, and sets it
//! to expire after exactly one week. If we use the policy that the
//! signature is only valid while the key *and* the self signature are
//! live, then if someone checks the signature a week after receiving
//! it, the signature will be considered invalid, because the key has
//! expired. The practical result is that all old messages from this
//! user will be considered invalid! Unfortunately, this will result
//! in users becoming accustomed to seeing invalid signatures, and
//! cause them to be less suspcious of them.
//!
//! Sequoia's low-level mechanisms support this interpretation of self
//! signatures, but they do *not* enforce it. It is still possible to
//! realize other policies using this low-level API.
//!
//! The possibility of abuse of this interpretation of signature
//! lifetimes is limited. If a key has been compromised, then the
//! right thing to do is to revoke it. Expiry doesn't help: the
//! attacker can simply create self-signatures that say whatever she
//! wants. Assuming the secret key material has not been compromised,
//! then an attacker could still reuse a message that would otherwise
//! be considered expired. However, the attacker will not be able to
//! change the signature's creation time, so, assuming a mail context
//! and MUAs that check that the time in the message's headers matches
//! the signature's creation time, the mails will appear old.
//! Further, this type of attack will be mitigated by the proposed
//! "[Intended Recipients]" subpacket, which more tightly binds the
//! message to its context.
//!
//! # [`ValidComponentAmalgamation`]
//!
//! Most operations need to query a `ComponentAmalgamation` for
//! multiple pieces of information. Accidentally using a different
//! `Policy` or a different reference time for one of the queries is
//! easy, especially when the queries are spread across multiple
//! functions. Further, using `None` for the reference time can
//! result in subtle timing bugs as each function translates it to the
//! current time on demand. In these cases, the correct approach
//! would be for the user of the library to get the current time at
//! the start of the operation. But, this is less convenient.
//! Finally, passing a `Policy` and a reference time to most function
//! calls clutters the code.
//!
//! To mitigate these issues, we have a separate data structure,
//! `ValidComponentAmalgamation`, which combines a
//! `ComponetAmalgamation`, a `Policy` and a reference time. It
//! implements methods that require a `Policy` and reference time, but
//! instead of requiring the caller to pass them in, it uses the ones
//! embedded in the data structure. Further, when the
//! `ValidComponentAmalgamation` constructor is passed `None` for the
//! reference time, it eagerly stores the current time, and uses that
//! for all operations. This approach elegantly solves all of the
//! aforementioned problems.
//!
//! # Lifetimes
//!
//! `ComponentAmalgamation` autoderefs to `ComponentBundle`.
//! Unfortunately, due to the definition of the [`Deref` trait],
//! `ComponentBundle` is assigned the same lifetime as
//! `ComponentAmalgamation`. However, it's lifetime is actually `'a`.
//! Particularly when using combinators like [`std::iter::map`], the
//! `ComponentBundle`'s lifetime is longer. Consider the following
//! code, which doesn't compile:
//!
//! ```compile_fail
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # 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()?;
//! cert.userids()
//! .map(|ua| {
//! // Use auto deref to get the containing `&ComponentBundle`.
//! let b: &ComponentBundle<_> = &ua;
//! b
//! })
//! .collect::<Vec<&UserID>>();
//! # Ok(()) }
//! ```
//!
//! Compiling it results in the following error:
//!
//! > `b` returns a value referencing data owned by the current
//! > function
//!
//! This error occurs because the `Deref` trait says that the lifetime
//! of the target, i.e., `&ComponentBundle`, is bounded by `ua`'s
//! lifetime, whose lifetime is indeed limited to the closure. But,
//! `&ComponentBundle` is independent of `ua`; it is a copy of the
//! `ComponentAmalgamation`'s reference to the `ComponentBundle` whose
//! lifetime is `'a`! Unfortunately, this can't be expressed using
//! `Deref`. But, it can be done using separate methods as shown
//! below for the [`ComponentAmalgamation::component`] method:
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # 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()?;
//! cert.userids()
//! .map(|ua| {
//! // ua's lifetime is this closure. But `component()`
//! // returns a reference whose lifetime is that of
//! // `cert`.
//! ua.component()
//! })
//! .collect::<Vec<&UserID>>();
//! # Ok(()) }
//! ```
//!
//! [`ComponentBundle`]: super::bundle
//! [`Signature`]: crate::packet::signature
//! [`Cert`]: super
//! [is supposed to]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
//! [`std::iter::map`]: std::iter::Map
//! [MD5 collisions]: https://en.wikipedia.org/wiki/MD5
//! [`Policy`]: crate::policy::Policy
//! [streaming verifier]: crate::parse::stream
//! [Intended Recipients]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09.html#name-intended-recipient-fingerpr
//! [signature expirations]: https://tools.ietf.org/html/rfc4880#section-5.2.3.10
//! [`Deref` trait]: std::ops::Deref
//! [`ComponentAmalgamation::component`]: ComponentAmalgamation::component()
use std::time;
use std::time::{
Duration,
SystemTime,
};
use std::clone::Clone;
use std::borrow::Borrow;
use crate::{
cert::prelude::*,
crypto::{Signer, hash::{Hash, Digest}},
Error,
KeyHandle,
packet,
packet::{
Signature,
Unknown,
UserAttribute,
UserID,
},
Result,
policy::{
HashAlgoSecurity,
Policy,
},
seal,
types::{
AEADAlgorithm,
CompressionAlgorithm,
Features,
HashAlgorithm,
KeyServerPreferences,
RevocationKey,
RevocationStatus,
RevocationType,
SignatureType,
SymmetricAlgorithm,
},
};
mod iter;
pub use iter::{
ComponentAmalgamationIter,
UnknownComponentAmalgamationIter,
UserAttributeAmalgamationIter,
UserIDAmalgamationIter,
ValidComponentAmalgamationIter,
ValidUserAttributeAmalgamationIter,
ValidUserIDAmalgamationIter,
};
pub mod key;
/// Embeds a policy and a reference time in an amalgamation.
///
/// This is used to turn a [`ComponentAmalgamation`] into a
/// [`ValidComponentAmalgamation`], and a [`KeyAmalgamation`] into a
/// [`ValidKeyAmalgamation`].
///
/// A certificate or a component is considered valid if:
///
/// - It has a self signature that is live at time `t`.
///
/// - The policy considers it acceptable.
///
/// - The certificate is valid.
///
/// # 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
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::{Policy, StandardPolicy};
///
/// const POLICY: &dyn Policy = &StandardPolicy::new();
///
/// fn f(ua: UserIDAmalgamation) -> openpgp::Result<()> {
/// let ua = ua.with_policy(POLICY, None)?;
/// // ...
/// # Ok(())
/// }
/// # fn main() -> openpgp::Result<()> {
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// # f(ua);
/// # Ok(())
/// # }
/// ```
///
pub trait ValidateAmalgamation<'a, C: 'a>: seal::Sealed {
/// The type returned by `with_policy`.
///
/// This is either a [`ValidComponentAmalgamation`] or
/// a [`ValidKeyAmalgamation`].
///
type V;
/// Uses the specified `Policy` and reference time with the amalgamation.
///
/// If `time` is `None`, the current time is used.
fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized;
}
/// Applies a policy to an amalgamation.
///
/// This is an internal variant of `ValidateAmalgamation`, which
/// allows validating a component for an otherwise invalid
/// certificate. See `ValidComponentAmalgamation::primary` for an
/// explanation.
trait ValidateAmalgamationRelaxed<'a, C: 'a> {
/// The type returned by `with_policy`.
type V;
/// Changes the amalgamation's policy.
///
/// If `time` is `None`, the current time is used.
///
/// If `valid_cert` is `false`, then this does not also check
/// whether the certificate is valid; it only checks whether the
/// component is valid. Normally, this should be `true`. This
/// option is only expose to allow breaking an infinite recursion:
///
/// - To check if a certificate is valid, we check if the
/// primary key is valid.
///
/// - To check if the primary key is valid, we need the primary
/// key's self signature
///
/// - To find the primary key's self signature, we need to find
/// the primary user id
///
/// - To find the primary user id, we need to check if the user
/// id is valid.
///
/// - To check if the user id is valid, we need to check that
/// the corresponding certificate is valid.
fn with_policy_relaxed<T>(self, policy: &'a dyn Policy, time: T,
valid_cert: bool) -> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized;
}
/// Methods for valid amalgamations.
///
/// The methods exposed by a `ValidComponentAmalgamation` are similar
/// to those exposed by a `ComponentAmalgamation`, but the policy and
/// reference time are included in the `ValidComponentAmalgamation`.
/// This helps prevent using different policies or different reference
/// times when using a component, which can easily happen when the
/// checks span multiple functions.
///
/// # 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 ValidAmalgamation<'a, C: 'a>: seal::Sealed
{
/// Maps the given function over binding and direct key signature.
///
/// Makes `f` consider both the binding signature and the direct
/// key signature. Information in the binding signature takes
/// precedence over the direct key signature. See also [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
fn map<F: Fn(&'a Signature) -> Option<T>, T>(&self, f: F) -> Option<T> {
f(self.binding_signature())
.or_else(|| self.direct_key_signature().ok().and_then(f))
}
/// Returns the valid amalgamation's associated certificate.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// fn f(ua: &ValidUserIDAmalgamation) {
/// let cert = ua.cert();
/// // ...
/// }
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let fpr = cert.fingerprint();
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// # assert_eq!(ua.cert().fingerprint(), fpr);
/// # f(&ua.with_policy(p, None)?);
/// # Ok(())
/// # }
/// ```
fn cert(&self) -> &ValidCert<'a>;
/// Returns the amalgamation's reference time.
///
/// # Examples
///
/// ```
/// # use std::time::{SystemTime, Duration, UNIX_EPOCH};
/// #
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// fn f(ua: &ValidUserIDAmalgamation) {
/// let t = ua.time();
/// // ...
/// }
/// # fn main() -> openpgp::Result<()> {
/// # let p = &StandardPolicy::new();
/// # let t = UNIX_EPOCH + Duration::from_secs(1554542220);
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .set_creation_time(t)
/// # .generate()?;
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// # let ua = ua.with_policy(p, t)?;
/// # assert_eq!(t, ua.time());
/// # f(&ua);
/// # Ok(())
/// # }
/// ```
fn time(&self) -> SystemTime;
/// Returns the amalgamation's policy.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::{Policy, StandardPolicy};
/// #
/// fn f(ua: &ValidUserIDAmalgamation) {
/// let policy = ua.policy();
/// // ...
/// }
/// # fn main() -> openpgp::Result<()> {
/// # let p: &dyn Policy = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// # let ua = ua.with_policy(p, None)?;
/// # assert!(std::ptr::eq(p, ua.policy()));
/// # f(&ua);
/// # Ok(())
/// # }
/// ```
fn policy(&self) -> &'a dyn Policy;
/// Returns the component's binding signature as of the reference time.
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::{Policy, StandardPolicy};
/// #
/// fn f(ua: &ValidUserIDAmalgamation) {
/// let sig = ua.binding_signature();
/// // ...
/// }
/// # fn main() -> openpgp::Result<()> {
/// # let p: &dyn Policy = &StandardPolicy::new();
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// # let ua = ua.with_policy(p, None)?;
/// # f(&ua);
/// # Ok(())
/// # }
/// ```
fn binding_signature(&self) -> &'a Signature;
/// Returns the certificate's direct key signature as of the
/// reference time, if any.
///
/// Subpackets on direct key signatures apply to all components of
/// the certificate, cf. [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
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::{Policy, StandardPolicy};
/// #
/// fn f(ua: &ValidUserIDAmalgamation) {
/// let sig = ua.direct_key_signature();
/// // ...
/// }
/// # 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 ua = cert.userids().nth(0).expect("User IDs");
/// # assert!(std::ptr::eq(ua.direct_key_signature().unwrap(),
/// # cert.direct_key_signature().unwrap()));
/// # f(&ua);
/// # Ok(())
/// # }
/// ```
fn direct_key_signature(&self) -> Result<&'a Signature> {
self.cert().cert.primary.binding_signature(self.policy(), self.time())
}
/// Returns the component's revocation status as of the amalgamation's
/// reference time.
///
/// This does *not* check whether the certificate has been
/// revoked. For that, use `Cert::revocation_status()`.
///
/// Note, as per [RFC 4880], a key is considered to be revoked at
/// some time if there were no soft revocations created as of that
/// time, and no hard revocations:
///
/// > If a key has been revoked because of a compromise, all signatures
/// > created by that key are suspect. However, if it was merely
/// > superseded or retired, old signatures are still valid.
///
/// [RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.23
///
/// # Examples
///
/// ```
/// # 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::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// # let cert = cert.with_policy(p, None)?;
/// # let ua = cert.userids().nth(0).expect("User IDs");
/// match ua.revocation_status() {
/// RevocationStatus::Revoked(revs) => {
/// // The certificate holder revoked the User ID.
/// # unreachable!();
/// }
/// RevocationStatus::CouldBe(revs) => {
/// // There are third-party revocations. You still need
/// // to check that they are valid (this is necessary,
/// // because without the Certificates are not normally
/// // available to Sequoia).
/// # unreachable!();
/// }
/// RevocationStatus::NotAsFarAsWeKnow => {
/// // We have no evidence that the User ID is revoked.
/// }
/// }
/// # Ok(())
/// # }
/// ```
fn revocation_status(&self) -> RevocationStatus<'a>;
/// Returns a list of any designated revokers for this component.
///
/// This function returns the designated revokers listed on the
/// components's binding signatures and the certificate's direct
/// key signatures.
///
/// Note: the returned list is deduplicated.
///
/// # Examples
///
/// ```
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::RevocationKey;
///
/// # fn main() -> Result<()> {
/// let p = &StandardPolicy::new();
///
/// let (alice, _) =
/// CertBuilder::general_purpose(None, Some("alice@example.org"))
/// .generate()?;
/// // Make Alice a designated revoker for Bob.
/// let (bob, _) =
/// CertBuilder::general_purpose(None, Some("bob@example.org"))
/// .set_revocation_keys(vec![(&alice).into()])
/// .generate()?;
///
/// // Make sure Alice is listed as a designated revoker for Bob's
/// // primary user id.
/// assert_eq!(bob.with_policy(p, None)?.primary_userid()?
/// .revocation_keys().collect::<Vec<&RevocationKey>>(),
/// vec![&(&alice).into()]);
///
/// // Make sure Alice is listed as a designated revoker for Bob's
/// // encryption subkey.
/// assert_eq!(bob.with_policy(p, None)?
/// .keys().for_transport_encryption().next().unwrap()
/// .revocation_keys().collect::<Vec<&RevocationKey>>(),
/// vec![&(&alice).into()]);
/// # Ok(()) }
/// ```
fn revocation_keys(&self)
-> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>;
}
/// A certificate component, its associated data, and useful methods.
///
/// [`Cert::userids`], [`ValidCert::primary_userid`], [`Cert::user_attributes`], and
/// [`Cert::unknowns`] return `ComponentAmalgamation`s.
///
/// `ComponentAmalgamation` implements [`ValidateAmalgamation`], which
/// allows you to turn a `ComponentAmalgamation` into a
/// [`ValidComponentAmalgamation`] using
/// [`ComponentAmalgamation::with_policy`].
///
/// [See the module's documentation] for more details.
///
/// # 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();
/// // Iterate over all User IDs.
/// for ua in cert.userids() {
/// // ua is a `ComponentAmalgamation`, specifically, a `UserIDAmalgamation`.
/// }
/// # Ok(())
/// # }
/// ```
///
/// [`Cert`]: super::Cert
/// [`Cert::userids`]: super::Cert::userids()
/// [`ValidCert::primary_userid`]: super::ValidCert::primary_userid()
/// [`Cert::user_attributes`]: super::Cert::user_attributes()
/// [`Cert::unknowns`]: super::Cert::unknowns()
/// [`ComponentAmalgamation::with_policy`]: ValidateAmalgamation::with_policy()
/// [See the module's documentation]: self
#[derive(Debug, PartialEq)]
pub struct ComponentAmalgamation<'a, C> {
cert: &'a Cert,
bundle: &'a ComponentBundle<C>,
}
assert_send_and_sync!(ComponentAmalgamation<'_, C> where C);
/// A User ID and its associated data.
///
/// A specialized version of [`ComponentAmalgamation`].
///
pub type UserIDAmalgamation<'a> = ComponentAmalgamation<'a, UserID>;
/// A User Attribute and its associated data.
///
/// A specialized version of [`ComponentAmalgamation`].
///
pub type UserAttributeAmalgamation<'a>
= ComponentAmalgamation<'a, UserAttribute>;
/// An Unknown component and its associated data.
///
/// A specialized version of [`ComponentAmalgamation`].
///
pub type UnknownComponentAmalgamation<'a>
= ComponentAmalgamation<'a, Unknown>;
// 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, C> Clone for ComponentAmalgamation<'a, C> {
fn clone(&self) -> Self {
Self {
cert: self.cert,
bundle: self.bundle,
}
}
}
impl<'a, C> std::ops::Deref for ComponentAmalgamation<'a, C> {
type Target = ComponentBundle<C>;
fn deref(&self) -> &Self::Target {
self.bundle
}
}
impl<'a, C> ComponentAmalgamation<'a, C> {
/// Creates a new amalgamation.
pub(crate) fn new(cert: &'a Cert, bundle: &'a ComponentBundle<C>) -> Self
{
Self {
cert,
bundle,
}
}
/// Returns the component's associated certificate.
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// #
/// # fn main() -> openpgp::Result<()> {
/// # let (cert, _) =
/// # CertBuilder::general_purpose(None, Some("alice@example.org"))
/// # .generate()?;
/// for u in cert.userids() {
/// // It's not only an identical `Cert`, it's the same one.
/// assert!(std::ptr::eq(u.cert(), &cert));
/// }
/// # Ok(()) }
/// ```
pub fn cert(&self) -> &'a Cert {
self.cert
}
/// Selects a binding signature.
///
/// Uses the provided policy and reference time to select an
/// appropriate binding signature.
///
/// Note: this function is not exported. Users of this interface
/// should do: ca.with_policy(policy, time)?.binding_signature().
fn binding_signature<T>(&self, policy: &dyn Policy, time: T)
-> Result<&'a Signature>
where T: Into<Option<time::SystemTime>>
{
let time = time.into().unwrap_or_else(crate::now);
self.bundle.binding_signature(policy, time)
}
/// Returns this amalgamation's bundle.
///
/// Note: although `ComponentAmalgamation` derefs to a
/// `&ComponentBundle`, this method provides a more accurate
/// lifetime, which is helpful when returning the reference from a
/// function. [See the module's documentation] for more details.
///
/// [See the module's documentation]: self
///
/// # Examples
///
/// ```
/// # fn main() -> sequoia_openpgp::Result<()> {
/// # 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()?;
/// cert.userids()
/// .map(|ua| {
/// // The following doesn't work:
/// //
/// // let b: &ComponentBundle<_> = &ua; b
/// //
/// // Because ua's lifetime is this closure and autoderef
/// // assigns `b` the same lifetime as `ua`. `bundle()`,
/// // however, returns a reference whose lifetime is that
/// // of `cert`.
/// ua.bundle()
/// })
/// .collect::<Vec<&ComponentBundle<_>>>();
/// # Ok(()) }
/// ```
pub fn bundle(&self) -> &'a ComponentBundle<C> {
self.bundle
}
/// Returns this amalgamation's component.
///
/// Note: although `ComponentAmalgamation` derefs to a
/// `&Component` (via `&ComponentBundle`), this method provides a
/// more accurate lifetime, which is helpful when returning the
/// reference from a function. [See the module's documentation]
/// for more details.
///
/// [See the module's documentation]: self
pub fn component(&self) -> &'a C {
self.bundle().component()
}
/// The component's self-signatures.
pub fn self_signatures(&self) -> impl Iterator<Item=&'a Signature> + Send + Sync {
self.bundle().self_signatures2()
}
/// The component's third-party certifications.
pub fn certifications(&self) -> impl Iterator<Item=&'a Signature> + Send + Sync {
self.bundle().certifications2()
}
/// Returns third-party certifications that appear to issued by
/// any of the specified keys.
///
/// A certification is returned if one of the provided key handles
/// matches an [Issuer subpacket] or [Issuer Fingerprint
/// subpacket] in the certification.
///
/// [Issuer subpacket]: https://datatracker.ietf.org/doc/html/rfc4880#section-5.2.3.5
/// [Issuer Fingerprint subpacket]: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-issuer-fingerprint
///
/// This function does not check that a certification is valid.
/// It can't. To check that a certification was actually issued
/// by a specific key, we also need a policy and the public key,
/// which we don't have. To only get valid certifications, use
/// [`UserIDAmalgamation::valid_certifications_by_key`] or
/// [`UserIDAmalgamation::active_certifications_by_key`] instead
/// of this function.
pub fn certifications_by_key<'b>(&'b self, issuers: &'b [ KeyHandle ])
-> impl Iterator<Item=&'a Signature> + Send + Sync + 'b
{
self.certifications().filter(|certification| {
certification.get_issuers().into_iter().any(|certification_issuer| {
issuers.iter().any(|issuer| {
certification_issuer.aliases(issuer)
})
})
})
}
/// The component's revocations that were issued by the
/// certificate holder.
pub fn self_revocations(&self) -> impl Iterator<Item=&'a Signature> + Send + Sync {
self.bundle().self_revocations2()
}
/// The component's revocations that were issued by other
/// certificates.
pub fn other_revocations(&self) -> impl Iterator<Item=&'a Signature> + Send + Sync {
self.bundle().other_revocations2()
}
/// Returns all of the component's signatures.
pub fn signatures(&self)
-> impl Iterator<Item = &'a Signature> + Send + Sync {
self.bundle().signatures()
}
// Used to implement
// [`UserIDAmalgamation::valid_certifications_by_key`],
// [`KeyAmalgamation::valid_certifications_by_key`],
// [`UserIDAmalgamation::active_certifications_by_key`], and
// [`KeyAmalgamation::active_certifications_by_key`].
fn valid_certifications_by_key_<'b, F>(
&self,
policy: &'a dyn Policy,
reference_time: Option<time::SystemTime>,
issuer: &'a packet::Key<packet::key::PublicParts,
packet::key::UnspecifiedRole>,
only_active: bool,
certifications: impl Iterator<Item=&'b Signature> + Send + Sync,
verify_certification: F)
-> impl Iterator<Item=&'b Signature> + Send + Sync
where
F: Fn(&Signature) -> Result<()>
{
let reference_time = reference_time.unwrap_or_else(crate::now);
let issuer_handle = issuer.key_handle();
let issuer_handle = &issuer_handle;
let mut certifications: Vec<(&Signature, _)> = certifications
.filter_map(|certification| {
// Extract the signature's creation time. Ignore
// certifications without a creation time: those are
// malformed.
certification
.signature_creation_time()
.map(|ct| (certification, ct))
})
.filter(|(certification, _ct)| {
// Filter out certifications that definitely aren't
// from `issuer`.
certification.get_issuers().into_iter().any(|sig_issuer| {
sig_issuer.aliases(issuer_handle)
})
})
.map(|(certification, ct)| {
let hard = if matches!(certification.typ(),
SignatureType::KeyRevocation
| SignatureType::SubkeyRevocation
| SignatureType::CertificationRevocation)
{
certification.reason_for_revocation()
.map(|(reason, _text)| {
reason.revocation_type() == RevocationType::Hard
})
// Interpret an unspecified reason as a hard
// revocation.
.unwrap_or(true)
} else {
false
};
(certification, ct, hard)
})
.filter(|(_certification, ct, hard)| {
// Skip certifications created after the reference
// time, unless they are hard revocations.
*ct <= reference_time || *hard
})
.filter(|(certification, ct, hard)| {
// Check that the certification is not expired as of
// the reference time.
if *hard {
// Hard revocations don't expire.
true
} else if let Some(validity)
= certification.signature_validity_period()
{
if validity == Duration::new(0, 0) {
// "If this is not present or has a value of
// zero, it never expires."
//
// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-key-expiration-time
true
} else {
// "the number of seconds after the signature
// creation time that the signature expires"
//
// Assume validity = 1 second, then:
//
// expiry time reference time status
// ----------- -------------- ------
// > ct live
// ct + 1 = ct + 1 expired
// < ct + 2 expired
*ct + validity > reference_time
}
} else {
true
}
})
.filter(|(_certification, ct, hard)| {
// Make sure the certification was created after the
// certificate, unless they are hard revocations.
self.cert.primary_key().creation_time() <= *ct || *hard
})
.filter(|(certification, _ct, _hard)| {
// Make sure the certification conforms to the policy.
policy
.signature(certification,
HashAlgoSecurity::CollisionResistance)
.is_ok()
})
.map(|(certification, ct, _hard)| (certification, ct))
.collect();
// Sort the certifications by creation time so that the newest
// certifications come first.
certifications.sort_unstable_by(|(_, a), (_, b)| {
a.cmp(b).reverse()
});
// Check that the issuer actually made the signatures, and
// collect the most recent certifications.
let mut valid = Vec::new();
for (certification, ct) in certifications.into_iter() {
if only_active {
if let Some((_active, active_ct)) = valid.get(0) {
if *active_ct != ct {
// This certification is further in the past.
// We're done.
break;
}
}
}
if let Ok(()) = verify_certification(certification) {
valid.push((certification, ct));
}
}
valid.into_iter()
.map(|(certification, _creation_time)| certification)
.collect::<Vec<&Signature>>()
.into_iter()
}
}
macro_rules! impl_with_policy {
($func:ident, $value:ident $(, $arg:ident: $type:ty )*) => {
fn $func<T>(self, policy: &'a dyn Policy, time: T, $($arg: $type, )*)
-> Result<Self::V>
where T: Into<Option<time::SystemTime>>,
Self: Sized
{
let time = time.into().unwrap_or_else(crate::now);
if $value {
self.cert.with_policy(policy, time)?;
}
let binding_signature = self.binding_signature(policy, time)?;
let cert = self.cert;
// We can't do `Cert::with_policy` as that would
// result in infinite recursion. But at this point,
// we know the certificate is valid (unless the caller
// doesn't care).
Ok(ValidComponentAmalgamation {
ca: self,
cert: ValidCert {
cert,
policy,
time,
},
binding_signature,
})
}
}
}
impl<'a, C> seal::Sealed for ComponentAmalgamation<'a, C> {}
impl<'a, C> ValidateAmalgamation<'a, C> for ComponentAmalgamation<'a, C> {
type V = ValidComponentAmalgamation<'a, C>;
impl_with_policy!(with_policy, true);
}
impl<'a, C> ValidateAmalgamationRelaxed<'a, C> for ComponentAmalgamation<'a, C> {
type V = ValidComponentAmalgamation<'a, C>;
impl_with_policy!(with_policy_relaxed, valid_cert, valid_cert: bool);
}
impl<'a> UserIDAmalgamation<'a> {
/// Returns a reference to the User ID.
///
/// Note: although `ComponentAmalgamation<UserID>` derefs to a
/// `&UserID` (via `&ComponentBundle`), this method provides a
/// more accurate lifetime, which is helpful when returning the
/// reference from a function. [See the module's documentation]
/// for more details.
///
/// [See the module's documentation]: self
pub fn userid(&self) -> &'a UserID {
self.component()
}
/// 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 [`UserIDAmalgamation`] and not
/// a [`ValidUserIDAmalgamation`], because a third-party
/// certification does not require the user ID to be self signed.
///
/// # Examples
///
/// Alice has certified that a certificate belongs to Bob on two
/// occasions. Whereas
/// [`UserIDAmalgamation::valid_certifications_by_key`] returns
/// both certifications,
/// [`UserIDAmalgamation::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 ua = bob.userids().next().expect("have a user id");
/// # assert_eq!(
/// # ua.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::GenericCertification)
/// # .set_signature_creation_time(ti)?
/// # .sign_userid_binding(
/// # &mut alice_signer,
/// # bob.primary_key().key(),
/// # &UserID::from(bob_userid))?;
/// # bob = bob.insert_packets(certification)?;
/// #
/// # let ua = bob.userids().next().expect("have a user id");
/// # assert_eq!(
/// # ua.valid_certifications_by_key(
/// # P, ti, alice.primary_key().key()).count(),
/// # i);
/// #
/// # assert_eq!(
/// # ua.active_certifications_by_key(
/// # P, ti, alice.primary_key().key()).count(),
/// # 1);
/// # }
/// let ua = bob.userids().next().expect("have user id");
///
/// let valid_certifications = ua.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 = ua.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 packet::Key<packet::key::PublicParts,
packet::key::UnspecifiedRole>>,
{
let reference_time = reference_time.into();
let issuer = issuer.into();
self.valid_certifications_by_key_(
policy, reference_time, issuer, false,
self.certifications(),
|sig| {
sig.clone().verify_userid_binding(
issuer,
self.cert.primary_key().key(),
self.userid())
})
}
/// Returns any active third-party certifications issued by the
/// specified key.
///
/// This function is like
/// [`UserIDAmalgamation::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 [`UserIDAmalgamation`] and not
/// a [`ValidUserIDAmalgamation`], because a third-party
/// certification does not require the user ID to be self signed.
///
/// # Examples
///
/// See the examples for
/// [`UserIDAmalgamation::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 packet::Key<packet::key::PublicParts,
packet::key::UnspecifiedRole>>,
{
let reference_time = reference_time.into();
let issuer = issuer.into();
self.valid_certifications_by_key_(
policy, reference_time, issuer, true,
self.certifications(),
|sig| {
sig.clone().verify_userid_binding(
issuer,
self.cert.primary_key().key(),
self.userid())
})
}
/// 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 live with respect to the reference time,
/// - it conforms to the policy, and
/// - the signature is cryptographically valid.
///
/// This method is implemented on a [`UserIDAmalgamation`] and not
/// a [`ValidUserIDAmalgamation`], because a third-party
/// revocation does not require the user ID to be self signed.
///
/// # Examples
///
/// Alice revokes a user ID on 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;
///
/// # // Alice has not certified Bob's User ID.
/// # let ua = bob.userids().next().expect("have a user id");
/// # assert_eq!(
/// # ua.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 certification = SignatureBuilder::new(SignatureType::CertificationRevocation)
/// # .set_signature_creation_time(t1)?
/// # .set_reason_for_revocation(
/// # ReasonForRevocation::UIDRetired, b"")?
/// # .sign_userid_binding(
/// # &mut alice_signer,
/// # bob.primary_key().key(),
/// # &UserID::from(bob_userid))?;
/// # let bob = bob.insert_packets([
/// # Packet::from(UserID::from(bob_userid)),
/// # Packet::from(certification),
/// # ])?;
/// let ua = bob.userids().next().expect("have user id");
///
/// let revs = ua.valid_third_party_revocations_by_key(
/// P, None, alice.primary_key().key());
/// // Alice revoked the User ID.
/// 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 packet::Key<packet::key::PublicParts,
packet::key::UnspecifiedRole>>,
{
let reference_time = reference_time.into();
let issuer = issuer.into();
self.valid_certifications_by_key_(
policy, reference_time, issuer, false,
self.other_revocations(),
|sig| {
sig.clone().verify_userid_revocation(
issuer,
self.cert.primary_key().key(),
self.userid())
})
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [draft-dkg-openpgp-1pa3pc] for details.
/// This can be used to address certificate flooding concerns.
///
/// A policy is needed, because the expiration is updated by
/// updating the current binding signatures.
///
/// [draft-dkg-openpgp-1pa3pc]: https://www.ietf.org/archive/id/draft-dkg-openpgp-1pa3pc-00.html
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # fn main() -> openpgp::Result<()> {
/// # use openpgp::cert::prelude::*;
/// # use openpgp::packet::signature::SignatureBuilder;
/// # use openpgp::types::*;
/// # let policy = &openpgp::policy::StandardPolicy::new();
/// let (alice, _) = CertBuilder::new()
/// .add_userid("alice@example.org")
/// .generate()?;
/// let mut alice_signer =
/// alice.primary_key().key().clone().parts_into_secret()?
/// .into_keypair()?;
///
/// let (bob, _) = CertBuilder::new()
/// .add_userid("bob@example.org")
/// .generate()?;
/// let mut bob_signer =
/// bob.primary_key().key().clone().parts_into_secret()?
/// .into_keypair()?;
/// let bob_pristine = bob.clone();
///
/// // Have Alice certify the binding between "bob@example.org" and
/// // Bob's key.
/// let alice_certifies_bob
/// = bob.userids().next().unwrap().userid().bind(
/// &mut alice_signer, &bob,
/// SignatureBuilder::new(SignatureType::GenericCertification))?;
/// let bob = bob.insert_packets(vec![alice_certifies_bob.clone()])?;
///
/// // Have Bob attest that certification.
/// let bobs_uid = bob.userids().next().unwrap();
/// let attestations =
/// bobs_uid.attest_certifications2(
/// policy,
/// None,
/// &mut bob_signer,
/// bobs_uid.certifications())?;
/// let bob = bob.insert_packets(attestations)?;
///
/// assert_eq!(bob.bad_signatures().count(), 0);
/// assert_eq!(bob.userids().next().unwrap().certifications().next(),
/// Some(&alice_certifies_bob));
/// # Ok(()) }
/// ```
pub fn attest_certifications2<T, C, S>(&self,
policy: &dyn Policy,
time: T,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where T: Into<Option<time::SystemTime>>,
C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
let time = time.into();
// Hash the components like in a binding signature.
let mut hash = HashAlgorithm::default().context()?;
self.cert().primary_key().hash(&mut hash);
self.userid().hash(&mut hash);
// Check if there is a previous attestation. If so, we need
// that to robustly override it.
let old = self.clone()
.with_policy(policy, time)
.ok()
.and_then(|v| v.attestation_key_signatures().next().cloned());
attest_certifications_common(hash, old, primary_signer, certifications)
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// This function is deprecated in favor of
/// [`UserIDAmalgamation::attest_certifications2`], which includes
/// a reference time parameter.
#[deprecated(note = "Use attest_certifications2 instead.")]
pub fn attest_certifications<C, S>(&self,
policy: &dyn Policy,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
self.attest_certifications2(
policy, None, primary_signer, certifications)
}
}
impl<'a> UserAttributeAmalgamation<'a> {
/// Returns a reference to the User Attribute.
///
/// Note: although `ComponentAmalgamation<UserAttribute>` derefs
/// to a `&UserAttribute` (via `&ComponentBundle`), this method
/// provides a more accurate lifetime, which is helpful when
/// returning the reference from a function. [See the module's
/// documentation] for more details.
///
/// [See the module's documentation]: self
pub fn user_attribute(&self) -> &'a UserAttribute {
self.component()
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [Section 5.2.3.30 of RFC 4880bis] for
/// details. This can be used to address certificate flooding
/// concerns.
///
/// A policy is needed, because the expiration is updated by
/// updating the current binding signatures.
///
/// [Section 5.2.3.30 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10.html#section-5.2.3.30
///
/// # Examples
///
/// See [`UserIDAmalgamation::attest_certifications#examples`].
///
/// [`UserIDAmalgamation::attest_certifications#examples`]: UserIDAmalgamation#examples
// The explicit link works around a bug in rustdoc.
pub fn attest_certifications2<T, C, S>(&self,
policy: &dyn Policy,
time: T,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where T: Into<Option<time::SystemTime>>,
C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
let time = time.into();
// Hash the components like in a binding signature.
let mut hash = HashAlgorithm::default().context()?;
self.cert().primary_key().hash(&mut hash);
self.user_attribute().hash(&mut hash);
// Check if there is a previous attestation. If so, we need
// that to robustly override it.
let old = self.clone()
.with_policy(policy, time)
.ok()
.and_then(|v| v.attestation_key_signatures().next().cloned());
attest_certifications_common(hash, old, primary_signer, certifications)
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// This function is deprecated in favor of
/// [`UserAttributeAmalgamation::attest_certifications2`], which
/// includes a reference time parameter.
#[deprecated(note = "Use attest_certifications2 instead.")]
pub fn attest_certifications<C, S>(&self,
policy: &dyn Policy,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
self.attest_certifications2(
policy, None, primary_signer, certifications)
}
}
/// Attests to third-party certifications.
#[allow(clippy::let_and_return)]
fn attest_certifications_common<C, S>(hash: Box<dyn Digest>,
old_attestation: Option<Signature>,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
use crate::{
packet::signature::{SignatureBuilder, subpacket::SubpacketArea},
serialize::MarshalInto,
};
let hash_algo = hash.algo();
let digest_size = hash.digest_size();
let mut attestations = Vec::new();
for certification in certifications.into_iter() {
let mut h = hash_algo.context()?;
certification.borrow().hash_for_confirmation(&mut h);
attestations.push(h.into_digest()?);
}
// Hashes SHOULD be sorted.
attestations.sort();
// All attestation signatures we generate for this component
// should have the same creation time. Fix it now. We also like
// our signatures to be newer than any existing signatures. Do so
// by using the old attestation as template.
let template = if let Some(old) = old_attestation {
let mut s: SignatureBuilder = old.into();
s.hashed_area_mut().clear();
s.unhashed_area_mut().clear();
s
} else {
// Backdate the signature a little so that we can immediately
// override it.
use crate::packet::signature::SIG_BACKDATE_BY;
let now = crate::now();
let mut creation_time =
now - time::Duration::new(SIG_BACKDATE_BY, 0);
// ... but don't backdate it further than the key's creation
// time, which would make it invalid.
let key_creation_time = primary_signer.public().creation_time();
if creation_time < key_creation_time {
// ... unless that would make it is later than now.
creation_time = key_creation_time.min(now);
}
let template = SignatureBuilder::new(SignatureType::AttestationKey)
.set_signature_creation_time(creation_time)?;
template
};
let template = template
.set_hash_algo(hash_algo)
// Important for size calculation.
.pre_sign(primary_signer)?;
// Compute the available space in the hashed area. For this,
// it is important that template.pre_sign has been called.
let available_space =
SubpacketArea::MAX_SIZE - template.hashed_area().serialized_len();
// Reserve space for the subpacket header, length and tag.
const SUBPACKET_HEADER_MAX_LEN: usize = 5 + 1;
// Compute the chunk size for each signature.
let digests_per_sig =
(available_space - SUBPACKET_HEADER_MAX_LEN) / digest_size;
// Now create the signatures.
let mut sigs = Vec::new();
for digests in attestations.chunks(digests_per_sig) {
sigs.push(
template.clone()
.set_attested_certifications(digests)?
.sign_hash(primary_signer, hash.clone())?);
}
if attestations.is_empty() {
// The certificate owner can withdraw attestations by issuing
// an empty attestation key signature.
assert!(sigs.is_empty());
sigs.push(
template
.set_attested_certifications(Option::<&[u8]>::None)?
.sign_hash(primary_signer, hash.clone())?);
}
Ok(sigs)
}
/// A `ComponentAmalgamation` plus a `Policy` and a reference time.
///
/// A `ValidComponentAmalgamation` combines a
/// [`ComponentAmalgamation`] with a [`Policy`] and a reference time.
/// This allows it to implement the [`ValidAmalgamation`] trait, which
/// provides methods that require a [`Policy`] and a reference time.
/// Although `ComponentAmalgamation` could implement these methods by
/// requiring that the caller explicitly pass them in, embedding them
/// in the `ValidComponentAmalgamation` helps ensure that multipart
/// operations, even those that span multiple functions, use the same
/// `Policy` and reference time.
///
/// A `ValidComponentAmalgamation` is typically obtained by
/// transforming a `ComponentAmalgamation` using
/// [`ValidateAmalgamation::with_policy`]. A
/// [`ComponentAmalgamationIter`] can also be changed to yield
/// `ValidComponentAmalgamation`s.
///
/// A `ValidComponentAmalgamation` 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* is live. If you care about that, then you need to
/// check it separately.
///
/// # Examples
///
/// Print out information about all non-revoked User IDs.
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// use openpgp::packet::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()?;
/// for u in cert.userids() {
/// // Create a `ValidComponentAmalgamation`. This may fail if
/// // there are no binding signatures that are accepted by the
/// // policy and that are live right now.
/// let u = u.with_policy(p, None)?;
///
/// // Before using the User ID, we still need to check that it is
/// // not revoked; `ComponentAmalgamation::with_policy` ensures
/// // that there is a valid *binding signature*, not that the
/// // `ComponentAmalgamation` is valid.
/// //
/// // Note: `ValidComponentAmalgamation::revocation_status` and
/// // `Preferences::preferred_symmetric_algorithms` 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.
/// //
/// // Note: we only check whether the User ID is not revoked. If
/// // we were using a key, we'd also want to check that it is alive.
/// // (Keys can expire, but User IDs cannot.)
/// if let RevocationStatus::Revoked(_revs) = u.revocation_status() {
/// // Revoked by the key owner. (If we care about
/// // designated revokers, then we need to check those
/// // ourselves.)
/// } else {
/// // Print information about the User ID.
/// eprintln!("{}: preferred symmetric algorithms: {:?}",
/// String::from_utf8_lossy(u.value()),
/// u.preferred_symmetric_algorithms());
/// }
/// }
/// # Ok(()) }
/// ```
///
/// [`Policy`]: crate::policy::Policy
#[derive(Debug)]
pub struct ValidComponentAmalgamation<'a, C> {
ca: ComponentAmalgamation<'a, C>,
cert: ValidCert<'a>,
// The binding signature at time `time`. (This is just a cache.)
binding_signature: &'a Signature,
}
assert_send_and_sync!(ValidComponentAmalgamation<'_, C> where C);
/// A Valid User ID and its associated data.
///
/// A specialized version of [`ValidComponentAmalgamation`].
///
pub type ValidUserIDAmalgamation<'a> = ValidComponentAmalgamation<'a, UserID>;
impl<'a> ValidUserIDAmalgamation<'a> {
/// Returns the userid's attested third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [Section 5.2.3.30 of RFC 4880bis] for
/// details. This can be used to address certificate flooding
/// concerns.
///
/// This method only returns signatures that are valid under the
/// current policy and are attested by the certificate holder.
///
/// [Section 5.2.3.30 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10.html#section-5.2.3.30
pub fn attested_certifications(&self)
-> impl Iterator<Item=&Signature> + Send + Sync
{
let mut hash_algo = None;
let digests: std::collections::HashSet<_> =
self.attestation_key_signatures()
.filter_map(|sig| {
sig.attested_certifications().ok()
.map(|digest_iter| (sig, digest_iter))
})
.flat_map(|(sig, digest_iter)| {
hash_algo = Some(sig.hash_algo());
digest_iter
})
.collect();
self.certifications()
.filter_map(move |sig| {
let mut hash = hash_algo.and_then(|a| a.context().ok())?;
sig.hash_for_confirmation(&mut hash);
let digest = hash.into_digest().ok()?;
if digests.contains(&digest[..]) {
Some(sig)
} else {
None
}
})
}
/// Returns set of active attestation key signatures.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Returns the set of signatures with the newest valid signature
/// creation time. Older signatures are not returned. The sum of
/// all digests in these signatures are the set of attested
/// third-party certifications.
///
/// This interface is useful for pruning old attestation key
/// signatures when filtering a certificate.
///
/// Note: This is a low-level interface. Consider using
/// [`ValidUserIDAmalgamation::attested_certifications`] to
/// iterate over all attested certifications.
///
/// [`ValidUserIDAmalgamation::attested_certifications`]: ValidUserIDAmalgamation#method.attested_certifications
// The explicit link works around a bug in rustdoc.
pub fn attestation_key_signatures(&'a self)
-> impl Iterator<Item=&'a Signature> + Send + Sync
{
let mut first = None;
// The newest valid signature will be returned first.
self.attestations()
// First, filter out any invalid (e.g. too new) signatures.
.filter(move |sig| self.cert.policy().signature(
sig,
HashAlgoSecurity::CollisionResistance).is_ok())
.take_while(move |sig| {
let time_hash = (
if let Some(t) = sig.signature_creation_time() {
(t, sig.hash_algo())
} else {
// Something is off. Just stop.
return false;
},
sig.hash_algo());
if let Some(reference) = first {
// Stop looking once we see an older signature or one
// with a different hash algo.
reference == time_hash
} else {
first = Some(time_hash);
true
}
})
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [Section 5.2.3.30 of RFC 4880bis] for
/// details. This can be used to address certificate flooding
/// concerns.
///
/// [Section 5.2.3.30 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10.html#section-5.2.3.30
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # fn main() -> openpgp::Result<()> {
/// # use openpgp::cert::prelude::*;
/// # use openpgp::packet::signature::SignatureBuilder;
/// # use openpgp::types::*;
/// # let policy = &openpgp::policy::StandardPolicy::new();
/// let (alice, _) = CertBuilder::new()
/// .add_userid("alice@example.org")
/// .generate()?;
/// let mut alice_signer =
/// alice.primary_key().key().clone().parts_into_secret()?
/// .into_keypair()?;
///
/// let (bob, _) = CertBuilder::new()
/// .add_userid("bob@example.org")
/// .generate()?;
/// let mut bob_signer =
/// bob.primary_key().key().clone().parts_into_secret()?
/// .into_keypair()?;
/// let bob_pristine = bob.clone();
///
/// // Have Alice certify the binding between "bob@example.org" and
/// // Bob's key.
/// let alice_certifies_bob
/// = bob.userids().next().unwrap().userid().bind(
/// &mut alice_signer, &bob,
/// SignatureBuilder::new(SignatureType::GenericCertification))?;
/// let bob = bob.insert_packets(vec![alice_certifies_bob.clone()])?;
///
/// // Have Bob attest that certification.
/// let bobs_uid = bob.userids().next().unwrap();
/// let attestations =
/// bobs_uid.attest_certifications(
/// policy,
/// &mut bob_signer,
/// bobs_uid.certifications())?;
/// let bob = bob.insert_packets(attestations)?;
///
/// assert_eq!(bob.bad_signatures().count(), 0);
/// assert_eq!(bob.userids().next().unwrap().certifications().next(),
/// Some(&alice_certifies_bob));
/// # Ok(()) }
/// ```
pub fn attest_certifications<C, S>(&self,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
std::ops::Deref::deref(self)
.attest_certifications2(self.policy(),
self.time(),
primary_signer,
certifications)
}
}
/// A Valid User Attribute and its associated data.
///
/// A specialized version of [`ValidComponentAmalgamation`].
///
pub type ValidUserAttributeAmalgamation<'a>
= ValidComponentAmalgamation<'a, UserAttribute>;
impl<'a> ValidUserAttributeAmalgamation<'a> {
/// Returns the user attributes's attested third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [Section 5.2.3.30 of RFC 4880bis] for
/// details. This can be used to address certificate flooding
/// concerns.
///
/// This method only returns signatures that are valid under the
/// current policy and are attested by the certificate holder.
///
/// [Section 5.2.3.30 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10.html#section-5.2.3.30
pub fn attested_certifications(&self)
-> impl Iterator<Item=&Signature> + Send + Sync
{
let mut hash_algo = None;
let digests: std::collections::HashSet<_> =
self.attestation_key_signatures()
.filter_map(|sig| {
sig.attested_certifications().ok()
.map(|digest_iter| (sig, digest_iter))
})
.flat_map(|(sig, digest_iter)| {
hash_algo = Some(sig.hash_algo());
digest_iter
})
.collect();
self.certifications()
.filter_map(move |sig| {
let mut hash = hash_algo.and_then(|a| a.context().ok())?;
sig.hash_for_confirmation(&mut hash);
let digest = hash.into_digest().ok()?;
if digests.contains(&digest[..]) {
Some(sig)
} else {
None
}
})
}
/// Returns set of active attestation key signatures.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Returns the set of signatures with the newest valid signature
/// creation time. Older signatures are not returned. The sum of
/// all digests in these signatures are the set of attested
/// third-party certifications.
///
/// This interface is useful for pruning old attestation key
/// signatures when filtering a certificate.
///
/// Note: This is a low-level interface. Consider using
/// [`ValidUserAttributeAmalgamation::attested_certifications`] to
/// iterate over all attested certifications.
///
/// [`ValidUserAttributeAmalgamation::attested_certifications`]: ValidUserAttributeAmalgamation#method.attested_certifications
// The explicit link works around a bug in rustdoc.
pub fn attestation_key_signatures(&'a self)
-> impl Iterator<Item=&'a Signature> + Send + Sync
{
let mut first = None;
// The newest valid signature will be returned first.
self.attestations()
// First, filter out any invalid (e.g. too new) signatures.
.filter(move |sig| self.cert.policy().signature(
sig,
HashAlgoSecurity::CollisionResistance).is_ok())
.take_while(move |sig| {
let time_hash = (
if let Some(t) = sig.signature_creation_time() {
(t, sig.hash_algo())
} else {
// Something is off. Just stop.
return false;
},
sig.hash_algo());
if let Some(reference) = first {
// Stop looking once we see an older signature or one
// with a different hash algo.
reference == time_hash
} else {
first = Some(time_hash);
true
}
})
}
/// Attests to third-party certifications.
///
/// This feature is [experimental](crate#experimental-features).
///
/// Allows the certificate owner to attest to third party
/// certifications. See [Section 5.2.3.30 of RFC 4880bis] for
/// details. This can be used to address certificate flooding
/// concerns.
///
/// [Section 5.2.3.30 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10.html#section-5.2.3.30
///
/// # Examples
///
/// See [`ValidUserIDAmalgamation::attest_certifications#examples`].
///
/// [`ValidUserIDAmalgamation::attest_certifications#examples`]: ValidUserIDAmalgamation#examples
// The explicit link works around a bug in rustdoc.
pub fn attest_certifications<C, S>(&self,
primary_signer: &mut dyn Signer,
certifications: C)
-> Result<Vec<Signature>>
where C: IntoIterator<Item = S>,
S: Borrow<Signature>,
{
std::ops::Deref::deref(self)
.attest_certifications2(self.policy(),
self.time(),
primary_signer,
certifications)
}
}
// 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, C> Clone for ValidComponentAmalgamation<'a, C> {
fn clone(&self) -> Self {
Self {
ca: self.ca.clone(),
cert: self.cert.clone(),
binding_signature: self.binding_signature,
}
}
}
impl<'a, C> std::ops::Deref for ValidComponentAmalgamation<'a, C> {
type Target = ComponentAmalgamation<'a, C>;
fn deref(&self) -> &Self::Target {
assert!(std::ptr::eq(self.ca.cert(), self.cert.cert()));
&self.ca
}
}
impl<'a, C: 'a> From<ValidComponentAmalgamation<'a, C>>
for ComponentAmalgamation<'a, C>
{
fn from(vca: ValidComponentAmalgamation<'a, C>) -> Self {
assert!(std::ptr::eq(vca.ca.cert(), vca.cert.cert()));
vca.ca
}
}
impl<'a, C> ValidComponentAmalgamation<'a, C>
where C: Ord + Send + Sync
{
/// Returns the amalgamated primary component at time `time`
///
/// If `time` is None, then the current time is used.
/// `ValidComponentAmalgamationIter` for the definition of a valid component.
///
/// The primary component is determined by taking the components that
/// are alive at time `t`, and sorting them as follows:
///
/// - non-revoked first
/// - primary first
/// - signature creation first
///
/// If there is more than one, then one is selected in a
/// deterministic, but undefined manner.
///
/// If `valid_cert` is `false`, then this does not also check
/// whether the certificate is valid; it only checks whether the
/// component is valid. Normally, this should be `true`. This
/// option is only exposed to allow breaking an infinite recursion:
///
/// - To check if a certificate is valid, we check if the
/// primary key is valid.
///
/// - To check if the primary key is valid, we need the primary
/// key's self signature
///
/// - To find the primary key's self signature, we need to find
/// the primary user id
///
/// - To find the primary user id, we need to check if the user
/// id is valid.
///
/// - To check if the user id is valid, we need to check that
/// the corresponding certificate is valid.
pub(super) fn primary(cert: &'a Cert,
iter: std::slice::Iter<'a, ComponentBundle<C>>,
policy: &'a dyn Policy, t: SystemTime,
valid_cert: bool)
-> Result<ValidComponentAmalgamation<'a, C>>
{
use std::cmp::Ordering;
let mut error = None;
// Filter out components that are not alive at time `t`.
//
// While we have the binding signature, extract a few
// properties to avoid recomputing the same thing multiple
// times.
iter.filter_map(|c| {
// No binding signature at time `t` => not alive.
let sig = match c.binding_signature(policy, t) {
Ok(sig) => Some(sig),
Err(e) => {
error = Some(e);
None
},
}?;
let revoked = c._revocation_status(policy, t, false, Some(sig));
let primary = sig.primary_userid().unwrap_or(false);
let signature_creation_time = match sig.signature_creation_time() {
Some(time) => Some(time),
None => {
error = Some(Error::MalformedPacket(
"Signature has no creation time".into()).into());
None
},
}?;
Some(((c, sig, revoked), primary, signature_creation_time))
})
.max_by(|(a, a_primary, a_signature_creation_time),
(b, b_primary, b_signature_creation_time)| {
match (matches!(&a.2, RevocationStatus::Revoked(_)),
matches!(&b.2, RevocationStatus::Revoked(_))) {
(true, false) => return Ordering::Less,
(false, true) => return Ordering::Greater,
_ => (),
}
match (a_primary, b_primary) {
(true, false) => return Ordering::Greater,
(false, true) => return Ordering::Less,
_ => (),
}
match a_signature_creation_time.cmp(b_signature_creation_time)
{
Ordering::Less => return Ordering::Less,
Ordering::Greater => return Ordering::Greater,
Ordering::Equal => (),
}
// Fallback to a lexographical comparison. Prefer
// the "smaller" one.
match a.0.component().cmp(b.0.component()) {
Ordering::Less => Ordering::Greater,
Ordering::Greater => Ordering::Less,
Ordering::Equal =>
panic!("non-canonicalized Cert (duplicate components)"),
}
})
.ok_or_else(|| {
error.map(|e| e.context(format!(
"No binding signature at time {}", crate::fmt::time(&t))))
.unwrap_or_else(|| Error::NoBindingSignature(t).into())
})
.and_then(|c| ComponentAmalgamation::new(cert, (c.0).0)
.with_policy_relaxed(policy, t, valid_cert))
}
/// The component's self-signatures.
///
/// This method only returns signatures that are valid under the current policy.
pub fn self_signatures(&self) -> impl Iterator<Item=&Signature> + Send + Sync {
std::ops::Deref::deref(self).self_signatures()
.filter(move |sig| self.cert.policy().signature(sig,
self.hash_algo_security).is_ok())
}
/// The component's third-party certifications.
///
/// This method only returns signatures that are valid under the current policy.
pub fn certifications(&self) -> impl Iterator<Item=&Signature> + Send + Sync {
std::ops::Deref::deref(self).certifications()
.filter(move |sig| self.cert.policy().signature(sig,
HashAlgoSecurity::CollisionResistance).is_ok())
}
/// The component's revocations that were issued by the
/// certificate holder.
///
/// This method only returns signatures that are valid under the current policy.
pub fn self_revocations(&self) -> impl Iterator<Item=&Signature> + Send + Sync {
std::ops::Deref::deref(self).self_revocations()
.filter(move |sig|self.cert.policy().signature(sig,
self.hash_algo_security).is_ok())
}
/// The component's revocations that were issued by other
/// certificates.
///
/// This method only returns signatures that are valid under the current policy.
pub fn other_revocations(&self) -> impl Iterator<Item=&Signature> + Send + Sync {
std::ops::Deref::deref(self).other_revocations()
.filter(move |sig| self.cert.policy().signature(sig,
HashAlgoSecurity::CollisionResistance).is_ok())
}
/// Returns all of the component's signatures.
///
/// This method only returns signatures that are valid under the
/// current policy.
pub fn signatures(&self)
-> impl Iterator<Item = &Signature> + Send + Sync {
std::ops::Deref::deref(self).signatures()
.filter(move |sig| self.cert.policy().signature(sig,
HashAlgoSecurity::CollisionResistance).is_ok())
}
}
impl<'a, C> seal::Sealed for ValidComponentAmalgamation<'a, C> {}
impl<'a, C> ValidateAmalgamation<'a, C> for ValidComponentAmalgamation<'a, C> {
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.ca.cert(), self.cert.cert()));
let time = time.into().unwrap_or_else(crate::now);
self.ca.with_policy(policy, time)
}
}
impl<'a, C> ValidAmalgamation<'a, C> for ValidComponentAmalgamation<'a, C> {
fn cert(&self) -> &ValidCert<'a> {
assert!(std::ptr::eq(self.ca.cert(), self.cert.cert()));
&self.cert
}
fn time(&self) -> SystemTime {
assert!(std::ptr::eq(self.ca.cert(), self.cert.cert()));
self.cert.time
}
fn policy(&self) -> &'a dyn Policy
{
assert!(std::ptr::eq(self.ca.cert(), self.cert.cert()));
self.cert.policy
}
fn binding_signature(&self) -> &'a Signature {
assert!(std::ptr::eq(self.ca.cert(), self.cert.cert()));
self.binding_signature
}
fn revocation_status(&self) -> RevocationStatus<'a> {
self.bundle._revocation_status(self.policy(), self.cert.time,
false, 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, C> crate::cert::Preferences<'a>
for ValidComponentAmalgamation<'a, C>
{
fn preferred_symmetric_algorithms(&self)
-> Option<&'a [SymmetricAlgorithm]> {
self.map(|s| s.preferred_symmetric_algorithms())
}
fn preferred_hash_algorithms(&self) -> Option<&'a [HashAlgorithm]> {
self.map(|s| s.preferred_hash_algorithms())
}
fn preferred_compression_algorithms(&self)
-> Option<&'a [CompressionAlgorithm]> {
self.map(|s| s.preferred_compression_algorithms())
}
fn preferred_aead_algorithms(&self) -> Option<&'a [AEADAlgorithm]> {
#[allow(deprecated)]
self.map(|s| s.preferred_aead_algorithms())
}
fn key_server_preferences(&self) -> Option<KeyServerPreferences> {
self.map(|s| s.key_server_preferences())
}
fn preferred_key_server(&self) -> Option<&'a [u8]> {
self.map(|s| s.preferred_key_server())
}
fn policy_uri(&self) -> Option<&'a [u8]> {
self.map(|s| s.policy_uri())
}
fn features(&self) -> Option<Features> {
self.map(|s| s.features())
}
}
#[cfg(test)]
mod test {
use super::*;
use std::time::UNIX_EPOCH;
use crate::policy::StandardPolicy as P;
use crate::Packet;
use crate::packet::signature::SignatureBuilder;
use crate::packet::UserID;
use crate::types::SignatureType;
use crate::types::ReasonForRevocation;
// derive(Clone) doesn't work with generic parameters that don't
// implement clone. Make sure that our custom implementations
// work.
//
// See: https://github.com/rust-lang/rust/issues/26925
#[test]
fn clone() {
let p = &P::new();
let (cert, _) = CertBuilder::new()
.add_userid("test@example.example")
.generate()
.unwrap();
let userid : UserIDAmalgamation = cert.userids().next().unwrap();
assert_eq!(userid.userid(), userid.clone().userid());
let userid : ValidUserIDAmalgamation
= userid.with_policy(p, None).unwrap();
let c = userid.clone();
assert_eq!(userid.userid(), c.userid());
assert_eq!(userid.time(), c.time());
}
#[test]
fn map() {
// The reference returned by `ComponentAmalgamation::userid`
// and `ComponentAmalgamation::user_attribute` is bound by the
// reference to the `Component` in the
// `ComponentAmalgamation`, not the `ComponentAmalgamation`
// itself.
let (cert, _) = CertBuilder::new()
.add_userid("test@example.example")
.generate()
.unwrap();
let _ = cert.userids().map(|ua| ua.userid())
.collect::<Vec<_>>();
let _ = cert.user_attributes().map(|ua| ua.user_attribute())
.collect::<Vec<_>>();
}
#[test]
fn component_amalgamation_certifications_by_key() -> Result<()> {
// Alice and Bob certify Carol's certificate. We then check
// that certifications_by_key returns them.
let (alice, _) = CertBuilder::new()
.add_userid("<alice@example.example>")
.generate()
.unwrap();
let (bob, _) = CertBuilder::new()
.add_userid("<bob@example.example>")
.generate()
.unwrap();
let carol_userid = "<carol@example.example>";
let (carol, _) = CertBuilder::new()
.add_userid(carol_userid)
.generate()
.unwrap();
let ua = alice.userids().next().expect("have a user id");
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 0);
// Alice has not certified Bob's User ID.
let ua = bob.userids().next().expect("have a user id");
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 0);
// Alice has not certified Carol's User ID.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 0);
// Have Alice certify Carol's certificate.
let mut alice_signer = alice.primary_key()
.key()
.clone()
.parts_into_secret().expect("have unencrypted key material")
.into_keypair().expect("have unencrypted key material");
let certification = SignatureBuilder::new(SignatureType::GenericCertification)
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification)?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 1);
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 1);
assert_eq!(ua.certifications_by_key(&[ bob.key_handle() ]).count(), 0);
// Have Bob certify Carol's certificate.
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::GenericCertification)
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification)?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 2);
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 1);
assert_eq!(ua.certifications_by_key(&[ bob.key_handle() ]).count(), 1);
// Again.
let certification = SignatureBuilder::new(SignatureType::GenericCertification)
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification)?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 3);
assert_eq!(ua.certifications_by_key(&[ alice.key_handle() ]).count(), 1);
assert_eq!(ua.certifications_by_key(&[ bob.key_handle() ]).count(), 2);
Ok(())
}
#[test]
fn user_id_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 ua = alice.userids().next().expect("have a user id");
assert_eq!(ua.valid_certifications_by_key(p, None, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, None, alice_primary).count(), 0);
// Alice has not certified Bob's User ID.
let ua = bob.userids().next().expect("have a user id");
assert_eq!(ua.valid_certifications_by_key(p, None, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, None, alice_primary).count(), 0);
// Alice has not certified Carol's User ID.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.valid_certifications_by_key(p, None, alice_primary).count(), 0);
assert_eq!(ua.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::GenericCertification)
.set_signature_creation_time(t1)?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 1);
assert_eq!(ua.valid_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, alice_primary).count(), 1);
assert_eq!(ua.active_certifications_by_key(p, t1, alice_primary).count(), 1);
assert_eq!(ua.valid_certifications_by_key(p, t1, bob_primary).count(), 0);
assert_eq!(ua.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::GenericCertification)
.set_signature_creation_time(t1)?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t2, alice_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t2, alice_primary).count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.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::GenericCertification)
.set_signature_creation_time(t2)?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 3);
assert_eq!(ua.valid_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.active_certifications_by_key(p, t2, alice_primary).count(), 1);
assert_eq!(ua.valid_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.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::GenericCertification)
.set_signature_creation_time(t1)?
.set_signature_validity_period(t2.duration_since(t1)?)?
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 4);
assert_eq!(ua.valid_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.active_certifications_by_key(p, t2, alice_primary).count(), 1);
assert_eq!(ua.valid_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, bob_primary).count(), 1);
assert_eq!(ua.active_certifications_by_key(p, t1, bob_primary).count(), 1);
// It expired.
assert_eq!(ua.valid_certifications_by_key(p, t2, bob_primary).count(), 0);
assert_eq!(ua.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::GenericCertification)
.set_signature_creation_time(t1)?
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&UserID::from(carol_userid))?;
let carol = carol.insert_packets(certification.clone())?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.certifications().count(), 5);
assert_eq!(ua.valid_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_certifications_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.active_certifications_by_key(p, t2, alice_primary).count(), 1);
assert_eq!(ua.valid_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.active_certifications_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.valid_certifications_by_key(p, t1, bob_primary).count(), 2);
assert_eq!(ua.active_certifications_by_key(p, t1, bob_primary).count(), 2);
// One of the certifications expired.
assert_eq!(ua.valid_certifications_by_key(p, t2, bob_primary).count(), 1);
assert_eq!(ua.active_certifications_by_key(p, t2, bob_primary).count(), 1);
Ok(())
}
#[test]
fn user_id_amalgamation_third_party_revocations_by_key() -> Result<()> {
// Alice and Bob revoke Carol's User ID. 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 carol_userid = UserID::from(carol_userid);
let ua = alice.userids().next().expect("have a user id");
assert_eq!(ua.valid_third_party_revocations_by_key(p, None, alice_primary).count(), 0);
// Alice has not certified Bob's User ID.
let ua = bob.userids().next().expect("have a user id");
assert_eq!(ua.valid_third_party_revocations_by_key(p, None, alice_primary).count(), 0);
// Alice has not certified Carol's User ID.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.valid_third_party_revocations_by_key(p, None, alice_primary).count(), 0);
// Have Alice revoke 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::CertificationRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(
ReasonForRevocation::UIDRetired, b"")?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&carol_userid)?;
let carol = carol.insert_packets([
Packet::from(carol_userid.clone()),
Packet::from(certification.clone()),
])?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.other_revocations().count(), 1);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, alice_primary).count(), 1);
assert_eq!(ua.valid_third_party_revocations_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::CertificationRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(ReasonForRevocation::UIDRetired, b"")?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&carol_userid)?;
let carol = carol.insert_packets([
Packet::from(carol_userid.clone()),
Packet::from(certification.clone()),
])?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.other_revocations().count(), 2);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t2, alice_primary).count(), 2);
assert_eq!(ua.valid_third_party_revocations_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::CertificationRevocation)
.set_signature_creation_time(t2)?
.set_reason_for_revocation(ReasonForRevocation::UIDRetired, b"")?
.sign_userid_binding(
&mut alice_signer,
carol.primary_key().key(),
&carol_userid)?;
let carol = carol.insert_packets([
Packet::from(carol_userid.clone()),
Packet::from(certification.clone()),
])?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.other_revocations().count(), 3);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.valid_third_party_revocations_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::CertificationRevocation)
.set_signature_creation_time(t1)?
.set_signature_validity_period(t2.duration_since(t1)?)?
.set_reason_for_revocation(ReasonForRevocation::UIDRetired, b"")?
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&carol_userid)?;
let carol = carol.insert_packets([
Packet::from(carol_userid.clone()),
Packet::from(certification.clone()),
])?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.other_revocations().count(), 4);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, bob_primary).count(), 1);
// It expired.
assert_eq!(ua.valid_third_party_revocations_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::CertificationRevocation)
.set_signature_creation_time(t1)?
.set_reason_for_revocation(ReasonForRevocation::UIDRetired, b"")?
.sign_userid_binding(
&mut bob_signer,
carol.primary_key().key(),
&carol_userid)?;
let carol = carol.insert_packets([
Packet::from(carol_userid.clone()),
Packet::from(certification.clone()),
])?;
// Check that it is returned.
let ua = carol.userids().next().expect("have a user id");
assert_eq!(ua.other_revocations().count(), 5);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, alice_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, alice_primary).count(), 2);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t2, alice_primary).count(), 3);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t0, bob_primary).count(), 0);
assert_eq!(ua.valid_third_party_revocations_by_key(p, t1, bob_primary).count(), 2);
// One of the certifications expired.
assert_eq!(ua.valid_third_party_revocations_by_key(p, t2, bob_primary).count(), 1);
Ok(())
}
}