1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* TLS 1.3 Protocol
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "sslt.h"
#include "stdarg.h"
#include "cert.h"
#include "ssl.h"
#include "keyhi.h"
#include "pk11func.h"
#include "prerr.h"
#include "secitem.h"
#include "secmod.h"
#include "sslimpl.h"
#include "sslproto.h"
#include "sslerr.h"
#include "ssl3exthandle.h"
#include "tls13hkdf.h"
#include "tls13con.h"
#include "tls13err.h"
#include "tls13ech.h"
#include "tls13exthandle.h"
#include "tls13hashstate.h"
#include "tls13subcerts.h"
#include "tls13psk.h"
static SECStatus tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
SSLSecretDirection install,
PRBool deleteSecret);
static SECStatus tls13_SendServerHelloSequence(sslSocket *ss);
static SECStatus tls13_SendEncryptedExtensions(sslSocket *ss);
static void tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group);
static SECStatus tls13_HandleClientKeyShare(sslSocket *ss,
TLS13KeyShareEntry *peerShare);
static SECStatus tls13_SendHelloRetryRequest(
sslSocket *ss, const sslNamedGroupDef *selectedGroup,
const PRUint8 *token, unsigned int tokenLen);
static SECStatus tls13_HandleServerKeyShare(sslSocket *ss);
static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b,
PRUint32 length);
static SECStatus tls13_SendCertificate(sslSocket *ss);
static SECStatus tls13_HandleCertificateDecode(
sslSocket *ss, PRUint8 *b, PRUint32 length);
static SECStatus tls13_HandleCertificate(
sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed);
static SECStatus tls13_ReinjectHandshakeTranscript(sslSocket *ss);
static SECStatus tls13_SendCertificateRequest(sslSocket *ss);
static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b,
PRUint32 length);
static SECStatus
tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey);
static SECStatus tls13_HandleCertificateVerify(
sslSocket *ss, PRUint8 *b, PRUint32 length);
static SECStatus tls13_RecoverWrappedSharedSecret(sslSocket *ss,
sslSessionID *sid);
static SECStatus
tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
const char *prefix,
const char *suffix,
const char *keylogLabel,
PK11SymKey **dest);
SECStatus
tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
const char *label,
unsigned int labelLen,
const SSL3Hashes *hashes,
PK11SymKey **dest,
SSLHashType hash);
static SECStatus tls13_SendEndOfEarlyData(sslSocket *ss);
static SECStatus tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b,
PRUint32 length);
static SECStatus tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss);
static SECStatus tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey);
static SECStatus tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
SSL3Hashes *hashes, SSLHashType type);
static SECStatus tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
PK11SymKey *secret,
PRUint8 *b, PRUint32 length,
const SSL3Hashes *hashes);
static SECStatus tls13_ClientHandleFinished(sslSocket *ss,
PRUint8 *b, PRUint32 length);
static SECStatus tls13_ServerHandleFinished(sslSocket *ss,
PRUint8 *b, PRUint32 length);
static SECStatus tls13_SendNewSessionTicket(sslSocket *ss,
const PRUint8 *appToken,
unsigned int appTokenLen);
static SECStatus tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b,
PRUint32 length);
static SECStatus tls13_ComputeEarlySecretsWithPsk(sslSocket *ss);
static SECStatus tls13_ComputeHandshakeSecrets(sslSocket *ss);
static SECStatus tls13_ComputeApplicationSecrets(sslSocket *ss);
static SECStatus tls13_ComputeFinalSecrets(sslSocket *ss);
static SECStatus tls13_ComputeFinished(
sslSocket *ss, PK11SymKey *baseKey, SSLHashType hashType,
const SSL3Hashes *hashes, PRBool sending, PRUint8 *output,
unsigned int *outputLen, unsigned int maxOutputLen);
static SECStatus tls13_SendClientSecondRound(sslSocket *ss);
static SECStatus tls13_SendClientSecondFlight(sslSocket *ss);
static SECStatus tls13_FinishHandshake(sslSocket *ss);
const char kHkdfLabelClient[] = "c";
const char kHkdfLabelServer[] = "s";
const char kHkdfLabelDerivedSecret[] = "derived";
const char kHkdfLabelResPskBinderKey[] = "res binder";
const char kHkdfLabelExtPskBinderKey[] = "ext binder";
const char kHkdfLabelEarlyTrafficSecret[] = "e traffic";
const char kHkdfLabelEarlyExporterSecret[] = "e exp master";
const char kHkdfLabelHandshakeTrafficSecret[] = "hs traffic";
const char kHkdfLabelApplicationTrafficSecret[] = "ap traffic";
const char kHkdfLabelFinishedSecret[] = "finished";
const char kHkdfLabelResumptionMasterSecret[] = "res master";
const char kHkdfLabelExporterMasterSecret[] = "exp master";
const char kHkdfLabelResumption[] = "resumption";
const char kHkdfLabelTrafficUpdate[] = "traffic upd";
const char kHkdfPurposeKey[] = "key";
const char kHkdfPurposeSn[] = "sn";
const char kHkdfPurposeIv[] = "iv";
const char keylogLabelClientEarlyTrafficSecret[] = "CLIENT_EARLY_TRAFFIC_SECRET";
const char keylogLabelClientHsTrafficSecret[] = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
const char keylogLabelServerHsTrafficSecret[] = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
const char keylogLabelClientTrafficSecret[] = "CLIENT_TRAFFIC_SECRET_0";
const char keylogLabelServerTrafficSecret[] = "SERVER_TRAFFIC_SECRET_0";
const char keylogLabelEarlyExporterSecret[] = "EARLY_EXPORTER_SECRET";
const char keylogLabelExporterSecret[] = "EXPORTER_SECRET";
/* Belt and suspenders in case we ever add a TLS 1.4. */
PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <=
SSL_LIBRARY_VERSION_TLS_1_3);
void
tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc)
{
PORT_Assert(desc != internal_error); /* These should never happen */
(void)SSL3_SendAlert(ss, alert_fatal, desc);
PORT_SetError(prError);
}
#ifdef TRACE
#define STATE_CASE(a) \
case a: \
return #a
static char *
tls13_HandshakeState(SSL3WaitState st)
{
switch (st) {
STATE_CASE(idle_handshake);
STATE_CASE(wait_client_hello);
STATE_CASE(wait_end_of_early_data);
STATE_CASE(wait_client_cert);
STATE_CASE(wait_client_key);
STATE_CASE(wait_cert_verify);
STATE_CASE(wait_change_cipher);
STATE_CASE(wait_finished);
STATE_CASE(wait_server_hello);
STATE_CASE(wait_certificate_status);
STATE_CASE(wait_server_cert);
STATE_CASE(wait_server_key);
STATE_CASE(wait_cert_request);
STATE_CASE(wait_hello_done);
STATE_CASE(wait_new_session_ticket);
STATE_CASE(wait_encrypted_extensions);
default:
break;
}
PORT_Assert(0);
return "unknown";
}
#endif
#define TLS13_WAIT_STATE_MASK 0x80
#define TLS13_BASE_WAIT_STATE(ws) (ws & ~TLS13_WAIT_STATE_MASK)
/* We don't mask idle_handshake because other parts of the code use it*/
#define TLS13_WAIT_STATE(ws) (((ws == idle_handshake) || (ws == wait_server_hello)) ? ws : ws | TLS13_WAIT_STATE_MASK)
#define TLS13_CHECK_HS_STATE(ss, err, ...) \
tls13_CheckHsState(ss, err, #err, __func__, __FILE__, __LINE__, \
__VA_ARGS__, \
wait_invalid)
void
tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
const char *func, const char *file, int line)
{
#ifdef TRACE
const char *new_state_name =
tls13_HandshakeState(ws);
SSL_TRC(3, ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
new_state_name,
func, file, line));
#endif
ss->ssl3.hs.ws = TLS13_WAIT_STATE(ws);
}
static PRBool
tls13_InHsStateV(sslSocket *ss, va_list ap)
{
SSL3WaitState ws;
while ((ws = va_arg(ap, SSL3WaitState)) != wait_invalid) {
if (TLS13_WAIT_STATE(ws) == ss->ssl3.hs.ws) {
return PR_TRUE;
}
}
return PR_FALSE;
}
PRBool
tls13_InHsState(sslSocket *ss, ...)
{
PRBool found;
va_list ap;
va_start(ap, ss);
found = tls13_InHsStateV(ss, ap);
va_end(ap);
return found;
}
static SECStatus
tls13_CheckHsState(sslSocket *ss, int err, const char *error_name,
const char *func, const char *file, int line,
...)
{
va_list ap;
va_start(ap, line);
if (tls13_InHsStateV(ss, ap)) {
va_end(ap);
return SECSuccess;
}
va_end(ap);
SSL_TRC(3, ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)",
SSL_GETPID(), ss->fd,
error_name,
tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
func, file, line));
tls13_FatalError(ss, err, unexpected_message);
return SECFailure;
}
PRBool
tls13_IsPostHandshake(const sslSocket *ss)
{
return ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && ss->firstHsDone;
}
SSLHashType
tls13_GetHashForCipherSuite(ssl3CipherSuite suite)
{
const ssl3CipherSuiteDef *cipherDef =
ssl_LookupCipherSuiteDef(suite);
PORT_Assert(cipherDef);
if (!cipherDef) {
return ssl_hash_none;
}
return cipherDef->prf_hash;
}
SSLHashType
tls13_GetHash(const sslSocket *ss)
{
/* suite_def may not be set yet when doing EPSK 0-Rtt. */
if (!ss->ssl3.hs.suite_def) {
if (ss->xtnData.selectedPsk) {
return ss->xtnData.selectedPsk->hash;
}
/* This should never happen. */
PORT_Assert(0);
return ssl_hash_none;
}
/* All TLS 1.3 cipher suites must have an explict PRF hash. */
PORT_Assert(ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none);
return ss->ssl3.hs.suite_def->prf_hash;
}
SECStatus
tls13_GetHashAndCipher(PRUint16 version, PRUint16 cipherSuite,
SSLHashType *hash, const ssl3BulkCipherDef **cipher)
{
if (version < SSL_LIBRARY_VERSION_TLS_1_3) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
// Lookup and check the suite.
SSLVersionRange vrange = { version, version };
if (!ssl3_CipherSuiteAllowedForVersionRange(cipherSuite, &vrange)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
const ssl3CipherSuiteDef *suiteDef = ssl_LookupCipherSuiteDef(cipherSuite);
const ssl3BulkCipherDef *cipherDef = ssl_GetBulkCipherDef(suiteDef);
if (cipherDef->type != type_aead) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
*hash = suiteDef->prf_hash;
if (cipher != NULL) {
*cipher = cipherDef;
}
return SECSuccess;
}
unsigned int
tls13_GetHashSizeForHash(SSLHashType hash)
{
switch (hash) {
case ssl_hash_sha256:
return 32;
case ssl_hash_sha384:
return 48;
default:
PORT_Assert(0);
}
return 32;
}
unsigned int
tls13_GetHashSize(const sslSocket *ss)
{
return tls13_GetHashSizeForHash(tls13_GetHash(ss));
}
static CK_MECHANISM_TYPE
tls13_GetHmacMechanismFromHash(SSLHashType hashType)
{
switch (hashType) {
case ssl_hash_sha256:
return CKM_SHA256_HMAC;
case ssl_hash_sha384:
return CKM_SHA384_HMAC;
default:
PORT_Assert(0);
}
return CKM_SHA256_HMAC;
}
static CK_MECHANISM_TYPE
tls13_GetHmacMechanism(const sslSocket *ss)
{
return tls13_GetHmacMechanismFromHash(tls13_GetHash(ss));
}
SECStatus
tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes,
const PRUint8 *buf, unsigned int len,
SSLHashType hash)
{
SECStatus rv;
rv = PK11_HashBuf(ssl3_HashTypeToOID(hash), hashes->u.raw, buf, len);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
hashes->len = tls13_GetHashSizeForHash(hash);
return SECSuccess;
}
static SECStatus
tls13_CreateKEMKeyPair(sslSocket *ss, const sslNamedGroupDef *groupDef,
sslKeyPair **outKeyPair)
{
PORT_Assert(groupDef);
sslKeyPair *keyPair = NULL;
SECKEYPrivateKey *privKey = NULL;
SECKEYPublicKey *pubKey = NULL;
CK_MECHANISM_TYPE mechanism;
CK_NSS_KEM_PARAMETER_SET_TYPE paramSet;
switch (groupDef->name) {
case ssl_grp_kem_xyber768d00:
mechanism = CKM_NSS_KYBER_KEY_PAIR_GEN;
paramSet = CKP_NSS_KYBER_768_ROUND3;
break;
case ssl_grp_kem_mlkem768x25519:
mechanism = CKM_NSS_ML_KEM_KEY_PAIR_GEN;
paramSet = CKP_NSS_ML_KEM_768;
break;
default:
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
PK11SlotInfo *slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg);
if (!slot) {
goto loser;
}
privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism,
¶mSet, &pubKey, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC,
CKF_DERIVE, CKF_DERIVE, ss->pkcs11PinArg);
if (!privKey) {
privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism,
¶mSet, &pubKey, PK11_ATTR_SESSION | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE,
CKF_DERIVE, CKF_DERIVE, ss->pkcs11PinArg);
}
PK11_FreeSlot(slot);
if (!privKey || !pubKey) {
goto loser;
}
keyPair = ssl_NewKeyPair(privKey, pubKey);
if (!keyPair) {
goto loser;
}
SSL_TRC(50, ("%d: SSL[%d]: Create Kyber ephemeral key %d",
SSL_GETPID(), ss ? ss->fd : NULL, groupDef->name));
PRINT_BUF(50, (ss, "Public Key", pubKey->u.kyber.publicValue.data,
pubKey->u.kyber.publicValue.len));
#ifdef TRACE
if (ssl_trace >= 50) {
SECItem d = { siBuffer, NULL, 0 };
SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_VALUE, &d);
if (rv == SECSuccess) {
PRINT_BUF(50, (ss, "Private Key", d.data, d.len));
SECITEM_FreeItem(&d, PR_FALSE);
} else {
SSL_TRC(50, ("Error extracting private key"));
}
}
#endif
*outKeyPair = keyPair;
return SECSuccess;
loser:
SECKEY_DestroyPrivateKey(privKey);
SECKEY_DestroyPublicKey(pubKey);
ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
return SECFailure;
}
SECStatus
tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef,
sslEphemeralKeyPair **outKeyPair)
{
SECStatus rv;
const ssl3DHParams *params;
sslEphemeralKeyPair *keyPair = NULL;
PORT_Assert(groupDef);
switch (groupDef->keaType) {
case ssl_kea_ecdh_hybrid:
if (groupDef->name != ssl_grp_kem_xyber768d00 && groupDef->name != ssl_grp_kem_mlkem768x25519) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
const sslNamedGroupDef *x25519 = ssl_LookupNamedGroup(ssl_grp_ec_curve25519);
sslEphemeralKeyPair *x25519Pair = ssl_LookupEphemeralKeyPair(ss, x25519);
if (x25519Pair) {
keyPair = ssl_CopyEphemeralKeyPair(x25519Pair);
}
if (!keyPair) {
rv = ssl_CreateECDHEphemeralKeyPair(ss, x25519, &keyPair);
if (rv != SECSuccess) {
return SECFailure;
}
}
keyPair->group = groupDef;
break;
case ssl_kea_ecdh:
if (groupDef->name == ssl_grp_ec_curve25519) {
sslEphemeralKeyPair *hybridPair = ssl_LookupEphemeralKeyPair(ss, ssl_LookupNamedGroup(ssl_grp_kem_mlkem768x25519));
if (!hybridPair) {
hybridPair = ssl_LookupEphemeralKeyPair(ss, ssl_LookupNamedGroup(ssl_grp_kem_xyber768d00));
}
if (hybridPair) {
// We could use ssl_CopyEphemeralKeyPair here, but we would need to free
// the KEM components. We should pull this out into a utility function when
// we refactor to support multiple hybrid mechanisms.
keyPair = PORT_ZNew(sslEphemeralKeyPair);
if (!keyPair) {
return SECFailure;
}
PR_INIT_CLIST(&keyPair->link);
keyPair->group = groupDef;
keyPair->keys = ssl_GetKeyPairRef(hybridPair->keys);
}
}
if (!keyPair) {
rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, &keyPair);
if (rv != SECSuccess) {
return SECFailure;
}
}
break;
case ssl_kea_dh:
params = ssl_GetDHEParams(groupDef);
PORT_Assert(params->name != ssl_grp_ffdhe_custom);
rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
if (rv != SECSuccess) {
return SECFailure;
}
break;
default:
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
// If we're creating an ECDH + KEM hybrid share and we're the client, then
// we still need to generate the KEM key pair. Otherwise we're done.
if (groupDef->keaType == ssl_kea_ecdh_hybrid && !ss->sec.isServer) {
rv = tls13_CreateKEMKeyPair(ss, groupDef, &keyPair->kemKeys);
if (rv != SECSuccess) {
ssl_FreeEphemeralKeyPair(keyPair);
return SECFailure;
}
}
*outKeyPair = keyPair;
return SECSuccess;
}
SECStatus
tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef)
{
sslEphemeralKeyPair *keyPair = NULL;
SECStatus rv;
rv = tls13_CreateKeyShare(ss, groupDef, &keyPair);
if (rv != SECSuccess) {
return SECFailure;
}
PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
return SECSuccess;
}
SECStatus
SSL_SendAdditionalKeyShares(PRFileDesc *fd, unsigned int count)
{
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
ss->additionalShares = count;
return SECSuccess;
}
/*
* Generate shares for ECDHE and FFDHE. This picks the first enabled group of
* the requisite type and creates a share for that.
*
* Called from ssl3_SendClientHello.
*/
SECStatus
tls13_SetupClientHello(sslSocket *ss, sslClientHelloType chType)
{
unsigned int i;
SSL3Statistics *ssl3stats = SSL_GetStatistics();
NewSessionTicket *session_ticket = NULL;
sslSessionID *sid = ss->sec.ci.sid;
unsigned int numShares = 0;
SECStatus rv;
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
rv = tls13_ClientSetupEch(ss, chType);
if (rv != SECSuccess) {
return SECFailure;
}
/* Everything below here is only run on the first CH. */
if (chType != client_hello_initial) {
return SECSuccess;
}
rv = tls13_ClientGreaseSetup(ss);
if (rv != SECSuccess) {
return SECFailure;
}
/* Select the first enabled group.
* TODO(ekr@rtfm.com): be smarter about offering the group
* that the other side negotiated if we are resuming. */
PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
if (!ss->namedGroupPreferences[i]) {
continue;
}
rv = tls13_AddKeyShare(ss, ss->namedGroupPreferences[i]);
if (rv != SECSuccess) {
return SECFailure;
}
if (++numShares > ss->additionalShares) {
break;
}
}
if (PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)) {
PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
return SECFailure;
}
/* Try to do stateless resumption, if we can. */
if (sid->cached != never_cached &&
sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
/* The caller must be holding sid->u.ssl3.lock for reading. */
session_ticket = &sid->u.ssl3.locked.sessionTicket;
PORT_Assert(session_ticket && session_ticket->ticket.data);
if (ssl_TicketTimeValid(ss, session_ticket)) {
ss->statelessResume = PR_TRUE;
}
if (ss->statelessResume) {
PORT_Assert(ss->sec.ci.sid);
rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
SSL_AtomicIncrementLong(&ssl3stats->sch_sid_cache_not_ok);
ssl_UncacheSessionID(ss);
ssl_FreeSID(ss->sec.ci.sid);
ss->sec.ci.sid = NULL;
return SECFailure;
}
ss->ssl3.hs.cipher_suite = ss->sec.ci.sid->u.ssl3.cipherSuite;
rv = ssl3_SetupCipherSuite(ss, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, PORT_GetError(), internal_error);
return SECFailure;
}
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
}
}
/* Derive the binder keys if any PSKs. */
if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
/* If an External PSK specified a suite, use that. */
sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
if (!ss->statelessResume &&
psk->type == ssl_psk_external &&
psk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
ss->ssl3.hs.cipher_suite = psk->zeroRttSuite;
}
rv = tls13_ComputeEarlySecretsWithPsk(ss);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
}
tls13_EchKeyLog(ss);
return SECSuccess;
}
static SECStatus
tls13_ImportDHEKeyShare(SECKEYPublicKey *peerKey,
PRUint8 *b, PRUint32 length,
SECKEYPublicKey *pubKey)
{
SECStatus rv;
SECItem publicValue = { siBuffer, NULL, 0 };
publicValue.data = b;
publicValue.len = length;
if (!ssl_IsValidDHEShare(&pubKey->u.dh.prime, &publicValue)) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
return SECFailure;
}
peerKey->keyType = dhKey;
rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.prime,
&pubKey->u.dh.prime);
if (rv != SECSuccess)
return SECFailure;
rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.base,
&pubKey->u.dh.base);
if (rv != SECSuccess)
return SECFailure;
rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.publicValue,
&publicValue);
if (rv != SECSuccess)
return SECFailure;
return SECSuccess;
}
static SECStatus
tls13_ImportKEMKeyShare(SECKEYPublicKey *peerKey, TLS13KeyShareEntry *entry)
{
SECItem pk = { siBuffer, NULL, 0 };
SECStatus rv;
size_t expected_len;
switch (entry->group->name) {
case ssl_grp_kem_xyber768d00:
expected_len = X25519_PUBLIC_KEY_BYTES + KYBER768_PUBLIC_KEY_BYTES;
break;
case ssl_grp_kem_mlkem768x25519:
expected_len = X25519_PUBLIC_KEY_BYTES + KYBER768_PUBLIC_KEY_BYTES;
break;
default:
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
return SECFailure;
}
if (entry->key_exchange.len != expected_len) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
return SECFailure;
}
switch (entry->group->name) {
case ssl_grp_kem_xyber768d00:
peerKey->keyType = kyberKey;
peerKey->u.kyber.params = params_kyber768_round3;
// key_exchange.data is `x25519 || kyber768`
pk.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES;
pk.len = KYBER768_PUBLIC_KEY_BYTES;
break;
case ssl_grp_kem_mlkem768x25519:
peerKey->keyType = kyberKey;
peerKey->u.kyber.params = params_ml_kem768;
// key_exchange.data is `mlkem768 || x25519`
pk.data = entry->key_exchange.data;
pk.len = KYBER768_PUBLIC_KEY_BYTES;
break;
default:
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.kyber.publicValue, &pk);
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
return SECSuccess;
}
static SECStatus
tls13_HandleKEMCiphertext(sslSocket *ss, TLS13KeyShareEntry *entry, sslKeyPair *keyPair, PK11SymKey **outKey)
{
SECItem ct = { siBuffer, NULL, 0 };
SECStatus rv;
switch (entry->group->name) {
case ssl_grp_kem_xyber768d00:
if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES + KYBER768_CIPHERTEXT_BYTES) {
ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
return SECFailure;
}
ct.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES;
ct.len = KYBER768_CIPHERTEXT_BYTES;
break;
case ssl_grp_kem_mlkem768x25519:
if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES + KYBER768_CIPHERTEXT_BYTES) {
ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
return SECFailure;
}
ct.data = entry->key_exchange.data;
ct.len = KYBER768_CIPHERTEXT_BYTES;
break;
default:
PORT_Assert(0);
ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = PK11_Decapsulate(keyPair->privKey, &ct, CKM_HKDF_DERIVE, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE, CKF_DERIVE, outKey);
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
}
return rv;
}
static SECStatus
tls13_HandleKEMKey(sslSocket *ss,
TLS13KeyShareEntry *entry,
PK11SymKey **key,
SECItem **ciphertext)
{
PORTCheapArenaPool arena;
SECKEYPublicKey *peerKey;
CK_OBJECT_HANDLE handle;
SECStatus rv;
PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey);
if (peerKey == NULL) {
goto loser;
}
peerKey->arena = &arena.arena;
peerKey->pkcs11Slot = NULL;
peerKey->pkcs11ID = CK_INVALID_HANDLE;
rv = tls13_ImportKEMKeyShare(peerKey, entry);
if (rv != SECSuccess) {
goto loser;
}
PK11SlotInfo *slot = PK11_GetBestSlot(CKM_NSS_KYBER, ss->pkcs11PinArg);
if (!slot) {
goto loser;
}
handle = PK11_ImportPublicKey(slot, peerKey, PR_FALSE);
PK11_FreeSlot(slot); /* peerKey holds a slot reference on success. */
if (handle == CK_INVALID_HANDLE) {
goto loser;
}
rv = PK11_Encapsulate(peerKey,
CKM_HKDF_DERIVE, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC,
CKF_DERIVE, key, ciphertext);
/* Destroy the imported public key */
PORT_Assert(peerKey->pkcs11Slot);
PK11_DestroyObject(peerKey->pkcs11Slot, peerKey->pkcs11ID);
PK11_FreeSlot(peerKey->pkcs11Slot);
PORT_DestroyCheapArena(&arena);
return rv;
loser:
PORT_DestroyCheapArena(&arena);
return SECFailure;
}
SECStatus
tls13_HandleKeyShare(sslSocket *ss,
TLS13KeyShareEntry *entry,
sslKeyPair *keyPair,
SSLHashType hash,
PK11SymKey **out)
{
PORTCheapArenaPool arena;
SECKEYPublicKey *peerKey;
CK_MECHANISM_TYPE mechanism;
PK11SymKey *key;
unsigned char *ec_data;
SECStatus rv;
int keySize = 0;
PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey);
if (peerKey == NULL) {
goto loser;
}
peerKey->arena = &arena.arena;
peerKey->pkcs11Slot = NULL;
peerKey->pkcs11ID = CK_INVALID_HANDLE;
switch (entry->group->keaType) {
case ssl_kea_ecdh_hybrid:
switch (entry->group->name) {
case ssl_grp_kem_xyber768d00:
// x25519 share is at the beginning
ec_data = entry->key_exchange.len < X25519_PUBLIC_KEY_BYTES
? NULL
: entry->key_exchange.data;
break;
case ssl_grp_kem_mlkem768x25519:
// x25519 share is at the end
ec_data = entry->key_exchange.len < X25519_PUBLIC_KEY_BYTES
? NULL
: entry->key_exchange.data + entry->key_exchange.len - X25519_PUBLIC_KEY_BYTES;
break;
default:
ec_data = NULL;
break;
}
if (!ec_data) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
goto loser;
}
rv = ssl_ImportECDHKeyShare(peerKey,
ec_data,
X25519_PUBLIC_KEY_BYTES,
ssl_LookupNamedGroup(ssl_grp_ec_curve25519));
mechanism = CKM_ECDH1_DERIVE;
break;
case ssl_kea_ecdh:
rv = ssl_ImportECDHKeyShare(peerKey,
entry->key_exchange.data,
entry->key_exchange.len,
entry->group);
mechanism = CKM_ECDH1_DERIVE;
break;
case ssl_kea_dh:
rv = tls13_ImportDHEKeyShare(peerKey,
entry->key_exchange.data,
entry->key_exchange.len,
keyPair->pubKey);
mechanism = CKM_DH_PKCS_DERIVE;
keySize = peerKey->u.dh.publicValue.len;
break;
default:
PORT_Assert(0);
goto loser;
}
if (rv != SECSuccess) {
goto loser;
}
key = PK11_PubDeriveWithKDF(
keyPair->privKey, peerKey, PR_FALSE, NULL, NULL, mechanism,
CKM_HKDF_DERIVE, CKA_DERIVE, keySize, CKD_NULL, NULL, NULL);
if (!key) {
ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
goto loser;
}
*out = key;
PORT_DestroyCheapArena(&arena);
return SECSuccess;
loser:
PORT_DestroyCheapArena(&arena);
return SECFailure;
}
static PRBool
tls13_UseServerSecret(sslSocket *ss, SSLSecretDirection direction)
{
return ss->sec.isServer == (direction == ssl_secret_write);
}
static PK11SymKey **
tls13_TrafficSecretRef(sslSocket *ss, SSLSecretDirection direction)
{
if (tls13_UseServerSecret(ss, direction)) {
return &ss->ssl3.hs.serverTrafficSecret;
}
return &ss->ssl3.hs.clientTrafficSecret;
}
SECStatus
tls13_UpdateTrafficKeys(sslSocket *ss, SSLSecretDirection direction)
{
PK11SymKey **secret;
PK11SymKey *updatedSecret;
PRUint16 epoch;
SECStatus rv;
secret = tls13_TrafficSecretRef(ss, direction);
rv = tls13_HkdfExpandLabel(*secret, tls13_GetHash(ss),
NULL, 0,
kHkdfLabelTrafficUpdate,
strlen(kHkdfLabelTrafficUpdate),
tls13_GetHmacMechanism(ss),
tls13_GetHashSize(ss),
ss->protocolVariant,
&updatedSecret);
if (rv != SECSuccess) {
return SECFailure;
}
PK11_FreeSymKey(*secret);
*secret = updatedSecret;
ssl_GetSpecReadLock(ss);
if (direction == ssl_secret_read) {
epoch = ss->ssl3.crSpec->epoch;
} else {
epoch = ss->ssl3.cwSpec->epoch;
}
ssl_ReleaseSpecReadLock(ss);
if (epoch == PR_UINT16_MAX) {
/* Good chance that this is an overflow from too many updates. */
FATAL_ERROR(ss, SSL_ERROR_TOO_MANY_KEY_UPDATES, internal_error);
return SECFailure;
}
++epoch;
if (ss->secretCallback) {
ss->secretCallback(ss->fd, epoch, direction, updatedSecret,
ss->secretCallbackArg);
}
rv = tls13_SetCipherSpec(ss, epoch, direction, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
return SECSuccess;
}
SECStatus
tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request, PRBool buffer)
{
SECStatus rv;
SSL_TRC(3, ("%d: TLS13[%d]: %s send key update, response %s",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
(request == update_requested) ? "requested"
: "not requested"));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(!ss->sec.isServer || !ss->ssl3.clientCertRequested);
if (!tls13_IsPostHandshake(ss)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_LIBRARY_FAILURE,
idle_handshake);
if (rv != SECSuccess) {
return SECFailure;
}
if (IS_DTLS(ss)) {
rv = dtls13_MaybeSendKeyUpdate(ss, request, buffer);
if (rv != SECSuccess) {
/* Error code set already. */
return SECFailure;
}
return rv;
}
ssl_GetXmitBufLock(ss);
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_key_update, 1);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
rv = ssl3_AppendHandshakeNumber(ss, request, 1);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
/* If we have been asked to buffer, then do so. This allows us to coalesce
* a KeyUpdate with a pending write. */
rv = ssl3_FlushHandshake(ss, buffer ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
if (rv != SECSuccess) {
goto loser; /* error code set by ssl3_FlushHandshake */
}
ssl_ReleaseXmitBufLock(ss);
rv = tls13_UpdateTrafficKeys(ss, ssl_secret_write);
if (rv != SECSuccess) {
goto loser; /* error code set by tls13_UpdateTrafficKeys */
}
return SECSuccess;
loser:
ssl_ReleaseXmitBufLock(ss);
return SECFailure;
}
SECStatus
SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate)
{
SECStatus rv;
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
if (!tls13_IsPostHandshake(ss)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
if (ss->ssl3.clientCertRequested) {
PORT_SetError(PR_WOULD_BLOCK_ERROR);
return SECFailure;
}
rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
idle_handshake);
if (rv != SECSuccess) {
return SECFailure;
}
ssl_GetSSL3HandshakeLock(ss);
rv = tls13_SendKeyUpdate(ss, requestUpdate ? update_requested : update_not_requested,
PR_FALSE /* don't buffer */);
/* Remember that we are the ones that initiated this KeyUpdate. */
if (rv == SECSuccess) {
ss->ssl3.peerRequestedKeyUpdate = PR_FALSE;
}
ssl_ReleaseSSL3HandshakeLock(ss);
return rv;
}
SECStatus
SSLExp_SetCertificateCompressionAlgorithm(PRFileDesc *fd, SSLCertificateCompressionAlgorithm alg)
{
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure; /* Code already set. */
}
ssl_GetSSL3HandshakeLock(ss);
if (ss->ssl3.supportedCertCompressionAlgorithmsCount == MAX_SUPPORTED_CERTIFICATE_COMPRESSION_ALGS) {
goto loser;
}
/* Reserved ID */
if (alg.id == 0) {
goto loser;
}
if (alg.encode == NULL && alg.decode == NULL) {
goto loser;
}
/* Checking that we have not yet registed an algorithm with the same ID. */
for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == alg.id) {
goto loser;
}
}
PORT_Memcpy(&ss->ssl3.supportedCertCompressionAlgorithms
[ss->ssl3.supportedCertCompressionAlgorithmsCount],
&alg, sizeof(alg));
ss->ssl3.supportedCertCompressionAlgorithmsCount += 1;
ssl_ReleaseSSL3HandshakeLock(ss);
return SECSuccess;
loser:
PORT_SetError(SEC_ERROR_INVALID_ARGS);
ssl_ReleaseSSL3HandshakeLock(ss);
return SECFailure;
}
/*
* enum {
* update_not_requested(0), update_requested(1), (255)
* } KeyUpdateRequest;
*
* struct {
* KeyUpdateRequest request_update;
* } KeyUpdate;
*/
/* If we're handing the DTLS1.3 message, we silently fail if there is a parsing problem. */
static SECStatus
tls13_HandleKeyUpdate(sslSocket *ss, PRUint8 *b, unsigned int length)
{
SECStatus rv;
PRUint32 update;
SSL_TRC(3, ("%d: TLS13[%d]: %s handle key update",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if (!tls13_IsPostHandshake(ss)) {
FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, unexpected_message);
return SECFailure;
}
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE,
idle_handshake);
if (rv != SECSuccess) {
/* We should never be idle_handshake prior to firstHsDone. */
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
rv = ssl3_ConsumeHandshakeNumber(ss, &update, 1, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* Error code set already. */
}
if (length != 0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
return SECFailure;
}
if (!(update == update_requested ||
update == update_not_requested)) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
return SECFailure;
}
if (IS_DTLS(ss)) {
return dtls13_HandleKeyUpdate(ss, b, length, update);
}
rv = tls13_UpdateTrafficKeys(ss, ssl_secret_read);
if (rv != SECSuccess) {
return SECFailure; /* Error code set by tls13_UpdateTrafficKeys. */
}
if (update == update_requested) {
PRBool sendUpdate;
if (ss->ssl3.clientCertRequested) {
/* Post-handshake auth is in progress; defer sending a key update. */
ss->ssl3.hs.keyUpdateDeferred = PR_TRUE;
ss->ssl3.hs.deferredKeyUpdateRequest = update_not_requested;
sendUpdate = PR_FALSE;
} else if (ss->ssl3.peerRequestedKeyUpdate) {
/* Only send an update if we have sent with the current spec. This
* prevents us from being forced to crank forward pointlessly. */
ssl_GetSpecReadLock(ss);
sendUpdate = ss->ssl3.cwSpec->nextSeqNum > 0;
ssl_ReleaseSpecReadLock(ss);
} else {
sendUpdate = PR_TRUE;
}
if (sendUpdate) {
/* Respond immediately (don't buffer). */
rv = tls13_SendKeyUpdate(ss, update_not_requested, PR_FALSE);
if (rv != SECSuccess) {
return SECFailure; /* Error already set. */
}
}
ss->ssl3.peerRequestedKeyUpdate = PR_TRUE;
}
return SECSuccess;
}
SECStatus
SSLExp_SendCertificateRequest(PRFileDesc *fd)
{
SECStatus rv;
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
/* Not supported. */
if (IS_DTLS(ss)) {
PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
return SECFailure;
}
if (!tls13_IsPostHandshake(ss)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
if (ss->ssl3.clientCertRequested) {
PORT_SetError(PR_WOULD_BLOCK_ERROR);
return SECFailure;
}
/* Disallow a CertificateRequest if this connection uses an external PSK. */
if (ss->sec.authType == ssl_auth_psk) {
PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
return SECFailure;
}
rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
idle_handshake);
if (rv != SECSuccess) {
return SECFailure;
}
if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_post_handshake_auth_xtn)) {
PORT_SetError(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION);
return SECFailure;
}
ssl_GetSSL3HandshakeLock(ss);
rv = tls13_SendCertificateRequest(ss);
if (rv == SECSuccess) {
ssl_GetXmitBufLock(ss);
rv = ssl3_FlushHandshake(ss, 0);
ssl_ReleaseXmitBufLock(ss);
ss->ssl3.clientCertRequested = PR_TRUE;
}
ssl_ReleaseSSL3HandshakeLock(ss);
return rv;
}
SECStatus
tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
if (ss->sec.isServer && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
SSL_TRC(3, ("%d: TLS13[%d]: successfully decrypted handshake after "
"failed 0-RTT",
SSL_GETPID(), ss->fd));
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
}
/* TODO(ekr@rtfm.com): Would it be better to check all the states here? */
switch (ss->ssl3.hs.msg_type) {
case ssl_hs_certificate:
return tls13_HandleCertificate(ss, b, length, PR_FALSE);
case ssl_hs_compressed_certificate:
return tls13_HandleCertificateDecode(ss, b, length);
case ssl_hs_certificate_request:
return tls13_HandleCertificateRequest(ss, b, length);
case ssl_hs_certificate_verify:
return tls13_HandleCertificateVerify(ss, b, length);
case ssl_hs_encrypted_extensions:
return tls13_HandleEncryptedExtensions(ss, b, length);
case ssl_hs_new_session_ticket:
return tls13_HandleNewSessionTicket(ss, b, length);
case ssl_hs_finished:
if (ss->sec.isServer) {
return tls13_ServerHandleFinished(ss, b, length);
} else {
return tls13_ClientHandleFinished(ss, b, length);
}
case ssl_hs_end_of_early_data:
return tls13_HandleEndOfEarlyData(ss, b, length);
case ssl_hs_key_update:
return tls13_HandleKeyUpdate(ss, b, length);
default:
FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, unexpected_message);
return SECFailure;
}
PORT_Assert(0); /* Unreached */
return SECFailure;
}
static SECStatus
tls13_RecoverWrappedSharedSecret(sslSocket *ss, sslSessionID *sid)
{
PK11SymKey *wrapKey; /* wrapping key */
SECItem wrappedMS = { siBuffer, NULL, 0 };
SSLHashType hashType;
SSL_TRC(3, ("%d: TLS13[%d]: recovering static secret (%s)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
/* Now find the hash used as the PRF for the previous handshake. */
hashType = tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite);
/* If we are the server, we compute the wrapping key, but if we
* are the client, its coordinates are stored with the ticket. */
if (ss->sec.isServer) {
wrapKey = ssl3_GetWrappingKey(ss, NULL,
sid->u.ssl3.masterWrapMech,
ss->pkcs11PinArg);
} else {
PK11SlotInfo *slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
sid->u.ssl3.masterSlotID);
if (!slot)
return SECFailure;
wrapKey = PK11_GetWrapKey(slot,
sid->u.ssl3.masterWrapIndex,
sid->u.ssl3.masterWrapMech,
sid->u.ssl3.masterWrapSeries,
ss->pkcs11PinArg);
PK11_FreeSlot(slot);
}
if (!wrapKey) {
return SECFailure;
}
wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
PK11SymKey *unwrappedPsk = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech,
NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
CKA_DERIVE, tls13_GetHashSizeForHash(hashType),
CKF_SIGN | CKF_VERIFY, ss->pkcs11PinArg);
PK11_FreeSymKey(wrapKey);
if (!unwrappedPsk) {
return SECFailure;
}
sslPsk *rpsk = tls13_MakePsk(unwrappedPsk, ssl_psk_resume, hashType, NULL);
if (!rpsk) {
PK11_FreeSymKey(unwrappedPsk);
return SECFailure;
}
if (sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
rpsk->maxEarlyData = sid->u.ssl3.locked.sessionTicket.max_early_data_size;
rpsk->zeroRttSuite = sid->u.ssl3.cipherSuite;
}
PRINT_KEY(50, (ss, "Recovered RMS", rpsk->key));
PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||
((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume);
if (ss->sec.isServer) {
/* In server, we couldn't select the RPSK in the extension handler
* since it was not unwrapped yet. We're committed now, so select
* it and add it to the list (to ensure it is freed). */
ss->xtnData.selectedPsk = rpsk;
}
PR_APPEND_LINK(&rpsk->link, &ss->ssl3.hs.psks);
return SECSuccess;
}
/* Key Derivation Functions.
*
* 0
* |
* v
* PSK -> HKDF-Extract = Early Secret
* |
* +-----> Derive-Secret(., "ext binder" | "res binder", "")
* | = binder_key
* |
* +-----> Derive-Secret(., "c e traffic",
* | ClientHello)
* | = client_early_traffic_secret
* |
* +-----> Derive-Secret(., "e exp master",
* | ClientHello)
* | = early_exporter_secret
* v
* Derive-Secret(., "derived", "")
* |
* v
*(EC)DHE -> HKDF-Extract = Handshake Secret
* |
* +-----> Derive-Secret(., "c hs traffic",
* | ClientHello...ServerHello)
* | = client_handshake_traffic_secret
* |
* +-----> Derive-Secret(., "s hs traffic",
* | ClientHello...ServerHello)
* | = server_handshake_traffic_secret
* v
* Derive-Secret(., "derived", "")
* |
* v
* 0 -> HKDF-Extract = Master Secret
* |
* +-----> Derive-Secret(., "c ap traffic",
* | ClientHello...Server Finished)
* | = client_traffic_secret_0
* |
* +-----> Derive-Secret(., "s ap traffic",
* | ClientHello...Server Finished)
* | = server_traffic_secret_0
* |
* +-----> Derive-Secret(., "exp master",
* | ClientHello...Server Finished)
* | = exporter_secret
* |
* +-----> Derive-Secret(., "res master",
* ClientHello...Client Finished)
* = resumption_master_secret
*
*/
static SECStatus
tls13_ComputeEarlySecretsWithPsk(sslSocket *ss)
{
SECStatus rv;
SSL_TRC(5, ("%d: TLS13[%d]: compute early secrets (%s)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
PORT_Assert(!ss->ssl3.hs.currentSecret);
sslPsk *psk = NULL;
if (ss->sec.isServer) {
psk = ss->xtnData.selectedPsk;
} else {
/* Client to use the first PSK for early secrets. */
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
}
PORT_Assert(psk && psk->key);
PORT_Assert(psk->hash != ssl_hash_none);
PK11SymKey *earlySecret = NULL;
rv = tls13_HkdfExtract(NULL, psk->key, psk->hash, &earlySecret);
if (rv != SECSuccess) {
return SECFailure;
}
/* No longer need the raw input key */
PK11_FreeSymKey(psk->key);
psk->key = NULL;
const char *label = (psk->type == ssl_psk_resume) ? kHkdfLabelResPskBinderKey : kHkdfLabelExtPskBinderKey;
rv = tls13_DeriveSecretNullHash(ss, earlySecret,
label, strlen(label),
&psk->binderKey, psk->hash);
if (rv != SECSuccess) {
PK11_FreeSymKey(earlySecret);
return SECFailure;
}
ss->ssl3.hs.currentSecret = earlySecret;
return SECSuccess;
}
/* This derives the early traffic and early exporter secrets. */
static SECStatus
tls13_DeriveEarlySecrets(sslSocket *ss)
{
SECStatus rv;
PORT_Assert(ss->ssl3.hs.currentSecret);
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelClient,
kHkdfLabelEarlyTrafficSecret,
keylogLabelClientEarlyTrafficSecret,
&ss->ssl3.hs.clientEarlyTrafficSecret);
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->secretCallback) {
ss->secretCallback(ss->fd, (PRUint16)TrafficKeyEarlyApplicationData,
ss->sec.isServer ? ssl_secret_read : ssl_secret_write,
ss->ssl3.hs.clientEarlyTrafficSecret,
ss->secretCallbackArg);
}
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
NULL, kHkdfLabelEarlyExporterSecret,
keylogLabelEarlyExporterSecret,
&ss->ssl3.hs.earlyExporterSecret);
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
static SECStatus
tls13_ComputeHandshakeSecret(sslSocket *ss)
{
SECStatus rv;
PK11SymKey *derivedSecret = NULL;
PK11SymKey *newSecret = NULL;
SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secret (%s)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
/* If no PSK, generate the default early secret. */
if (!ss->ssl3.hs.currentSecret) {
PORT_Assert(!ss->xtnData.selectedPsk);
rv = tls13_HkdfExtract(NULL, NULL,
tls13_GetHash(ss), &ss->ssl3.hs.currentSecret);
if (rv != SECSuccess) {
return SECFailure;
}
}
PORT_Assert(ss->ssl3.hs.currentSecret);
PORT_Assert(ss->ssl3.hs.dheSecret);
/* Derive-Secret(., "derived", "") */
rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelDerivedSecret,
strlen(kHkdfLabelDerivedSecret),
&derivedSecret, tls13_GetHash(ss));
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return rv;
}
/* HKDF-Extract(ECDHE, .) = Handshake Secret */
rv = tls13_HkdfExtract(derivedSecret, ss->ssl3.hs.dheSecret,
tls13_GetHash(ss), &newSecret);
PK11_FreeSymKey(derivedSecret);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return rv;
}
PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
ss->ssl3.hs.currentSecret = newSecret;
return SECSuccess;
}
static SECStatus
tls13_ComputeHandshakeSecrets(sslSocket *ss)
{
SECStatus rv;
PK11SymKey *derivedSecret = NULL;
PK11SymKey *newSecret = NULL;
PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
ss->ssl3.hs.dheSecret = NULL;
SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secrets (%s)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
/* Now compute |*HsTrafficSecret| */
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelClient,
kHkdfLabelHandshakeTrafficSecret,
keylogLabelClientHsTrafficSecret,
&ss->ssl3.hs.clientHsTrafficSecret);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return rv;
}
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelServer,
kHkdfLabelHandshakeTrafficSecret,
keylogLabelServerHsTrafficSecret,
&ss->ssl3.hs.serverHsTrafficSecret);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return rv;
}
if (ss->secretCallback) {
SSLSecretDirection dir =
ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
ss->ssl3.hs.clientHsTrafficSecret,
ss->secretCallbackArg);
dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
ss->ssl3.hs.serverHsTrafficSecret,
ss->secretCallbackArg);
}
SSL_TRC(5, ("%d: TLS13[%d]: compute master secret (%s)",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
/* Crank HKDF forward to make master secret, which we
* stuff in current secret. */
rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelDerivedSecret,
strlen(kHkdfLabelDerivedSecret),
&derivedSecret, tls13_GetHash(ss));
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return rv;
}
rv = tls13_HkdfExtract(derivedSecret,
NULL,
tls13_GetHash(ss),
&newSecret);
PK11_FreeSymKey(derivedSecret);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
ss->ssl3.hs.currentSecret = newSecret;
return SECSuccess;
}
static SECStatus
tls13_ComputeApplicationSecrets(sslSocket *ss)
{
SECStatus rv;
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelClient,
kHkdfLabelApplicationTrafficSecret,
keylogLabelClientTrafficSecret,
&ss->ssl3.hs.clientTrafficSecret);
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelServer,
kHkdfLabelApplicationTrafficSecret,
keylogLabelServerTrafficSecret,
&ss->ssl3.hs.serverTrafficSecret);
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->secretCallback) {
SSLSecretDirection dir =
ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
dir, ss->ssl3.hs.clientTrafficSecret,
ss->secretCallbackArg);
dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
dir, ss->ssl3.hs.serverTrafficSecret,
ss->secretCallbackArg);
}
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
NULL, kHkdfLabelExporterMasterSecret,
keylogLabelExporterSecret,
&ss->ssl3.hs.exporterSecret);
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
static SECStatus
tls13_ComputeFinalSecrets(sslSocket *ss)
{
SECStatus rv;
PORT_Assert(!ss->ssl3.crSpec->masterSecret);
PORT_Assert(!ss->ssl3.cwSpec->masterSecret);
PORT_Assert(ss->ssl3.hs.currentSecret);
rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
NULL, kHkdfLabelResumptionMasterSecret,
NULL,
&ss->ssl3.hs.resumptionMasterSecret);
PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
ss->ssl3.hs.currentSecret = NULL;
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
static void
tls13_RestoreCipherInfo(sslSocket *ss, sslSessionID *sid)
{
/* Set these to match the cached value.
* TODO(ekr@rtfm.com): Make a version with the "true" values.
* Bug 1256137.
*/
ss->sec.authType = sid->authType;
ss->sec.authKeyBits = sid->authKeyBits;
ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
ss->sec.signatureScheme = sid->sigScheme;
}
/* Check whether resumption-PSK is allowed. */
static PRBool
tls13_CanResume(sslSocket *ss, const sslSessionID *sid)
{
const sslServerCert *sc;
if (!sid) {
return PR_FALSE;
}
if (sid->version != ss->version) {
return PR_FALSE;
}
#ifdef UNSAFE_FUZZER_MODE
/* When fuzzing, sid could contain garbage that will crash tls13_GetHashForCipherSuite.
* Do a direct comparison of cipher suites. This makes us refuse to resume when the
* protocol allows it, but resumption is discretionary anyway. */
if (sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
#else
if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
#endif
return PR_FALSE;
}
/* Server sids don't remember the server cert we previously sent, but they
* do remember the type of certificate we originally used, so we can locate
* it again, provided that the current ssl socket has had its server certs
* configured the same as the previous one. */
sc = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
if (!sc || !sc->serverCert) {
return PR_FALSE;
}
return PR_TRUE;
}
static PRBool
tls13_CanNegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
{
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
sslPsk *psk = ss->xtnData.selectedPsk;
if (!ss->opt.enable0RttData) {
return PR_FALSE;
}
if (!psk) {
return PR_FALSE;
}
if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
return PR_FALSE;
}
if (!psk->maxEarlyData) {
return PR_FALSE;
}
if (ss->ssl3.hs.cipher_suite != psk->zeroRttSuite) {
return PR_FALSE;
}
if (psk->type == ssl_psk_resume) {
if (!sid) {
return PR_FALSE;
}
PORT_Assert(sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data);
PORT_Assert(ss->statelessResume);
if (!ss->statelessResume) {
return PR_FALSE;
}
if (SECITEM_CompareItem(&ss->xtnData.nextProto,
&sid->u.ssl3.alpnSelection) != 0) {
return PR_FALSE;
}
} else if (psk->type != ssl_psk_external) {
PORT_Assert(0);
return PR_FALSE;
}
if (tls13_IsReplay(ss, sid)) {
return PR_FALSE;
}
return PR_TRUE;
}
/* Called from tls13_HandleClientHelloPart2 to update the state of 0-RTT handling.
*
* 0-RTT is only permitted if:
* 1. The early data extension was present.
* 2. We are resuming a session.
* 3. The 0-RTT option is set.
* 4. The ticket allowed 0-RTT.
* 5. We negotiated the same ALPN value as in the ticket.
*/
static void
tls13_NegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
{
SSL_TRC(3, ("%d: TLS13[%d]: negotiate 0-RTT %p",
SSL_GETPID(), ss->fd, sid));
/* tls13_ServerHandleEarlyDataXtn sets this to ssl_0rtt_sent, so this will
* be ssl_0rtt_none unless early_data is present. */
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
return;
}
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored) {
/* HelloRetryRequest causes 0-RTT to be ignored. On the second
* ClientHello, reset the ignore state so that decryption failure is
* handled normally. */
if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr) {
PORT_Assert(ss->ssl3.hs.helloRetry);
ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
} else {
SSL_TRC(3, ("%d: TLS13[%d]: application ignored 0-RTT",
SSL_GETPID(), ss->fd));
}
return;
}
if (!tls13_CanNegotiateZeroRtt(ss, sid)) {
SSL_TRC(3, ("%d: TLS13[%d]: ignore 0-RTT", SSL_GETPID(), ss->fd));
ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
return;
}
SSL_TRC(3, ("%d: TLS13[%d]: enable 0-RTT", SSL_GETPID(), ss->fd));
PORT_Assert(ss->xtnData.selectedPsk);
ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_0rtt_cipher_suite;
}
/* Check if the offered group is acceptable. */
static PRBool
tls13_isGroupAcceptable(const sslNamedGroupDef *offered,
const sslNamedGroupDef *preferredGroup)
{
/* We accept epsilon (e) bits around the offered group size. */
const unsigned int e = 2;
PORT_Assert(offered);
PORT_Assert(preferredGroup);
if (offered->bits >= preferredGroup->bits - e &&
offered->bits <= preferredGroup->bits + e) {
return PR_TRUE;
}
return PR_FALSE;
}
/* Find remote key share for given group and return it.
* Returns NULL if no key share is found. */
static TLS13KeyShareEntry *
tls13_FindKeyShareEntry(sslSocket *ss, const sslNamedGroupDef *group)
{
PRCList *cur_p = PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
while (cur_p != &ss->xtnData.remoteKeyShares) {
TLS13KeyShareEntry *offer = (TLS13KeyShareEntry *)cur_p;
if (offer->group == group) {
return offer;
}
cur_p = PR_NEXT_LINK(cur_p);
}
return NULL;
}
static SECStatus
tls13_NegotiateKeyExchange(sslSocket *ss,
const sslNamedGroupDef **requestedGroup,
TLS13KeyShareEntry **clientShare)
{
unsigned int index;
TLS13KeyShareEntry *entry = NULL;
const sslNamedGroupDef *preferredGroup = NULL;
/* We insist on DHE. */
if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_psk_key_exchange_modes_xtn)) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES,
missing_extension);
return SECFailure;
}
/* Since the server insists on DHE to provide forward secracy, for
* every other PskKem value but DHE stateless resumption is disabled,
* this includes other specified and GREASE values. */
if (!memchr(ss->xtnData.psk_ke_modes.data, tls13_psk_dh_ke,
ss->xtnData.psk_ke_modes.len)) {
SSL_TRC(3, ("%d: TLS13[%d]: client offered PSK without DH",
SSL_GETPID(), ss->fd));
ss->statelessResume = PR_FALSE;
}
}
/* Now figure out which key share we like the best out of the
* mutually supported groups, regardless of what the client offered
* for key shares.
*/
if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION,
missing_extension);
return SECFailure;
}
SSL_TRC(3, ("%d: TLS13[%d]: selected KE = %s", SSL_GETPID(),
ss->fd, ss->statelessResume || ss->xtnData.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE"));
/* Find the preferred group and an according client key share available. */
for (index = 0; index < SSL_NAMED_GROUP_COUNT; ++index) {
/* Continue to the next group if this one is not enabled. */
if (!ss->namedGroupPreferences[index]) {
/* There's a gap in the preferred groups list. Assume this is a group
* that's not supported by the client but preferred by the server. */
if (preferredGroup) {
entry = NULL;
break;
}
continue;
}
/* Check if the client sent a key share for this group. */
entry = tls13_FindKeyShareEntry(ss, ss->namedGroupPreferences[index]);
if (preferredGroup) {
/* We already found our preferred group but the group didn't have a share. */
if (entry) {
/* The client sent a key share with group ss->namedGroupPreferences[index] */
if (tls13_isGroupAcceptable(ss->namedGroupPreferences[index],
preferredGroup)) {
/* This is not the preferred group, but it's acceptable */
preferredGroup = ss->namedGroupPreferences[index];
} else {
/* The proposed group is not acceptable. */
entry = NULL;
}
}
break;
} else {
/* The first enabled group is the preferred group. */
preferredGroup = ss->namedGroupPreferences[index];
if (entry) {
break;
}
}
}
if (!preferredGroup) {
FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, handshake_failure);
return SECFailure;
}
SSL_TRC(3, ("%d: TLS13[%d]: group = %d", SSL_GETPID(), ss->fd,
preferredGroup->name));
/* Either provide a share, or provide a group that should be requested in a
* HelloRetryRequest, but not both. */
if (entry) {
PORT_Assert(preferredGroup == entry->group);
*clientShare = entry;
*requestedGroup = NULL;
} else {
*clientShare = NULL;
*requestedGroup = preferredGroup;
}
return SECSuccess;
}
SECStatus
tls13_SelectServerCert(sslSocket *ss)
{
PRCList *cursor;
SECStatus rv;
if (!ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
missing_extension);
return SECFailure;
}
/* This picks the first certificate that has:
* a) the right authentication method, and
* b) the right named curve (EC only)
*
* We might want to do some sort of ranking here later. For now, it's all
* based on what order they are configured in. */
for (cursor = PR_NEXT_LINK(&ss->serverCerts);
cursor != &ss->serverCerts;
cursor = PR_NEXT_LINK(cursor)) {
sslServerCert *cert = (sslServerCert *)cursor;
if (SSL_CERT_IS_ONLY(cert, ssl_auth_rsa_decrypt)) {
continue;
}
rv = ssl_PickSignatureScheme(ss,
cert->serverCert,
cert->serverKeyPair->pubKey,
cert->serverKeyPair->privKey,
ss->xtnData.sigSchemes,
ss->xtnData.numSigSchemes,
PR_FALSE,
&ss->ssl3.hs.signatureScheme);
if (rv == SECSuccess) {
/* Found one. */
ss->sec.serverCert = cert;
/* If we can use a delegated credential (DC) for authentication in
* the current handshake, then commit to using it now. We'll send a
* DC as an extension and use the DC private key to sign the
* handshake.
*
* This sets the signature scheme to be the signature scheme
* indicated by the DC.
*/
rv = tls13_MaybeSetDelegatedCredential(ss);
if (rv != SECSuccess) {
return SECFailure; /* Failure indicates an internal error. */
}
ss->sec.authType = ss->ssl3.hs.kea_def_mutable.authKeyType =
ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
ss->sec.authKeyBits = cert->serverKeyBits;
return SECSuccess;
}
}
FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM,
handshake_failure);
return SECFailure;
}
/* Note: |requestedGroup| is non-NULL when we send a key_share extension. */
static SECStatus
tls13_MaybeSendHelloRetry(sslSocket *ss, const sslNamedGroupDef *requestedGroup,
PRBool *hrrSent)
{
SSLHelloRetryRequestAction action = ssl_hello_retry_accept;
PRUint8 token[256] = { 0 };
unsigned int tokenLen = 0;
SECStatus rv;
if (ss->hrrCallback) {
action = ss->hrrCallback(!ss->ssl3.hs.helloRetry,
ss->xtnData.applicationToken.data,
ss->xtnData.applicationToken.len,
token, &tokenLen, sizeof(token),
ss->hrrCallbackArg);
}
/* These use SSL3_SendAlert directly to avoid an assertion in
* tls13_FatalError(), which is ordinarily OK. */
if (action == ssl_hello_retry_request && ss->ssl3.hs.helloRetry) {
(void)SSL3_SendAlert(ss, alert_fatal, internal_error);
PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
return SECFailure;
}
if (action != ssl_hello_retry_request && tokenLen) {
(void)SSL3_SendAlert(ss, alert_fatal, internal_error);
PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
return SECFailure;
}
if (tokenLen > sizeof(token)) {
(void)SSL3_SendAlert(ss, alert_fatal, internal_error);
PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
return SECFailure;
}
if (action == ssl_hello_retry_fail) {
FATAL_ERROR(ss, SSL_ERROR_APPLICATION_ABORT, handshake_failure);
return SECFailure;
}
if (action == ssl_hello_retry_reject_0rtt) {
ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
}
if (!requestedGroup && action != ssl_hello_retry_request) {
return SECSuccess;
}
rv = tls13_SendHelloRetryRequest(ss, requestedGroup, token, tokenLen);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
/* We may have received ECH, but have to start over with CH2. */
ss->ssl3.hs.echAccepted = PR_FALSE;
PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
ss->ssl3.hs.echHpkeCtx = NULL;
*hrrSent = PR_TRUE;
return SECSuccess;
}
static SECStatus
tls13_NegotiateAuthentication(sslSocket *ss)
{
if (ss->statelessResume) {
SSL_TRC(3, ("%d: TLS13[%d]: selected resumption PSK authentication",
SSL_GETPID(), ss->fd));
ss->ssl3.hs.signatureScheme = ssl_sig_none;
ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
/* Overwritten by tls13_RestoreCipherInfo. */
ss->sec.authType = ssl_auth_psk;
return SECSuccess;
} else if (ss->xtnData.selectedPsk) {
/* If the EPSK doesn't specify a suite, use what was negotiated.
* Else, only use the EPSK if we negotiated that suite. */
if (ss->xtnData.selectedPsk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL ||
ss->ssl3.hs.cipher_suite == ss->xtnData.selectedPsk->zeroRttSuite) {
SSL_TRC(3, ("%d: TLS13[%d]: selected external PSK authentication",
SSL_GETPID(), ss->fd));
ss->ssl3.hs.signatureScheme = ssl_sig_none;
ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
ss->sec.authType = ssl_auth_psk;
return SECSuccess;
}
}
/* If there were PSKs, they are no longer needed. */
if (ss->xtnData.selectedPsk) {
tls13_DestroyPskList(&ss->ssl3.hs.psks);
ss->xtnData.selectedPsk = NULL;
}
SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication",
SSL_GETPID(), ss->fd));
SECStatus rv = tls13_SelectServerCert(ss);
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
/* Called from ssl3_HandleClientHello after we have parsed the
* ClientHello and are sure that we are going to do TLS 1.3
* or fail. */
SECStatus
tls13_HandleClientHelloPart2(sslSocket *ss,
const SECItem *suites,
sslSessionID *sid,
const PRUint8 *msg,
unsigned int len)
{
SECStatus rv;
SSL3Statistics *ssl3stats = SSL_GetStatistics();
const sslNamedGroupDef *requestedGroup = NULL;
TLS13KeyShareEntry *clientShare = NULL;
ssl3CipherSuite previousCipherSuite = 0;
const sslNamedGroupDef *previousGroup = NULL;
PRBool hrr = PR_FALSE;
PRBool previousOfferedEch;
/* If the legacy_version field is set to 0x300 or smaller,
* reject the connection with protocol_version alert. */
if (ss->clientHelloVersion <= SSL_LIBRARY_VERSION_3_0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, protocol_version);
goto loser;
}
ss->ssl3.hs.endOfFlight = PR_TRUE;
if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
}
/* Negotiate cipher suite. */
rv = ssl3_NegotiateCipherSuite(ss, suites, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
goto loser;
}
/* If we are going around again, then we should make sure that the cipher
* suite selection doesn't change. That's a sign of client shennanigans. */
if (ss->ssl3.hs.helloRetry) {
/* Update sequence numbers before checking the cookie so that any alerts
* we generate are sent with the right sequence numbers. */
if (IS_DTLS(ss)) {
/* Count the first ClientHello and the HelloRetryRequest. */
ss->ssl3.hs.sendMessageSeq = 1;
ss->ssl3.hs.recvMessageSeq = 1;
ssl_GetSpecWriteLock(ss);
/* Increase the write sequence number. The read sequence number
* will be reset after this to early data or handshake. */
ss->ssl3.cwSpec->nextSeqNum = 1;
ssl_ReleaseSpecWriteLock(ss);
}
if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_cookie_xtn) ||
!ss->xtnData.cookie.len) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION,
missing_extension);
goto loser;
}
PRINT_BUF(50, (ss, "Client sent cookie",
ss->xtnData.cookie.data, ss->xtnData.cookie.len));
rv = tls13_HandleHrrCookie(ss, ss->xtnData.cookie.data,
ss->xtnData.cookie.len,
&previousCipherSuite,
&previousGroup,
&previousOfferedEch, NULL, PR_TRUE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO, illegal_parameter);
goto loser;
}
}
/* Now merge the ClientHello into the hash state. */
rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
/* Now create a synthetic kea_def that we can tweak. */
ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
/* Note: We call this quite a bit earlier than with TLS 1.2 and
* before. */
rv = ssl3_ServerCallSNICallback(ss);
if (rv != SECSuccess) {
goto loser; /* An alert has already been sent. */
}
/* Check if we could in principle resume. */
if (ss->statelessResume) {
PORT_Assert(sid);
if (!sid) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
if (!tls13_CanResume(ss, sid)) {
ss->statelessResume = PR_FALSE;
}
}
/* Select key exchange. */
rv = tls13_NegotiateKeyExchange(ss, &requestedGroup, &clientShare);
if (rv != SECSuccess) {
goto loser;
}
/* We should get either one of these, but not both. */
PORT_Assert((requestedGroup && !clientShare) ||
(!requestedGroup && clientShare));
/* After HelloRetryRequest, check consistency of cipher and group. */
if (ss->ssl3.hs.helloRetry) {
PORT_Assert(previousCipherSuite);
if (ss->ssl3.hs.cipher_suite != previousCipherSuite) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
illegal_parameter);
goto loser;
}
if (!clientShare) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
illegal_parameter);
goto loser;
}
/* CH1/CH2 must either both include ECH, or both exclude it. */
if (previousOfferedEch != (ss->xtnData.ech != NULL)) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
previousOfferedEch ? missing_extension : illegal_parameter);
goto loser;
}
/* If we requested a new key share, check that the client provided just
* one of the right type. */
if (previousGroup) {
if (PR_PREV_LINK(&ss->xtnData.remoteKeyShares) !=
PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
illegal_parameter);
goto loser;
}
if (clientShare->group != previousGroup) {
FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
illegal_parameter);
goto loser;
}
}
}
rv = tls13_MaybeSendHelloRetry(ss, requestedGroup, &hrr);
if (rv != SECSuccess) {
goto loser;
}
if (hrr) {
if (sid) { /* Free the sid. */
ssl_UncacheSessionID(ss);
ssl_FreeSID(sid);
}
PORT_Assert(ss->ssl3.hs.helloRetry);
return SECSuccess;
}
/* Select the authentication (this is also handshake shape). */
rv = tls13_NegotiateAuthentication(ss);
if (rv != SECSuccess) {
goto loser;
}
if (ss->sec.authType == ssl_auth_psk) {
if (ss->statelessResume) {
/* We are now committed to trying to resume. */
PORT_Assert(sid);
/* Check that the negotiated SNI and the cached SNI match. */
if (SECITEM_CompareItem(&sid->u.ssl3.srvName,
&ss->ssl3.hs.srvVirtName) != SECEqual) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
handshake_failure);
goto loser;
}
ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType,
sid->namedCurve);
PORT_Assert(ss->sec.serverCert);
rv = tls13_RecoverWrappedSharedSecret(ss, sid);
if (rv != SECSuccess) {
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
tls13_RestoreCipherInfo(ss, sid);
PORT_Assert(!ss->sec.localCert);
ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
if (sid->peerCert != NULL) {
ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
}
} else if (sid) {
/* We should never have a SID in the non-resumption case. */
PORT_Assert(0);
ssl_UncacheSessionID(ss);
ssl_FreeSID(sid);
sid = NULL;
}
ssl3_RegisterExtensionSender(
ss, &ss->xtnData,
ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn);
tls13_NegotiateZeroRtt(ss, sid);
rv = tls13_ComputeEarlySecretsWithPsk(ss);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
} else {
if (sid) { /* we had a sid, but it's no longer valid, free it */
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
ssl_UncacheSessionID(ss);
ssl_FreeSID(sid);
sid = NULL;
}
tls13_NegotiateZeroRtt(ss, NULL);
}
if (ss->statelessResume) {
PORT_Assert(ss->xtnData.selectedPsk);
PORT_Assert(ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk);
}
/* Now that we have the binder key, check the binder. */
if (ss->xtnData.selectedPsk) {
SSL3Hashes hashes;
PORT_Assert(ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen);
rv = tls13_ComputePskBinderHash(
ss,
ss->ssl3.hs.messages.buf,
ss->ssl3.hs.messages.len - ss->xtnData.pskBindersLen,
&hashes, tls13_GetHash(ss));
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
PORT_Assert(ss->xtnData.selectedPsk->hash == tls13_GetHash(ss));
PORT_Assert(ss->ssl3.hs.suite_def);
rv = tls13_VerifyFinished(ss, ssl_hs_client_hello,
ss->xtnData.selectedPsk->binderKey,
ss->xtnData.pskBinder.data,
ss->xtnData.pskBinder.len,
&hashes);
}
if (rv != SECSuccess) {
goto loser;
}
/* This needs to go after we verify the psk binder. */
rv = ssl3_InitHandshakeHashes(ss);
if (rv != SECSuccess) {
goto loser;
}
/* If this is TLS 1.3 we are expecting a ClientKeyShare
* extension. Missing/absent extension cause failure
* below. */
rv = tls13_HandleClientKeyShare(ss, clientShare);
if (rv != SECSuccess) {
goto loser; /* An alert was sent already. */
}
/* From this point we are either committed to resumption, or not. */
if (ss->statelessResume) {
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_hits);
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_stateless_resumes);
} else {
if (sid) {
/* We had a sid, but it's no longer valid, free it. */
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
ssl_UncacheSessionID(ss);
ssl_FreeSID(sid);
} else if (!ss->xtnData.selectedPsk) {
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_misses);
}
sid = ssl3_NewSessionID(ss, PR_TRUE);
if (!sid) {
FATAL_ERROR(ss, PORT_GetError(), internal_error);
return SECFailure;
}
}
/* Take ownership of the session. */
ss->sec.ci.sid = sid;
sid = NULL;
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
rv = tls13_DeriveEarlySecrets(ss);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
}
ssl_GetXmitBufLock(ss);
rv = tls13_SendServerHelloSequence(ss);
ssl_ReleaseXmitBufLock(ss);
if (rv != SECSuccess) {
FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
return SECFailure;
}
/* We're done with PSKs */
tls13_DestroyPskList(&ss->ssl3.hs.psks);
ss->xtnData.selectedPsk = NULL;
return SECSuccess;
loser:
if (sid) {
ssl_UncacheSessionID(ss);
ssl_FreeSID(sid);
}
return SECFailure;
}
SECStatus
SSLExp_HelloRetryRequestCallback(PRFileDesc *fd,
SSLHelloRetryRequestCallback cb, void *arg)
{
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure; /* Code already set. */
}
ss->hrrCallback = cb;
ss->hrrCallbackArg = arg;
return SECSuccess;
}
/*
* struct {
* ProtocolVersion server_version;
* CipherSuite cipher_suite;
* Extension extensions<2..2^16-1>;
* } HelloRetryRequest;
*
* Note: this function takes an empty buffer and returns
* a non-empty one on success, in which case the caller must
* eventually clean up.
*/
SECStatus
tls13_ConstructHelloRetryRequest(sslSocket *ss,
ssl3CipherSuite cipherSuite,
const sslNamedGroupDef *selectedGroup,
PRUint8 *cookie, unsigned int cookieLen,
const PRUint8 *cookieGreaseEchSignal,
sslBuffer *buffer)
{
SECStatus rv;
sslBuffer extensionsBuf = SSL_BUFFER_EMPTY;
PORT_Assert(buffer->len == 0);
/* Note: cookie is pointing to a stack variable, so is only valid
* now. */
ss->xtnData.selectedGroup = selectedGroup;
ss->xtnData.cookie.data = cookie;
ss->xtnData.cookie.len = cookieLen;
/* Set restored ss->ssl3.hs.greaseEchBuf value for ECH HRR extension
* reconstruction. */
if (cookieGreaseEchSignal) {
PORT_Assert(!ss->ssl3.hs.greaseEchBuf.len);
rv = sslBuffer_Append(&ss->ssl3.hs.greaseEchBuf,
cookieGreaseEchSignal,
TLS13_ECH_SIGNAL_LEN);
if (rv != SECSuccess) {
goto loser;
}
}
rv = ssl_ConstructExtensions(ss, &extensionsBuf,
ssl_hs_hello_retry_request);
/* Reset ss->ssl3.hs.greaseEchBuf if it was changed. */
if (cookieGreaseEchSignal) {
sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
}
if (rv != SECSuccess) {
goto loser;
}
/* These extensions can't be empty. */
PORT_Assert(SSL_BUFFER_LEN(&extensionsBuf) > 0);
/* Clean up cookie so we're not pointing at random memory. */
ss->xtnData.cookie.data = NULL;
ss->xtnData.cookie.len = 0;
rv = ssl_ConstructServerHello(ss, PR_TRUE, &extensionsBuf, buffer);
if (rv != SECSuccess) {
goto loser;
}
sslBuffer_Clear(&extensionsBuf);
return SECSuccess;
loser:
sslBuffer_Clear(&extensionsBuf);
sslBuffer_Clear(buffer);
return SECFailure;
}
static SECStatus
tls13_SendHelloRetryRequest(sslSocket *ss,
const sslNamedGroupDef *requestedGroup,
const PRUint8 *appToken, unsigned int appTokenLen)
{
SECStatus rv;
unsigned int cookieLen;
PRUint8 cookie[1024];
sslBuffer messageBuf = SSL_BUFFER_EMPTY;
SSL_TRC(3, ("%d: TLS13[%d]: send hello retry request handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
/* If an ECH backend or shared-mode server accepted ECH when offered,
* the HRR extension's payload must be set to 8 zero bytes, these are
* overwritten with the accept_confirmation value after the handshake
* transcript calculation.
* If a client-facing or shared-mode server did not accept ECH when offered
* OR if ECH GREASE is enabled on the server and a ECH extension was
* received, a 8 byte random value is set as the extension's payload
* [draft-ietf-tls-esni-14, Section 7].
*
* The (temporary) payload is written to the extension in tls13exthandle.c/
* tls13_ServerSendHrrEchXtn(). */
if (ss->xtnData.ech) {
PRUint8 echGreaseRaw[TLS13_ECH_SIGNAL_LEN] = { 0 };
if (!(ss->ssl3.hs.echAccepted ||
(ss->opt.enableTls13BackendEch &&
ss->xtnData.ech &&
ss->xtnData.ech->receivedInnerXtn))) {
rv = PK11_GenerateRandom(echGreaseRaw, TLS13_ECH_SIGNAL_LEN);
if (rv != SECSuccess) {
return SECFailure;
}
SSL_TRC(100, ("Generated random value for ECH HRR GREASE."));
}
sslBuffer echGreaseBuffer = SSL_BUFFER_EMPTY;
rv = sslBuffer_Append(&echGreaseBuffer, echGreaseRaw, sizeof(echGreaseRaw));
if (rv != SECSuccess) {
return SECFailure;
}
/* HRR GREASE/accept_confirmation zero bytes placeholder buffer. */
ss->ssl3.hs.greaseEchBuf = echGreaseBuffer;
}
/* Compute the cookie we are going to need. */
rv = tls13_MakeHrrCookie(ss, requestedGroup,
appToken, appTokenLen,
cookie, &cookieLen, sizeof(cookie));
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
/* Now build the body of the message. */
rv = tls13_ConstructHelloRetryRequest(ss, ss->ssl3.hs.cipher_suite,
requestedGroup,
cookie, cookieLen,
NULL, &messageBuf);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
/* And send it. */
ssl_GetXmitBufLock(ss);
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
SSL_BUFFER_LEN(&messageBuf));
if (rv != SECSuccess) {
goto loser;
}
rv = ssl3_AppendBufferToHandshake(ss, &messageBuf);
if (rv != SECSuccess) {
goto loser;
}
sslBuffer_Clear(&messageBuf); /* Done with messageBuf */
if (ss->ssl3.hs.fakeSid.len) {
PRInt32 sent;
PORT_Assert(!IS_DTLS(ss));
rv = ssl3_SendChangeCipherSpecsInt(ss);
if (rv != SECSuccess) {
goto loser;
}
/* ssl3_SendChangeCipherSpecsInt() only flushes to the output buffer, so we
* have to force a send. */
sent = ssl_SendSavedWriteData(ss);
if (sent < 0 && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
PORT_SetError(SSL_ERROR_SOCKET_WRITE_FAILURE);
goto loser;
}
} else {
rv = ssl3_FlushHandshake(ss, 0);
if (rv != SECSuccess) {
goto loser; /* error code set by ssl3_FlushHandshake */
}
}
/* We depend on this being exactly one record and one message. */
PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&
ss->ssl3.cwSpec->nextSeqNum == 1));
ssl_ReleaseXmitBufLock(ss);
ss->ssl3.hs.helloRetry = PR_TRUE;
/* We received early data but have to ignore it because we sent a retry. */
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
}
return SECSuccess;
loser:
sslBuffer_Clear(&messageBuf);
ssl_ReleaseXmitBufLock(ss);
return SECFailure;
}
/* Called from tls13_HandleClientHello.
*
* Caller must hold Handshake and RecvBuf locks.
*/
static SECStatus
tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare)
{
SECStatus rv;
sslEphemeralKeyPair *keyPair; /* ours */
SECItem *ciphertext = NULL;
PK11SymKey *dheSecret = NULL;
PK11SymKey *kemSecret = NULL;
SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(peerShare);
tls13_SetKeyExchangeType(ss, peerShare->group);
/* Generate our key */
rv = tls13_AddKeyShare(ss, peerShare->group);
if (rv != SECSuccess) {
return rv;
}
/* We should have exactly one key share. */
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
PR_NEXT_LINK(&ss->ephemeralKeyPairs));
keyPair = ((sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs));
ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
/* Register the sender */
rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_key_share_xtn,
tls13_ServerSendKeyShareXtn);
if (rv != SECSuccess) {
return SECFailure; /* Error code set already. */
}
rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys,
tls13_GetHash(ss),
&dheSecret);
if (rv != SECSuccess) {
goto loser; /* Error code already set. */
}
if (peerShare->group->keaType == ssl_kea_ecdh_hybrid) {
rv = tls13_HandleKEMKey(ss, peerShare, &kemSecret, &ciphertext);
if (rv != SECSuccess) {
goto loser; /* Error set by tls13_HandleKEMKey */
}
switch (peerShare->group->name) {
case ssl_grp_kem_xyber768d00:
ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
break;
case ssl_grp_kem_mlkem768x25519:
ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(kemSecret, dheSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
break;
default:
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
ss->ssl3.hs.dheSecret = NULL;
break;
}
if (!ss->ssl3.hs.dheSecret) {
goto loser; /* Error set by PK11_ConcatSymKeys */
}
keyPair->kemCt = ciphertext;
PK11_FreeSymKey(dheSecret);
PK11_FreeSymKey(kemSecret);
} else {
ss->ssl3.hs.dheSecret = dheSecret;
}
return SECSuccess;
loser:
SECITEM_FreeItem(ciphertext, PR_TRUE);
PK11_FreeSymKey(dheSecret);
PK11_FreeSymKey(kemSecret);
FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
return SECFailure;
}
/*
* [draft-ietf-tls-tls13-11] Section 6.3.3.2
*
* opaque DistinguishedName<1..2^16-1>;
*
* struct {
* opaque certificate_extension_oid<1..2^8-1>;
* opaque certificate_extension_values<0..2^16-1>;
* } CertificateExtension;
*
* struct {
* opaque certificate_request_context<0..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
* DistinguishedName certificate_authorities<0..2^16-1>;
* CertificateExtension certificate_extensions<0..2^16-1>;
* } CertificateRequest;
*/
static SECStatus
tls13_SendCertificateRequest(sslSocket *ss)
{
SECStatus rv;
sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
unsigned int offset = 0;
SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",
SSL_GETPID(), ss->fd));
if (ss->firstHsDone) {
PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
if (ss->ssl3.hs.shaPostHandshake == NULL) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
return SECFailure;
}
}
rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate_request);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
/* We should always have at least one of these. */
PORT_Assert(SSL_BUFFER_LEN(&extensionBuf) > 0);
/* Create a new request context for post-handshake authentication */
if (ss->firstHsDone) {
PRUint8 context[16];
SECItem contextItem = { siBuffer, context, sizeof(context) };
rv = PK11_GenerateRandom(context, sizeof(context));
if (rv != SECSuccess) {
goto loser;
}
SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &contextItem);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
goto loser;
}
offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
}
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request,
1 + /* request context length */
ss->xtnData.certReqContext.len +
2 + /* extension length */
SSL_BUFFER_LEN(&extensionBuf));
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
/* Context. */
rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.certReqContext.data,
ss->xtnData.certReqContext.len, 1);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
/* Extensions. */
rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
if (ss->firstHsDone) {
rv = ssl3_UpdatePostHandshakeHashes(ss,
SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
if (rv != SECSuccess) {
goto loser;
}
}
sslBuffer_Clear(&extensionBuf);
return SECSuccess;
loser:
sslBuffer_Clear(&extensionBuf);
return SECFailure;
}
/* [draft-ietf-tls-tls13; S 4.4.1] says:
*
* Transcript-Hash(ClientHello1, HelloRetryRequest, ... MN) =
* Hash(message_hash || // Handshake type
* 00 00 Hash.length || // Handshake message length
* Hash(ClientHello1) || // Hash of ClientHello1
* HelloRetryRequest ... MN)
*
* For an ECH handshake, the process occurs for the outer
* transcript in |ss->ssl3.hs.messages| and the inner
* transcript in |ss->ssl3.hs.echInnerMessages|.
*/
static SECStatus
tls13_ReinjectHandshakeTranscript(sslSocket *ss)
{
SSL3Hashes hashes = { 0 };
SSL3Hashes echInnerHashes = { 0 };
SECStatus rv;
/* First compute the hash. */
rv = tls13_ComputeHash(ss, &hashes,
ss->ssl3.hs.messages.buf,
ss->ssl3.hs.messages.len,
tls13_GetHash(ss));
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->ssl3.hs.echHpkeCtx) {
rv = tls13_ComputeHash(ss, &echInnerHashes,
ss->ssl3.hs.echInnerMessages.buf,
ss->ssl3.hs.echInnerMessages.len,
tls13_GetHash(ss));
if (rv != SECSuccess) {
return SECFailure;
}
}
ssl3_RestartHandshakeHashes(ss);
/* Reinject the message. The Default context variant updates
* the default hash state. Use it for both non-ECH and ECH Outer. */
rv = ssl_HashHandshakeMessageDefault(ss, ssl_hs_message_hash,
hashes.u.raw, hashes.len);
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->ssl3.hs.echHpkeCtx) {
rv = ssl_HashHandshakeMessageEchInner(ss, ssl_hs_message_hash,
echInnerHashes.u.raw,
echInnerHashes.len);
if (rv != SECSuccess) {
return SECFailure;
}
}
return SECSuccess;
}
static unsigned int
ssl_ListCount(PRCList *list)
{
unsigned int c = 0;
PRCList *cur;
for (cur = PR_NEXT_LINK(list); cur != list; cur = PR_NEXT_LINK(cur)) {
++c;
}
return c;
}
/*
* savedMsg contains the HelloRetryRequest message. When its extensions are parsed
* in ssl3_HandleParsedExtensions, the handler for ECH HRR extensions (tls13_ClientHandleHrrEchXtn)
* will take a reference into the message buffer.
*
* This reference is then used in tls13_MaybeHandleEchSignal in order to compute
* the transcript for the ECH signal calculation. This was felt to be preferable
* to re-parsing the HelloRetryRequest message in order to create the transcript.
*
* Consequently, savedMsg should not be moved or mutated between these
* function calls.
*/
SECStatus
tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *savedMsg,
PRUint32 savedLength)
{
SECStatus rv;
SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST,
unexpected_message);
return SECFailure;
}
PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
/* Restore the null cipher spec for writing. */
ssl_GetSpecWriteLock(ss);
ssl_CipherSpecRelease(ss->ssl3.cwSpec);
ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_write,
TrafficKeyClearText);
PORT_Assert(ss->ssl3.cwSpec);
ssl_ReleaseSpecWriteLock(ss);
} else {
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none);
}
/* Set the spec version, because we want to send CH now with 0303 */
tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
/* Extensions must contain more than just supported_versions. This will
* ensure that a HelloRetryRequest isn't a no-op: we must have at least two
* extensions, supported_versions plus one other. That other must be one
* that we understand and recognize as being valid for HelloRetryRequest,
* and should alter our next Client Hello. */
unsigned int requiredExtensions = 1;
/* The ECH HRR extension is a no-op from the client's perspective. */
if (ss->xtnData.ech) {
requiredExtensions++;
}
if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= requiredExtensions) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,
decode_error);
return SECFailure;
}
rv = ssl3_HandleParsedExtensions(ss, ssl_hs_hello_retry_request);
ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
if (rv != SECSuccess) {
return SECFailure; /* Error code set below */
}
rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_TRUE);
if (rv != SECSuccess) {
return SECFailure;
}
ss->ssl3.hs.helloRetry = PR_TRUE;
rv = tls13_ReinjectHandshakeTranscript(ss);
if (rv != SECSuccess) {
return rv;
}
rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
savedMsg, savedLength);
if (rv != SECSuccess) {
return SECFailure;
}
ssl_GetXmitBufLock(ss);
if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
rv = ssl3_SendChangeCipherSpecsInt(ss);
if (rv != SECSuccess) {
goto loser;
}
}
rv = ssl3_SendClientHello(ss, client_hello_retry);
if (rv != SECSuccess) {
goto loser;
}
ssl_ReleaseXmitBufLock(ss);
return SECSuccess;
loser:
ssl_ReleaseXmitBufLock(ss);
return SECFailure;
}
static SECStatus
tls13_SendPostHandshakeCertificate(sslSocket *ss)
{
SECStatus rv;
if (ss->ssl3.hs.restartTarget) {
PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (ss->ssl3.hs.clientCertificatePending) {
SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
" certificate authentication is still pending.",
SSL_GETPID(), ss->fd));
ss->ssl3.hs.restartTarget = tls13_SendPostHandshakeCertificate;
PORT_SetError(PR_WOULD_BLOCK_ERROR);
return SECFailure;
}
ssl_GetXmitBufLock(ss);
rv = tls13_SendClientSecondFlight(ss);
ssl_ReleaseXmitBufLock(ss);
PORT_Assert(ss->ssl3.hs.ws == idle_handshake);
PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
ss->ssl3.hs.shaPostHandshake = NULL;
if (rv != SECSuccess) {
return SECFailure;
}
return rv;
}
static SECStatus
tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
SECStatus rv;
SECItem context = { siBuffer, NULL, 0 };
SECItem extensionsData = { siBuffer, NULL, 0 };
SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
/* Client */
if (ss->opt.enablePostHandshakeAuth) {
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
wait_cert_request, idle_handshake);
} else {
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
wait_cert_request);
}
if (rv != SECSuccess) {
return SECFailure;
}
/* MUST NOT combine external PSKs with certificate authentication. */
if (ss->sec.authType == ssl_auth_psk) {
FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, unexpected_message);
return SECFailure;
}
if (tls13_IsPostHandshake(ss)) {
PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
if (ss->ssl3.hs.shaPostHandshake == NULL) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
return SECFailure;
}
rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_request, b, length);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
/* clean up anything left from previous handshake. */
if (ss->ssl3.clientCertChain != NULL) {
CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
ss->ssl3.clientCertChain = NULL;
}
if (ss->ssl3.clientCertificate != NULL) {
CERT_DestroyCertificate(ss->ssl3.clientCertificate);
ss->ssl3.clientCertificate = NULL;
}
if (ss->ssl3.clientPrivateKey != NULL) {
SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
ss->ssl3.clientPrivateKey = NULL;
}
if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
}
SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
ss->xtnData.certReqContext.data = NULL;
} else {
PORT_Assert(ss->ssl3.clientCertChain == NULL);
PORT_Assert(ss->ssl3.clientCertificate == NULL);
PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
PORT_Assert(!ss->ssl3.hs.clientCertRequested);
PORT_Assert(ss->xtnData.certReqContext.data == NULL);
}
rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
if (rv != SECSuccess) {
return SECFailure;
}
/* Unless it is a post-handshake client auth, the certificate
* request context must be empty. */
if (!tls13_IsPostHandshake(ss) && context.len > 0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, illegal_parameter);
return SECFailure;
}
rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData, 2, &b, &length);
if (rv != SECSuccess) {
return SECFailure;
}
if (length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, decode_error);
return SECFailure;
}
/* Process all the extensions. */
rv = ssl3_HandleExtensions(ss, &extensionsData.data, &extensionsData.len,
ssl_hs_certificate_request);
if (rv != SECSuccess) {
return SECFailure;
}
if (!ss->xtnData.numSigSchemes) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
missing_extension);
return SECFailure;
}
rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &context);
if (rv != SECSuccess) {
return SECFailure;
}
ss->ssl3.hs.clientCertRequested = PR_TRUE;
if (ss->firstHsDone) {
/* Request a client certificate. */
rv = ssl3_BeginHandleCertificateRequest(
ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
&ss->xtnData.certReqAuthorities);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return rv;
}
rv = tls13_SendPostHandshakeCertificate(ss);
if (rv != SECSuccess) {
return rv; /* error code is set. */
}
} else {
TLS13_SET_HS_STATE(ss, wait_server_cert);
}
return SECSuccess;
}
PRBool
tls13_ShouldRequestClientAuth(sslSocket *ss)
{
/* Even if we are configured to request a certificate, we can't
* if this handshake used a PSK, even when we are resuming. */
return ss->opt.requestCertificate &&
ss->ssl3.hs.kea_def->authKeyType != ssl_auth_psk;
}
static SECStatus
tls13_SendEncryptedServerSequence(sslSocket *ss)
{
SECStatus rv;
rv = tls13_ComputeHandshakeSecrets(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
ssl_secret_write, PR_FALSE);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
ssl_tls13_early_data_xtn,
ssl_SendEmptyExtension);
if (rv != SECSuccess) {
return SECFailure; /* Error code set already. */
}
}
rv = tls13_SendEncryptedExtensions(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
if (tls13_ShouldRequestClientAuth(ss)) {
rv = tls13_SendCertificateRequest(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
}
if (ss->ssl3.hs.signatureScheme != ssl_sig_none) {
SECKEYPrivateKey *svrPrivKey;
rv = tls13_SendCertificate(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
if (tls13_IsSigningWithDelegatedCredential(ss)) {
SSL_TRC(3, ("%d: TLS13[%d]: Signing with delegated credential",
SSL_GETPID(), ss->fd));
svrPrivKey = ss->sec.serverCert->delegCredKeyPair->privKey;
} else {
svrPrivKey = ss->sec.serverCert->serverKeyPair->privKey;
}
rv = tls13_SendCertificateVerify(ss, svrPrivKey);
if (rv != SECSuccess) {
return SECFailure; /* err code is set. */
}
}
rv = tls13_SendFinished(ss, ss->ssl3.hs.serverHsTrafficSecret);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
return SECSuccess;
}
/* Called from: ssl3_HandleClientHello */
static SECStatus
tls13_SendServerHelloSequence(sslSocket *ss)
{
SECStatus rv;
PRErrorCode err = 0;
SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
ssl_tls13_supported_versions_xtn,
tls13_ServerSendSupportedVersionsXtn);
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_ComputeHandshakeSecret(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
rv = ssl3_SendServerHello(ss);
if (rv != SECSuccess) {
return rv; /* err code is set. */
}
if (ss->ssl3.hs.fakeSid.len) {
PORT_Assert(!IS_DTLS(ss));
SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
if (!ss->ssl3.hs.helloRetry) {
rv = ssl3_SendChangeCipherSpecsInt(ss);
if (rv != SECSuccess) {
return rv;
}
}
}
rv = tls13_SendEncryptedServerSequence(ss);
if (rv != SECSuccess) {
err = PORT_GetError();
}
/* Even if we get an error, since the ServerHello was successfully
* serialized, we should give it a chance to reach the network. This gives
* the client a chance to perform the key exchange and decrypt the alert
* we're about to send. */
rv |= ssl3_FlushHandshake(ss, 0);
if (rv != SECSuccess) {
if (err) {
PORT_SetError(err);
}
return SECFailure;
}
/* Compute the rest of the secrets except for the resumption
* and exporter secret. */
rv = tls13_ComputeApplicationSecrets(ss);
if (rv != SECSuccess) {
LOG_ERROR(ss, PORT_GetError());
return SECFailure;
}
rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
ssl_secret_write, PR_FALSE);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (IS_DTLS(ss)) {
/* We need this for reading ACKs. */
ssl_CipherSpecAddRef(ss->ssl3.crSpec);
}
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
ssl_secret_read, PR_TRUE);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
TLS13_SET_HS_STATE(ss, wait_end_of_early_data);
} else {
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored);
rv = tls13_SetCipherSpec(ss,
TrafficKeyHandshake,
ssl_secret_read, PR_FALSE);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (tls13_ShouldRequestClientAuth(ss)) {
TLS13_SET_HS_STATE(ss, wait_client_cert);
} else {
TLS13_SET_HS_STATE(ss, wait_finished);
}
}
/* Here we set a baseline value for our RTT estimation.
* This value is updated when we get a response from the client. */
ss->ssl3.hs.rttEstimate = ssl_Time(ss);
return SECSuccess;
}
SECStatus
tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength)
{
SECStatus rv;
sslSessionID *sid = ss->sec.ci.sid;
SSL3Statistics *ssl3stats = SSL_GetStatistics();
if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
PORT_Assert(ss->xtnData.selectedPsk);
if (ss->xtnData.selectedPsk->type != ssl_psk_resume) {
ss->statelessResume = PR_FALSE;
}
} else {
/* We may have offered a PSK. If the server didn't negotiate
* it, clear this state to re-extract the Early Secret. */
if (ss->ssl3.hs.currentSecret) {
/* We might have dropped incompatible PSKs on HRR
* (see RFC8466, Section 4.1.4). */
PORT_Assert(ss->ssl3.hs.helloRetry ||
ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
ss->ssl3.hs.currentSecret = NULL;
}
ss->statelessResume = PR_FALSE;
ss->xtnData.selectedPsk = NULL;
}
if (ss->statelessResume) {
PORT_Assert(sid->version >= SSL_LIBRARY_VERSION_TLS_1_3);
if (tls13_GetHash(ss) !=
tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite)) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO,
illegal_parameter);
return SECFailure;
}
}
/* Now create a synthetic kea_def that we can tweak. */
ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
if (ss->xtnData.selectedPsk) {
ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
if (ss->statelessResume) {
tls13_RestoreCipherInfo(ss, sid);
if (sid->peerCert) {
ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
}
SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_hits);
SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_stateless_resumes);
} else {
ss->sec.authType = ssl_auth_psk;
}
} else {
if (ss->statelessResume &&
ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_misses);
}
if (sid->cached == in_client_cache) {
/* If we tried to resume and failed, let's not try again. */
ssl_UncacheSessionID(ss);
}
}
/* Discard current SID and make a new one, though it may eventually
* end up looking a lot like the old one.
*/
ssl_FreeSID(sid);
ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
if (sid == NULL) {
FATAL_ERROR(ss, PORT_GetError(), internal_error);
return SECFailure;
}
if (ss->statelessResume) {
PORT_Assert(ss->sec.peerCert);
sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
}
sid->version = ss->version;
rv = tls13_HandleServerKeyShare(ss);
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_ComputeHandshakeSecret(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_FALSE);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
rv = tls13_ComputeHandshakeSecrets(ss);
if (rv != SECSuccess) {
return SECFailure; /* error code is set. */
}
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
/* When we send 0-RTT, we saved the null spec in case we needed it to
* send another ClientHello in response to a HelloRetryRequest. Now
* that we won't be receiving a HelloRetryRequest, release the spec. */
ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_write, TrafficKeyClearText);
}
rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
ssl_secret_read, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
return SECFailure;
}
TLS13_SET_HS_STATE(ss, wait_encrypted_extensions);
return SECSuccess;
}
static void
tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group)
{
ss->sec.keaGroup = group;
switch (group->keaType) {
/* Note: These overwrite on resumption.... so if you start with ECDH
* and resume with DH, we report DH. That's fine, since no answer
* is really right. */
case ssl_kea_ecdh:
ss->ssl3.hs.kea_def_mutable.exchKeyType =
ss->statelessResume ? ssl_kea_ecdh_psk : ssl_kea_ecdh;
ss->sec.keaType = ssl_kea_ecdh;
break;
case ssl_kea_ecdh_hybrid:
ss->ssl3.hs.kea_def_mutable.exchKeyType =
ss->statelessResume ? ssl_kea_ecdh_hybrid_psk : ssl_kea_ecdh_hybrid;
ss->sec.keaType = ssl_kea_ecdh_hybrid;
break;
case ssl_kea_dh:
ss->ssl3.hs.kea_def_mutable.exchKeyType =
ss->statelessResume ? ssl_kea_dh_psk : ssl_kea_dh;
ss->sec.keaType = ssl_kea_dh;
break;
default:
PORT_Assert(0);
}
}
/*
* Called from ssl3_HandleServerHello.
*
* Caller must hold Handshake and RecvBuf locks.
*/
static SECStatus
tls13_HandleServerKeyShare(sslSocket *ss)
{
SECStatus rv;
TLS13KeyShareEntry *entry;
sslEphemeralKeyPair *keyPair;
PK11SymKey *dheSecret = NULL;
PK11SymKey *kemSecret = NULL;
SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
/* This list should have one entry. */
if (PR_CLIST_IS_EMPTY(&ss->xtnData.remoteKeyShares)) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_KEY_SHARE, missing_extension);
return SECFailure;
}
entry = (TLS13KeyShareEntry *)PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
PORT_Assert(PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares);
/* Now get our matching key. */
keyPair = ssl_LookupEphemeralKeyPair(ss, entry->group);
if (!keyPair) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, illegal_parameter);
return SECFailure;
}
PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group));
rv = tls13_HandleKeyShare(ss, entry, keyPair->keys,
tls13_GetHash(ss),
&dheSecret);
if (rv != SECSuccess) {
goto loser; /* Error code already set. */
}
if (entry->group->keaType == ssl_kea_ecdh_hybrid) {
rv = tls13_HandleKEMCiphertext(ss, entry, keyPair->kemKeys, &kemSecret);
if (rv != SECSuccess) {
goto loser; /* Error set by tls13_HandleKEMCiphertext */
}
switch (entry->group->name) {
case ssl_grp_kem_xyber768d00:
ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
break;
case ssl_grp_kem_mlkem768x25519:
ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(kemSecret, dheSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
break;
default:
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
ss->ssl3.hs.dheSecret = NULL;
break;
}
if (!ss->ssl3.hs.dheSecret) {
goto loser; /* Error set by PK11_ConcatSymKeys */
}
PK11_FreeSymKey(dheSecret);
PK11_FreeSymKey(kemSecret);
} else {
ss->ssl3.hs.dheSecret = dheSecret;
}
tls13_SetKeyExchangeType(ss, entry->group);
ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
return SECSuccess;
loser:
PK11_FreeSymKey(dheSecret);
PK11_FreeSymKey(kemSecret);
FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
return SECFailure;
}
static PRBool
tls13_FindCompressionAlgAndCheckIfSupportsEncoding(sslSocket *ss)
{
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg) {
if (ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL) {
return PR_TRUE;
}
return PR_FALSE;
}
}
return PR_FALSE;
}
static SECStatus
tls13_FindCompressionAlgAndEncodeCertificate(
sslSocket *ss, SECItem *certificateToEncode, SECItem *encodedCertificate)
{
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SECStatus rv = SECFailure;
for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg &&
ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL) {
rv = ss->ssl3.supportedCertCompressionAlgorithms[j].encode(
certificateToEncode, encodedCertificate);
return rv;
}
}
PORT_SetError(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
return SECFailure;
}
static SECStatus
tls13_SendCompressedCertificate(sslSocket *ss, sslBuffer *bufferCertificate)
{
/* TLS Certificate Compression. RFC 8879 */
/* As the encoding function takes as input a SECItem,
* we convert bufferCertificate to certificateToEncode.
*
* encodedCertificate is used to store the certificate
* after encoding.
*/
SECItem encodedCertificate = { siBuffer, NULL, 0 };
SECItem certificateToEncode = { siBuffer, NULL, 0 };
SECStatus rv = SECFailure;
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(30, ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData.compressionAlg)));
PRINT_BUF(50, (NULL, "The certificate before encoding:",
bufferCertificate->buf, bufferCertificate->len));
PRUint32 lengthUnencodedMessage = bufferCertificate->len;
rv = ssl3_CopyToSECItem(bufferCertificate, &certificateToEncode);
if (rv != SECSuccess) {
SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
goto loser; /* Code already set. */
}
rv = tls13_FindCompressionAlgAndEncodeCertificate(ss, &certificateToEncode,
&encodedCertificate);
if (rv != SECSuccess) {
SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
PORT_SetError(SEC_ERROR_NO_MEMORY);
goto loser; /* Code already set. */
}
/* The CompressedCertificate message is formed as follows:
* struct {
* CertificateCompressionAlgorithm algorithm;
* uint24 uncompressed_length;
* opaque compressed_certificate_message<1..2^24-1>;
* } CompressedCertificate;
*/
if (encodedCertificate.len < 1) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
goto loser;
}
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_compressed_certificate,
encodedCertificate.len + 2 + 3 + 3);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
rv = ssl3_AppendHandshakeNumber(ss, ss->xtnData.compressionAlg, 2);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
rv = ssl3_AppendHandshakeNumber(ss, lengthUnencodedMessage, 3);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
PRINT_BUF(30, (NULL, "The encoded certificate: ",
encodedCertificate.data, encodedCertificate.len));
rv = ssl3_AppendHandshakeVariable(ss, encodedCertificate.data, encodedCertificate.len, 3);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
SECITEM_FreeItem(&certificateToEncode, PR_FALSE);
SECITEM_FreeItem(&encodedCertificate, PR_FALSE);
return SECSuccess;
loser:
SECITEM_FreeItem(&certificateToEncode, PR_FALSE);
SECITEM_FreeItem(&encodedCertificate, PR_FALSE);
return SECFailure;
}
/*
* opaque ASN1Cert<1..2^24-1>;
*
* struct {
* ASN1Cert cert_data;
* Extension extensions<0..2^16-1>;
* } CertificateEntry;
*
* struct {
* opaque certificate_request_context<0..2^8-1>;
* CertificateEntry certificate_list<0..2^24-1>;
* } Certificate;
*/
static SECStatus
tls13_SendCertificate(sslSocket *ss)
{
SECStatus rv;
CERTCertificateList *certChain;
int certChainLen = 0;
int i;
SECItem context = { siBuffer, NULL, 0 };
sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
sslBuffer bufferCertificate = SSL_BUFFER_EMPTY;
SSL_TRC(3, ("%d: TLS1.3[%d]: send certificate handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if (ss->sec.isServer) {
PORT_Assert(!ss->sec.localCert);
/* A server certificate is selected in tls13_SelectServerCert(). */
PORT_Assert(ss->sec.serverCert);
certChain = ss->sec.serverCert->serverCertChain;
ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
} else {
if (ss->sec.localCert)
CERT_DestroyCertificate(ss->sec.localCert);
certChain = ss->ssl3.clientCertChain;
ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
}
if (!ss->sec.isServer) {
PORT_Assert(ss->ssl3.hs.clientCertRequested);
context = ss->xtnData.certReqContext;
}
if (certChain) {
for (i = 0; i < certChain->len; i++) {
/* Each cert is 3 octet length, cert, and extensions */
certChainLen += 3 + certChain->certs[i].len + 2;
}
/* Build the extensions. This only applies to the leaf cert, because we
* don't yet send extensions for non-leaf certs. */
rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate);
if (rv != SECSuccess) {
return SECFailure; /* code already set */
}
/* extensionBuf.len is only added once, for the leaf cert. */
certChainLen += SSL_BUFFER_LEN(&extensionBuf);
}
rv = sslBuffer_AppendVariable(&bufferCertificate, context.data, context.len, 1);
if (rv != SECSuccess) {
goto loser; /* Code already set. */
}
rv = sslBuffer_AppendNumber(&bufferCertificate, certChainLen, 3);
if (rv != SECSuccess) {
goto loser; /* Code already set. */
}
if (certChain) {
for (i = 0; i < certChain->len; i++) {
rv = sslBuffer_AppendVariable(&bufferCertificate, certChain->certs[i].data,
certChain->certs[i].len, 3);
if (rv != SECSuccess) {
goto loser; /* Code already set. */
}
if (i) {
/* Not end-entity. */
rv = sslBuffer_AppendNumber(&bufferCertificate, 0, 2);
if (rv != SECSuccess) {
goto loser; /* Code already set. */
}
continue;
}
rv = sslBuffer_AppendBufferVariable(&bufferCertificate, &extensionBuf, 2);
if (rv != SECSuccess) {
goto loser; /* Code already set. */
}
}
}
/* If no compression mechanism was established or
* the compression mechanism supports only decoding,
* we continue as before. */
if (ss->xtnData.compressionAlg == 0 || !tls13_FindCompressionAlgAndCheckIfSupportsEncoding(ss)) {
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
1 + context.len + 3 + certChainLen);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
rv = ssl3_AppendBufferToHandshake(ss, &bufferCertificate);
if (rv != SECSuccess) {
goto loser; /* err set by AppendHandshake. */
}
} else {
rv = tls13_SendCompressedCertificate(ss, &bufferCertificate);
if (rv != SECSuccess) {
goto loser; /* err set by tls13_SendCompressedCertificate. */
}
}
sslBuffer_Clear(&bufferCertificate);
sslBuffer_Clear(&extensionBuf);
return SECSuccess;
loser:
sslBuffer_Clear(&bufferCertificate);
sslBuffer_Clear(&extensionBuf);
return SECFailure;
}
static SECStatus
tls13_HandleCertificateEntry(sslSocket *ss, SECItem *data, PRBool first,
SECItem *certData)
{
SECStatus rv;
SECItem extensionsData;
rv = ssl3_ConsumeHandshakeVariable(ss, certData,
3, &data->data, &data->len);
if (rv != SECSuccess) {
return SECFailure;
}
rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData,
2, &data->data, &data->len);
if (rv != SECSuccess) {
return SECFailure;
}
/* Parse all the extensions. */
if (first && !ss->sec.isServer) {
rv = ssl3_HandleExtensions(ss, &extensionsData.data,
&extensionsData.len,
ssl_hs_certificate);
if (rv != SECSuccess) {
return SECFailure;
}
/* TODO(ekr@rtfm.com): Copy out SCTs. Bug 1315727. */
}
return SECSuccess;
}
static SECStatus
tls13_EnsureCerticateExpected(sslSocket *ss)
{
SECStatus rv = SECFailure;
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if (ss->sec.isServer) {
/* Receiving this message might be the first sign we have that
* early data is over, so pretend we received EOED. */
rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
if (ss->ssl3.clientCertRequested) {
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
idle_handshake);
} else {
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
wait_client_cert);
}
} else {
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
wait_cert_request, wait_server_cert);
}
return rv;
}
/* RFC 8879 TLS Certificate Compression
* struct {
* CertificateCompressionAlgorithm algorithm;
* uint24 uncompressed_length;
* opaque compressed_certificate_message<1..2^24-1>;
* } CompressedCertificate;
*/
static SECStatus
tls13_HandleCertificateDecode(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SECStatus rv = SECFailure;
if (!ss->xtnData.certificateCompressionAdvertised) {
FATAL_ERROR(ss, SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE, decode_error);
return SECFailure;
}
rv = tls13_EnsureCerticateExpected(ss);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
if (ss->firstHsDone) {
rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_compressed_certificate, b, length);
if (rv != SECSuccess) {
return rv;
}
}
SSL_TRC(30, ("%d: TLS1.3[%d]: %s handles certificate compression handshake",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
PRINT_BUF(50, (NULL, "The certificate before decoding:", b, length));
/* Reading CertificateCompressionAlgorithm. */
PRUint32 compressionAlg = 0;
rv = ssl3_ConsumeHandshakeNumber(ss, &compressionAlg, 2, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* Alert already sent. */
}
PRBool compressionAlgorithmIsSupported = PR_FALSE;
SECStatus (*certificateDecodingFunc)(const SECItem *,
unsigned char *output, size_t outputLen, size_t *usedLen) = NULL;
for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == compressionAlg) {
compressionAlgorithmIsSupported = PR_TRUE;
certificateDecodingFunc = ss->ssl3.supportedCertCompressionAlgorithms[i].decode;
}
}
/* Peer selected a compression algorithm we do not support (and did not advertise). */
if (!compressionAlgorithmIsSupported) {
PORT_SetError(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
return SECFailure;
}
/* The algorithm does not support decoding. */
if (certificateDecodingFunc == NULL) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
return SECFailure;
}
SSL_TRC(30, ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
PRUint32 decodedCertLen = 0;
rv = ssl3_ConsumeHandshakeNumber(ss, &decodedCertLen, 3, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* alert has been sent */
}
/* If the received CompressedCertificate message cannot be decompressed,
* he connection MUST be terminated with the "bad_certificate" alert.
*/
if (decodedCertLen == 0) {
SSL_TRC(50, ("%d: TLS13[%d]: %s decoded certificate length is incorrect",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
return SECFailure;
}
/* opaque compressed_certificate_message<1..2^24-1>; */
PRUint32 compressedCertLen = 0;
rv = ssl3_ConsumeHandshakeNumber(ss, &compressedCertLen, 3, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* alert has been sent */
}
if (compressedCertLen == 0 || compressedCertLen != length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
return SECFailure;
}
/* Decoding received certificate. */
PRUint8 *decodedCert = PORT_ZAlloc(decodedCertLen);
if (!decodedCert) {
return SECFailure;
}
size_t actualCertLen = 0;
SECItem encodedCertAsSecItem = { siBuffer, b, compressedCertLen };
rv = certificateDecodingFunc(&encodedCertAsSecItem,
decodedCert, decodedCertLen, &actualCertLen);
if (rv != SECSuccess) {
SSL_TRC(50, ("%d: TLS13[%d]: %s decoding of the certificate has failed",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
goto loser;
}
PRINT_BUF(60, (ss, "consume bytes:", b, compressedCertLen));
*b += compressedCertLen;
length -= compressedCertLen;
/* If, after decompression, the specified length does not match the actual length,
* the party receiving the invalid message MUST abort the connection
* with the "bad_certificate" alert.
*/
if (actualCertLen != decodedCertLen) {
SSL_TRC(50, ("%d: TLS13[%d]: %s certificate length does not correspond to extension length",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
goto loser;
}
PRINT_BUF(50, (NULL, "Decoded certificate",
decodedCert, decodedCertLen));
/* compressed_certificate_message: The result of applying the indicated
* compression algorithm to the encoded Certificate message that
* would have been sent if certificate compression was not in use.
*
* After decompression, the Certificate message MUST be processed as if
* it were encoded without being compressed. This way, the parsing and
* the verification have the same security properties as they would have
* in TLS normally.
*/
rv = tls13_HandleCertificate(ss, decodedCert, decodedCertLen, PR_TRUE);
if (rv != SECSuccess) {
goto loser;
}
/* We allow only one compressed certificate to be handled after each
certificate compression advertisement.
See test CertificateCompression_TwoEncodedCertificateRequests. */
ss->xtnData.certificateCompressionAdvertised = PR_FALSE;
PORT_Free(decodedCert);
return SECSuccess;
loser:
PORT_Free(decodedCert);
return SECFailure;
}
/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
* tls13 Certificate message.
* Caller must hold Handshake and RecvBuf locks.
*/
static SECStatus
tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed)
{
SECStatus rv;
SECItem context = { siBuffer, NULL, 0 };
SECItem certList;
PRBool first = PR_TRUE;
ssl3CertNode *lastCert = NULL;
SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
rv = tls13_EnsureCerticateExpected(ss);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
/* We can ignore any other cleartext from the client. */
if (ss->sec.isServer && IS_DTLS(ss)) {
ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
dtls_ReceivedFirstMessageInFlight(ss);
}
/* AlreadyHashed is true only when Certificate Compression is used. */
if (ss->firstHsDone && !alreadyHashed) {
rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
}
if (!ss->firstHsDone && ss->sec.isServer) {
/* Our first shot an getting an RTT estimate. If the client took extra
* time to fetch a certificate, this will be bad, but we can't do much
* about that. */
ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
}
/* Process the context string */
rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
if (rv != SECSuccess)
return SECFailure;
if (ss->ssl3.clientCertRequested) {
PORT_Assert(ss->sec.isServer);
if (SECITEM_CompareItem(&context, &ss->xtnData.certReqContext) != 0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
return SECFailure;
}
}
rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
if (rv != SECSuccess) {
return SECFailure;
}
if (length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
return SECFailure;
}
if (!certList.len) {
if (!ss->sec.isServer) {
/* Servers always need to send some cert. */
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
return SECFailure;
} else {
/* This is TLS's version of a no_certificate alert. */
/* I'm a server. I've requested a client cert. He hasn't got one. */
rv = ssl3_HandleNoCertificate(ss);
if (rv != SECSuccess) {
return SECFailure;
}
TLS13_SET_HS_STATE(ss, wait_finished);
return SECSuccess;
}
}
/* Now clean up. */
ssl3_CleanupPeerCerts(ss);
ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (ss->ssl3.peerCertArena == NULL) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
while (certList.len) {
SECItem derCert; // will hold a weak reference into certList
rv = tls13_HandleCertificateEntry(ss, &certList, first,
&derCert);
if (rv != SECSuccess) {
ss->xtnData.signedCertTimestamps.len = 0;
return SECFailure;
}
if (first) {
ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &derCert,
NULL, PR_FALSE, PR_TRUE);
if (!ss->sec.peerCert) {
PRErrorCode errCode = PORT_GetError();
switch (errCode) {
case PR_OUT_OF_MEMORY_ERROR:
case SEC_ERROR_BAD_DATABASE:
case SEC_ERROR_NO_MEMORY:
FATAL_ERROR(ss, errCode, internal_error);
return SECFailure;
default:
ssl3_SendAlertForCertError(ss, errCode);
return SECFailure;
}
}
if (ss->xtnData.signedCertTimestamps.len) {
sslSessionID *sid = ss->sec.ci.sid;
rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
&ss->xtnData.signedCertTimestamps);
ss->xtnData.signedCertTimestamps.len = 0;
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
}
} else {
ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,
ssl3CertNode);
if (!c) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
c->derCert = SECITEM_ArenaDupItem(ss->ssl3.peerCertArena,
&derCert);
c->next = NULL;
if (lastCert) {
lastCert->next = c;
} else {
ss->ssl3.peerCertChain = c;
}
lastCert = c;
}
first = PR_FALSE;
}
SECKEY_UpdateCertPQG(ss->sec.peerCert);
return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
}
/* Add context to the hash functions as described in
[draft-ietf-tls-tls13; Section 4.9.1] */
SECStatus
tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
SSLHashType algorithm, PRBool sending,
SSL3Hashes *tbsHash)
{
SECStatus rv = SECSuccess;
PK11Context *ctx;
const unsigned char context_padding[] = {
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
};
const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
: server_cert_verify_string;
unsigned int hashlength;
/* Double check that we are doing the same hash.*/
PORT_Assert(hashes->len == tls13_GetHashSize(ss));
ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
if (!ctx) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
goto loser;
}
PORT_Assert(SECFailure);
PORT_Assert(!SECSuccess);
PRINT_BUF(50, (ss, "TLS 1.3 hash without context", hashes->u.raw, hashes->len));
PRINT_BUF(50, (ss, "Context string", context_string, strlen(context_string)));
rv |= PK11_DigestBegin(ctx);
rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
strlen(context_string) + 1); /* +1 includes the terminating 0 */
rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
/* Update the hash in-place */
rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
PK11_DestroyContext(ctx, PR_TRUE);
PRINT_BUF(50, (ss, "TLS 1.3 hash with context", tbsHash->u.raw, hashlength));
tbsHash->len = hashlength;
tbsHash->hashAlg = algorithm;
if (rv) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
return SECSuccess;
loser:
return SECFailure;
}
/*
* Derive-Secret(Secret, Label, Messages) =
* HKDF-Expand-Label(Secret, Label,
* Hash(Messages) + Hash(resumption_context), L))
*/
SECStatus
tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
const char *label,
unsigned int labelLen,
const SSL3Hashes *hashes,
PK11SymKey **dest,
SSLHashType hash)
{
SECStatus rv;
rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
label, labelLen, CKM_HKDF_DERIVE,
tls13_GetHashSizeForHash(hash),
ss->protocolVariant, dest);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
return SECSuccess;
}
/* Convenience wrapper for the empty hash. */
SECStatus
tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
const char *label,
unsigned int labelLen,
PK11SymKey **dest,
SSLHashType hash)
{
SSL3Hashes hashes;
SECStatus rv;
PRUint8 buf[] = { 0 };
rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
if (rv != SECSuccess) {
return SECFailure;
}
return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
}
/* Convenience wrapper that lets us supply a separate prefix and suffix. */
static SECStatus
tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
const char *prefix,
const char *suffix,
const char *keylogLabel,
PK11SymKey **dest)
{
SECStatus rv;
SSL3Hashes hashes;
char buf[100];
const char *label;
if (prefix) {
if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
(void)PR_snprintf(buf, sizeof(buf), "%s %s",
prefix, suffix);
label = buf;
} else {
label = suffix;
}
SSL_TRC(3, ("%d: TLS13[%d]: deriving secret '%s'",
SSL_GETPID(), ss->fd, label));
rv = tls13_ComputeHandshakeHashes(ss, &hashes);
if (rv != SECSuccess) {
PORT_Assert(0); /* Should never fail */
ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = tls13_DeriveSecret(ss, key, label, strlen(label),
&hashes, dest, tls13_GetHash(ss));
if (rv != SECSuccess) {
return SECFailure;
}
if (keylogLabel) {
ssl3_RecordKeyLog(ss, keylogLabel, *dest);
}
return SECSuccess;
}
SECStatus
SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
{
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SecretCallback",
SSL_GETPID(), fd));
return SECFailure;
}
ssl_Get1stHandshakeLock(ss);
ssl_GetSSL3HandshakeLock(ss);
ss->secretCallback = cb;
ss->secretCallbackArg = arg;
ssl_ReleaseSSL3HandshakeLock(ss);
ssl_Release1stHandshakeLock(ss);
return SECSuccess;
}
/* Derive traffic keys for the next cipher spec in the queue. */
static SECStatus
tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
TrafficKeyType type,
PRBool deleteSecret)
{
size_t keySize = spec->cipherDef->key_size;
size_t ivSize = spec->cipherDef->iv_size +
spec->cipherDef->explicit_nonce_size; /* This isn't always going to
* work, but it does for
* AES-GCM */
CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
PK11SymKey **prkp = NULL;
PK11SymKey *prk = NULL;
PRBool clientSecret;
SECStatus rv;
/* These labels are just used for debugging. */
static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
static const char kHkdfPhaseApplicationDataKeys[] = "application data";
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
clientSecret = !tls13_UseServerSecret(ss, spec->direction);
switch (type) {
case TrafficKeyEarlyApplicationData:
PORT_Assert(clientSecret);
prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
break;
case TrafficKeyHandshake:
prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
: &ss->ssl3.hs.serverHsTrafficSecret;
spec->phase = kHkdfPhaseHandshakeKeys;
break;
case TrafficKeyApplicationData:
prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
: &ss->ssl3.hs.serverTrafficSecret;
spec->phase = kHkdfPhaseApplicationDataKeys;
break;
default:
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
PORT_Assert(0);
return SECFailure;
}
PORT_Assert(prkp != NULL);
prk = *prkp;
SSL_TRC(3, ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)",
SSL_GETPID(), ss->fd, SPEC_DIR(spec),
spec->epoch, spec->phase));
rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
NULL, 0,
kHkdfPurposeKey, strlen(kHkdfPurposeKey),
bulkAlgorithm, keySize,
ss->protocolVariant,
&spec->keyMaterial.key);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
PORT_Assert(0);
goto loser;
}
if (IS_DTLS(ss) && spec->epoch > 0) {
rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
ss->protocolVariant, prk, kHkdfPurposeSn,
strlen(kHkdfPurposeSn), &spec->maskContext);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
PORT_Assert(0);
goto loser;
}
}
rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
NULL, 0,
kHkdfPurposeIv, strlen(kHkdfPurposeIv),
ss->protocolVariant,
spec->keyMaterial.iv, ivSize);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
PORT_Assert(0);
goto loser;
}
if (deleteSecret) {
PK11_FreeSymKey(prk);
*prkp = NULL;
}
return SECSuccess;
loser:
return SECFailure;
}
void
tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
{
/* Set the record version to pretend to be (D)TLS 1.2. */
if (IS_DTLS(ss)) {
spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
} else {
spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_2;
}
SSL_TRC(10, ("%d: TLS13[%d]: set spec=%d record version to 0x%04x",
SSL_GETPID(), ss->fd, spec, spec->recordVersion));
}
static SECStatus
tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
{
ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(spec->epoch);
/* Version isn't set when we send 0-RTT data. */
spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version);
ssl_SaveCipherSpec(ss, spec);
/* We want to keep read cipher specs around longer because
* there are cases where we might get either epoch N or
* epoch N+1. */
if (IS_DTLS(ss) && spec->direction == ssl_secret_read) {
ssl_CipherSpecAddRef(spec);
}
SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x",
SSL_GETPID(), ss->fd, suite));
spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
if (spec->epoch == TrafficKeyEarlyApplicationData) {
if (ss->xtnData.selectedPsk &&
ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
}
}
tls13_SetSpecRecordVersion(ss, spec);
/* The record size limit is reduced by one so that the remainder of the
* record handling code can use the same checks for all versions. */
if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
? ss->opt.recordSizeLimit
: ss->xtnData.recordSizeLimit) -
1;
} else {
spec->recordSizeLimit = MAX_FRAGMENT_LENGTH;
}
return SECSuccess;
}
/*
* Initialize the cipher context. All TLS 1.3 operations are AEAD,
* so they are all message contexts.
*/
static SECStatus
tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
{
CK_MECHANISM_TYPE encMechanism;
CK_ATTRIBUTE_TYPE encMode;
SECItem iv;
SSLCipherAlgorithm calg;
calg = spec->cipherDef->calg;
encMechanism = ssl3_Alg2Mech(calg);
encMode = CKA_NSS_MESSAGE | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT);
iv.data = NULL;
iv.len = 0;
/*
* build the context
*/
spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
spec->keyMaterial.key,
&iv);
if (!spec->cipherContext) {
ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
return SECFailure;
}
return SECSuccess;
}
/*
* Called before sending alerts to set up the right key on the client.
* We might encounter errors during the handshake where the current
* key is ClearText or EarlyApplicationData. This
* function switches to the Handshake key if possible.
*/
SECStatus
tls13_SetAlertCipherSpec(sslSocket *ss)
{
SECStatus rv;
if (ss->sec.isServer) {
return SECSuccess;
}
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
return SECSuccess;
}
if (TLS13_IN_HS_STATE(ss, wait_server_hello)) {
return SECSuccess;
}
if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
(ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
return SECSuccess;
}
rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
ssl_secret_write, PR_FALSE);
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
return SECSuccess;
}
/* Install a new cipher spec for this direction.
*
* During the handshake, the values for |epoch| take values from the
* TrafficKeyType enum. Afterwards, key update increments them.
*/
static SECStatus
tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
SSLSecretDirection direction, PRBool deleteSecret)
{
TrafficKeyType type;
SECStatus rv;
ssl3CipherSpec *spec = NULL;
ssl3CipherSpec **specp;
/* Flush out old handshake data. */
ssl_GetXmitBufLock(ss);
rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
ssl_ReleaseXmitBufLock(ss);
if (rv != SECSuccess) {
return SECFailure;
}
/* Create the new spec. */
spec = ssl_CreateCipherSpec(ss, direction);
if (!spec) {
return SECFailure;
}
spec->epoch = epoch;
spec->nextSeqNum = 0;
if (IS_DTLS(ss)) {
dtls_InitRecvdRecords(&spec->recvdRecords);
}
/* This depends on spec having a valid direction and epoch. */
rv = tls13_SetupPendingCipherSpec(ss, spec);
if (rv != SECSuccess) {
goto loser;
}
type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch);
rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
if (rv != SECSuccess) {
goto loser;
}
rv = tls13_InitPendingContext(ss, spec);
if (rv != SECSuccess) {
goto loser;
}
/* Now that we've set almost everything up, finally cut over. */
specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
ssl_GetSpecWriteLock(ss);
ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
*specp = spec; /* Overwrite. */
ssl_ReleaseSpecWriteLock(ss);
SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s",
SSL_GETPID(), ss->fd, SSL_ROLE(ss), spec->epoch,
spec->phase, SPEC_DIR(spec)));
return SECSuccess;
loser:
ssl_CipherSpecRelease(spec);
return SECFailure;
}
SECStatus
tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
{
SECStatus rv;
PK11Context *ctx = NULL;
PRBool useEchInner;
sslBuffer *transcript;
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
/* Backup: if we haven't done any hashing, then hash now.
* This happens when we are doing 0-RTT on the client. */
ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
if (!ctx) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
return SECFailure;
}
if (PK11_DigestBegin(ctx) != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
/* One might expect this to use ss->ssl3.hs.echAccepted,
* but with 0-RTT we don't know that yet. */
useEchInner = ss->sec.isServer ? PR_FALSE : !!ss->ssl3.hs.echHpkeCtx;
transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
PRINT_BUF(10, (ss, "Handshake hash computed over saved messages",
transcript->buf,
transcript->len));
if (PK11_DigestOp(ctx,
transcript->buf,
transcript->len) != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
} else {
if (ss->firstHsDone) {
ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
} else {
ctx = PK11_CloneContext(ss->ssl3.hs.sha);
}
if (!ctx) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
return SECFailure;
}
}
rv = PK11_DigestFinal(ctx, hashes->u.raw,
&hashes->len,
sizeof(hashes->u.raw));
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
goto loser;
}
PRINT_BUF(10, (ss, "Handshake hash", hashes->u.raw, hashes->len));
PORT_Assert(hashes->len == tls13_GetHashSize(ss));
PK11_DestroyContext(ctx, PR_TRUE);
return SECSuccess;
loser:
PK11_DestroyContext(ctx, PR_TRUE);
return SECFailure;
}
TLS13KeyShareEntry *
tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
{
TLS13KeyShareEntry *n;
PORT_Assert(o);
n = PORT_ZNew(TLS13KeyShareEntry);
if (!n) {
return NULL;
}
if (SECSuccess != SECITEM_CopyItem(NULL, &n->key_exchange, &o->key_exchange)) {
PORT_Free(n);
return NULL;
}
n->group = o->group;
return n;
}
void
tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
{
if (!offer) {
return;
}
SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE);
PORT_ZFree(offer, sizeof(*offer));
}
void
tls13_DestroyKeyShares(PRCList *list)
{
PRCList *cur_p;
/* The list must be initialized. */
PORT_Assert(PR_LIST_HEAD(list));
while (!PR_CLIST_IS_EMPTY(list)) {
cur_p = PR_LIST_TAIL(list);
PR_REMOVE_LINK(cur_p);
tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
}
}
void
tls13_DestroyEarlyData(PRCList *list)
{
PRCList *cur_p;
while (!PR_CLIST_IS_EMPTY(list)) {
TLS13EarlyData *msg;
cur_p = PR_LIST_TAIL(list);
msg = (TLS13EarlyData *)cur_p;
PR_REMOVE_LINK(cur_p);
SECITEM_ZfreeItem(&msg->data, PR_FALSE);
PORT_ZFree(msg, sizeof(*msg));
}
}
/* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
* nonce algorithm:
*
* The length of the per-record nonce (iv_length) is set to max(8 bytes,
* N_MIN) for the AEAD algorithm (see [RFC5116] Section 4). An AEAD
* algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
* The per-record nonce for the AEAD construction is formed as follows:
*
* 1. The 64-bit record sequence number is padded to the left with
* zeroes to iv_length.
*
* 2. The padded sequence number is XORed with the static
* client_write_iv or server_write_iv, depending on the role.
*
* The resulting quantity (of length iv_length) is used as the per-
* record nonce.
*
* Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
*
* See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
*/
static void
tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
const unsigned char *nonce, unsigned int nonceLen,
unsigned char *ivOut, unsigned int ivOutLen)
{
size_t i;
unsigned int offset = ivOutLen - nonceLen;
PORT_Assert(ivInLen <= ivOutLen);
PORT_Assert(nonceLen <= ivOutLen);
PORT_Memset(ivOut, 0, ivOutLen);
PORT_Memcpy(ivOut, ivIn, ivInLen);
/* XOR the last n bytes of the IV with the nonce (should be a counter). */
for (i = 0; i < nonceLen; ++i) {
ivOut[offset + i] ^= nonce[i];
}
PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen));
}
/* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
* counter, but it doesn't know about the DTLS epic, so we add it here.
*/
unsigned int
tls13_SetupAeadIv(PRBool isDTLS, SSL3ProtocolVersion v, unsigned char *ivOut, unsigned char *ivIn,
unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
{
PORT_Memcpy(ivOut, ivIn, ivLen);
if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) {
/* handle the tls 1.2 counter mode case, the epoc is copied
* instead of xored. We accomplish this by clearing ivOut
* before running xor. */
if (offset >= ivLen) {
ivOut[offset] = ivOut[offset + 1] = 0;
}
ivOut[offset] ^= (unsigned char)(epoch >> BPB) & 0xff;
ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
offset += 2;
}
return offset;
}
/*
* Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
* ways.
* 1) If context is not supplied, it treats the operation as a single shot
* and creates a context from symKey and mech.
* 2) It always assumes the tag will be at the end of the buffer
* (in on decrypt, out on encrypt) just like the old single shot.
* 3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
* nonce.
* NOTE is context is supplied, symKey and mech are ignored
*/
SECStatus
tls13_AEAD(PK11Context *context, PRBool decrypt,
CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
const unsigned char *nonceIn, unsigned int nonceLen,
const unsigned char *aad, unsigned int aadLen,
unsigned char *out, unsigned int *outLen, unsigned int maxout,
unsigned int tagLen, const unsigned char *in, unsigned int inLen)
{
unsigned char *tag;
unsigned char iv[MAX_IV_LENGTH];
unsigned char tagbuf[HASH_LENGTH_MAX];
SECStatus rv;
/* must have either context or the symKey set */
if (!context) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
PORT_Assert(ivLen <= MAX_IV_LENGTH);
PORT_Assert(tagLen <= HASH_LENGTH_MAX);
if (!ivOut) {
ivOut = iv; /* caller doesn't need a returned, iv */
}
if (ivGen == CKG_NO_GENERATE) {
tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
} else if (ivIn != ivOut) {
PORT_Memcpy(ivOut, ivIn, ivLen);
}
if (decrypt) {
inLen = inLen - tagLen;
tag = (unsigned char *)in + inLen;
/* tag is const on decrypt, but returned on encrypt */
} else {
/* tag is written to a separate buffer, then added to the end
* of the actual output buffer. This allows output buffer to be larger
* than the input buffer and everything still work */
tag = tagbuf;
}
rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
out, (int *)outLen, maxout, tag, tagLen, in, inLen);
/* on encrypt SSL always puts the tag at the end of the buffer */
if ((rv == SECSuccess) && !(decrypt)) {
unsigned int len = *outLen;
/* make sure there is still space */
if (len + tagLen > maxout) {
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
return SECFailure;
}
PORT_Memcpy(out + len, tag, tagLen);
*outLen += tagLen;
}
return rv;
}
static SECStatus
tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
SECStatus rv;
PRUint32 innerLength;
SECItem oldAlpn = { siBuffer, NULL, 0 };
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
SSL_GETPID(), ss->fd));
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
wait_encrypted_extensions);
if (rv != SECSuccess) {
return SECFailure;
}
rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* Alert already sent. */
}
if (innerLength != length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
illegal_parameter);
return SECFailure;
}
/* If we are doing 0-RTT, then we already have an ALPN value. Stash
* it for comparison. */
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
oldAlpn = ss->xtnData.nextProto;
ss->xtnData.nextProto.data = NULL;
ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
}
rv = ssl3_ParseExtensions(ss, &b, &length);
if (rv != SECSuccess) {
return SECFailure; /* Error code set below */
}
/* Handle the rest of the extensions. */
rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
if (rv != SECSuccess) {
return SECFailure; /* Error code set below */
}
/* We can only get here if we offered 0-RTT. */
if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
if (!ss->xtnData.selectedPsk) {
/* Illegal to accept 0-RTT without also accepting PSK. */
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
illegal_parameter);
}
ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
/* Check that the server negotiated the same ALPN (if any). */
if (SECITEM_CompareItem(&oldAlpn, &ss->xtnData.nextProto)) {
SECITEM_FreeItem(&oldAlpn, PR_FALSE);
FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,
illegal_parameter);
return SECFailure;
}
/* Check that the server negotiated the same cipher suite. */
if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
illegal_parameter);
return SECFailure;
}
} else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
/* Though we sent 0-RTT, the early_data extension wasn't present so the
* state is unmodified; the server must have rejected 0-RTT. */
ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
} else {
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
(ss->ssl3.hs.helloRetry &&
ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored));
}
SECITEM_FreeItem(&oldAlpn, PR_FALSE);
if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
TLS13_SET_HS_STATE(ss, wait_finished);
} else {
TLS13_SET_HS_STATE(ss, wait_cert_request);
}
/* Client is done with any PSKs */
tls13_DestroyPskList(&ss->ssl3.hs.psks);
ss->xtnData.selectedPsk = NULL;
return SECSuccess;
}
static SECStatus
tls13_SendEncryptedExtensions(sslSocket *ss)
{
sslBuffer extensions = SSL_BUFFER_EMPTY;
SECStatus rv;
SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
if (rv != SECSuccess) {
return SECFailure;
}
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
SSL_BUFFER_LEN(&extensions) + 2);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
goto loser;
}
rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
goto loser;
}
sslBuffer_Clear(&extensions);
return SECSuccess;
loser:
sslBuffer_Clear(&extensions);
return SECFailure;
}
SECStatus
tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
{
SECStatus rv = SECFailure;
SECItem buf = { siBuffer, NULL, 0 };
unsigned int len;
SSLHashType hashAlg;
SSL3Hashes hash;
SSL3Hashes tbsHash; /* The hash "to be signed". */
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(3, ("%d: TLS13[%d]: send certificate_verify handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
rv = tls13_ComputeHandshakeHashes(ss, &hash);
if (rv != SECSuccess) {
return SECFailure;
}
/* We should have picked a signature scheme when we received a
* CertificateRequest, or when we picked a server certificate. */
PORT_Assert(ss->ssl3.hs.signatureScheme != ssl_sig_none);
if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
PR_TRUE, &tbsHash);
if (rv != SECSuccess) {
return SECFailure;
}
rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
if (rv == SECSuccess && !ss->sec.isServer) {
/* Remember the info about the slot that did the signing.
* Later, when doing an SSL restart handshake, verify this.
* These calls are mere accessors, and can't fail.
*/
PK11SlotInfo *slot;
sslSessionID *sid = ss->sec.ci.sid;
slot = PK11_GetSlotFromPrivateKey(privKey);
sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
sid->u.ssl3.clAuthValid = PR_TRUE;
PK11_FreeSlot(slot);
}
if (rv != SECSuccess) {
goto done; /* err code was set by ssl3_SignHashes */
}
len = buf.len + 2 + 2;
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
if (rv != SECSuccess) {
goto done; /* error code set by AppendHandshake */
}
rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
if (rv != SECSuccess) {
goto done; /* err set by AppendHandshakeNumber */
}
rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
if (rv != SECSuccess) {
goto done; /* error code set by AppendHandshake */
}
done:
/* For parity with the allocation functions, which don't use
* SECITEM_AllocItem(). */
if (buf.data)
PORT_Free(buf.data);
return rv;
}
/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
* tls13 CertificateVerify message
* Caller must hold Handshake and RecvBuf locks.
*/
SECStatus
tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
CERTSubjectPublicKeyInfo *spki;
SECKEYPublicKey *pubKey = NULL;
SECItem signed_hash = { siBuffer, NULL, 0 };
SECStatus rv;
SSLSignatureScheme sigScheme;
SSLHashType hashAlg;
SSL3Hashes tbsHash;
SSL3Hashes hashes;
SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY,
wait_cert_verify);
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_ComputeHandshakeHashes(ss, &hashes);
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->firstHsDone) {
rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
} else {
rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
}
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, illegal_parameter);
return SECFailure;
}
/* Set the |spki| used to verify the handshake. When verifying with a
* delegated credential (DC), this corresponds to the DC public key;
* otherwise it correspond to the public key of the peer's end-entity
* certificate.
*/
if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
/* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
* to match CertificateVerify.scheme.
* DelegatedCredential.cred.expected_cert_verify_algorithm must also be
* the same as was reported in ssl3_AuthCertificate.
*/
if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
return SECFailure;
}
/* Verify the DC has three steps: (1) use the peer's end-entity
* certificate to verify DelegatedCredential.signature, (2) check that
* the certificate has the correct key usage, and (3) check that the DC
* hasn't expired.
*/
rv = tls13_VerifyDelegatedCredential(ss, dc);
if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
return SECFailure;
}
SSL_TRC(3, ("%d: TLS13[%d]: Verifying with delegated credential",
SSL_GETPID(), ss->fd));
spki = dc->spki;
} else {
spki = &ss->sec.peerCert->subjectPublicKeyInfo;
}
rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
if (rv != SECSuccess) {
/* Error set already */
FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
return SECFailure;
}
hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE, &tbsHash);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error);
return SECFailure;
}
rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
if (rv != SECSuccess) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
return SECFailure;
}
if (length != 0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, decode_error);
return SECFailure;
}
pubKey = SECKEY_ExtractPublicKey(spki);
if (pubKey == NULL) {
ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
return SECFailure;
}
rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
&tbsHash, &signed_hash);
if (rv != SECSuccess) {
FATAL_ERROR(ss, PORT_GetError(), decrypt_error);
goto loser;
}
/* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
if (!ss->sec.isServer) {
ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
rv = ssl_SetAuthKeyBits(ss, pubKey);
if (rv != SECSuccess) {
goto loser; /* Alert sent and code set. */
}
if (prelimAuthKeyBits != ss->sec.authKeyBits) {
FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
goto loser;
}
}
/* Request a client certificate now if one was requested. */
if (ss->ssl3.hs.clientCertRequested) {
PORT_Assert(!ss->sec.isServer);
rv = ssl3_BeginHandleCertificateRequest(
ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
&ss->xtnData.certReqAuthorities);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
}
SECKEY_DestroyPublicKey(pubKey);
TLS13_SET_HS_STATE(ss, wait_finished);
return SECSuccess;
loser:
SECKEY_DestroyPublicKey(pubKey);
return SECFailure;
}
/* Compute the PSK binder hash over:
* Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
* |len| bytes of |buf| */
static SECStatus
tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
SSL3Hashes *hashes, SSLHashType hashType)
{
SECStatus rv;
PK11Context *ctx = NULL;
sslBuffer *clientResidual = NULL;
if (!ss->sec.isServer) {
/* On the server, HRR residual is already buffered. */
clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
}
PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PRINT_BUF(10, (NULL, "Binder computed over ClientHello",
b, length));
ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
if (!ctx) {
goto loser;
}
rv = PK11_DigestBegin(ctx);
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
if (clientResidual && clientResidual->len) {
PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,
clientResidual->len));
rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
}
if (IS_DTLS(ss) && !ss->sec.isServer) {
/* Removing the unnecessary header fields.
* See ssl3_AppendHandshakeHeader.*/
PORT_Assert(length >= 12);
rv = PK11_DigestOp(ctx, b, 4);
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
rv = PK11_DigestOp(ctx, b + 12, length - 12);
} else {
rv = PK11_DigestOp(ctx, b, length);
}
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
goto loser;
}
PK11_DestroyContext(ctx, PR_TRUE);
PRINT_BUF(10, (NULL, "PSK Binder hash", hashes->u.raw, hashes->len));
return SECSuccess;
loser:
if (ctx) {
PK11_DestroyContext(ctx, PR_TRUE);
}
return SECFailure;
}
/* Compute and inject the PSK Binder for sending.
*
* When sending a ClientHello, we construct all the extensions with a dummy
* value for the binder. To construct the binder, we commit the entire message
* up to the point where the binders start. Then we calculate the hash using
* the saved message (in ss->ssl3.hs.messages). This is written over the dummy
* binder, after which we write the remainder of the binder extension. */
SECStatus
tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
{
SSL3Hashes hashes;
SECStatus rv;
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
unsigned int size = tls13_GetHashSizeForHash(psk->hash);
unsigned int prefixLen = extensions->len - size - 3;
unsigned int finishedLen;
PORT_Assert(extensions->len >= size + 3);
rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
if (rv != SECSuccess) {
return SECFailure;
}
/* Only write the extension up to the point before the binders. Assume that
* the pre_shared_key extension is at the end of the buffer. Don't write
* the binder, or the lengths that precede it (a 2 octet length for the list
* of all binders, plus a 1 octet length for the binder length). */
rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
if (rv != SECSuccess) {
return SECFailure;
}
/* Calculate the binder based on what has been written out. */
rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
if (rv != SECSuccess) {
return SECFailure;
}
/* Write the binder into the extensions buffer, over the zeros we reserved
* previously. This avoids an allocation and means that we don't need a
* separate write for the extra bits that precede the binder. */
PORT_Assert(psk->binderKey);
rv = tls13_ComputeFinished(ss, psk->binderKey,
psk->hash, &hashes, PR_TRUE,
extensions->buf + extensions->len - size,
&finishedLen, size);
if (rv != SECSuccess) {
return SECFailure;
}
PORT_Assert(finishedLen == size);
/* Write out the remainder of the extension. */
rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
extensions->len - prefixLen);
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
static SECStatus
tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
SSLHashType hashType, const SSL3Hashes *hashes,
PRBool sending, PRUint8 *output, unsigned int *outputLen,
unsigned int maxOutputLen)
{
SECStatus rv;
PK11Context *hmacCtx = NULL;
CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
SECItem param = { siBuffer, NULL, 0 };
unsigned int outputLenUint;
const char *label = kHkdfLabelFinishedSecret;
PK11SymKey *secret = NULL;
PORT_Assert(baseKey);
SSL_TRC(3, ("%d: TLS13[%d]: %s calculate finished",
SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
PRINT_BUF(50, (ss, "Handshake hash", hashes->u.raw, hashes->len));
/* Now derive the appropriate finished secret from the base secret. */
rv = tls13_HkdfExpandLabel(baseKey, hashType,
NULL, 0, label, strlen(label),
tls13_GetHmacMechanismFromHash(hashType),
tls13_GetHashSizeForHash(hashType),
ss->protocolVariant, &secret);
if (rv != SECSuccess) {
goto abort;
}
PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType));
hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN,
secret, ¶m);
if (!hmacCtx) {
goto abort;
}
rv = PK11_DigestBegin(hmacCtx);
if (rv != SECSuccess)
goto abort;
rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
if (rv != SECSuccess)
goto abort;
PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType));
rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
if (rv != SECSuccess)
goto abort;
*outputLen = outputLenUint;
PK11_FreeSymKey(secret);
PK11_DestroyContext(hmacCtx, PR_TRUE);
PRINT_BUF(50, (ss, "finished value", output, outputLenUint));
return SECSuccess;
abort:
if (secret) {
PK11_FreeSymKey(secret);
}
if (hmacCtx) {
PK11_DestroyContext(hmacCtx, PR_TRUE);
}
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
static SECStatus
tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
{
SECStatus rv;
PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
unsigned int finishedLen;
SSL3Hashes hashes;
SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
rv = tls13_ComputeHandshakeHashes(ss, &hashes);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
ssl_GetSpecReadLock(ss);
rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE,
finishedBuf, &finishedLen, sizeof(finishedBuf));
ssl_ReleaseSpecReadLock(ss);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
if (rv != SECSuccess) {
return SECFailure; /* Error code already set. */
}
rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
if (rv != SECSuccess) {
return SECFailure; /* Error code already set. */
}
/* TODO(ekr@rtfm.com): Record key log */
return SECSuccess;
}
static SECStatus
tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
PK11SymKey *secret,
PRUint8 *b, PRUint32 length,
const SSL3Hashes *hashes)
{
SECStatus rv;
PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
unsigned int finishedLen;
if (!hashes) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE,
finishedBuf, &finishedLen, sizeof(finishedBuf));
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
if (length != finishedLen) {
#ifndef UNSAFE_FUZZER_MODE
FATAL_ERROR(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED : SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
return SECFailure;
#endif
}
if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
#ifndef UNSAFE_FUZZER_MODE
FATAL_ERROR(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE,
decrypt_error);
return SECFailure;
#endif
}
return SECSuccess;
}
static SECStatus
tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
PRUint8 *b, PRUint32 length)
{
SECStatus rv;
SSL3Hashes hashes;
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED,
wait_finished);
if (rv != SECSuccess) {
return SECFailure;
}
ss->ssl3.hs.endOfFlight = PR_TRUE;
rv = tls13_ComputeHandshakeHashes(ss, &hashes);
if (rv != SECSuccess) {
LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (ss->firstHsDone) {
rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
} else {
rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
}
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
return tls13_VerifyFinished(ss, ssl_hs_finished,
key, b, length, &hashes);
}
static SECStatus
tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
SECStatus rv;
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(3, ("%d: TLS13[%d]: client handle finished handshake",
SSL_GETPID(), ss->fd));
rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
b, length);
if (rv != SECSuccess) {
return SECFailure;
}
return tls13_SendClientSecondRound(ss);
}
static SECStatus
tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
SECStatus rv;
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(3, ("%d: TLS13[%d]: server handle finished handshake",
SSL_GETPID(), ss->fd));
if (!tls13_ShouldRequestClientAuth(ss)) {
/* Receiving this message might be the first sign we have that
* early data is over, so pretend we received EOED. */
rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
if (rv != SECSuccess) {
return SECFailure; /* Code already set. */
}
if (!tls13_IsPostHandshake(ss)) {
/* Finalize the RTT estimate. */
ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
}
}
rv = tls13_CommonHandleFinished(ss,
ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
b, length);
if (rv != SECSuccess) {
return SECFailure;
}
if (ss->firstHsDone) {
TLS13_SET_HS_STATE(ss, idle_handshake);
PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
ss->ssl3.hs.shaPostHandshake = NULL;
ss->ssl3.clientCertRequested = PR_FALSE;
if (ss->ssl3.hs.keyUpdateDeferred) {
rv = tls13_SendKeyUpdate(ss, ss->ssl3.hs.deferredKeyUpdateRequest,
PR_FALSE);
if (rv != SECSuccess) {
return SECFailure; /* error is set. */
}
ss->ssl3.hs.keyUpdateDeferred = PR_FALSE;
}
return SECSuccess;
}
if (!tls13_ShouldRequestClientAuth(ss) &&
(ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
dtls_ReceivedFirstMessageInFlight(ss);
}
rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
ssl_secret_read, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
if (IS_DTLS(ss)) {
ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
/* We need to keep the handshake cipher spec so we can
* read re-transmitted client Finished. */
rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
DTLS_RETRANSMIT_FINISHED_MS,
dtls13_HolddownTimerCb);
if (rv != SECSuccess) {
return SECFailure;
}
}
rv = tls13_ComputeFinalSecrets(ss);
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_FinishHandshake(ss);
if (rv != SECSuccess) {
return SECFailure;
}
ssl_GetXmitBufLock(ss);
/* If resumption, authType is the original value and not ssl_auth_psk. */
if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
rv = tls13_SendNewSessionTicket(ss, NULL, 0);
if (rv != SECSuccess) {
goto loser;
}
rv = ssl3_FlushHandshake(ss, 0);
if (rv != SECSuccess) {
goto loser;
}
}
ssl_ReleaseXmitBufLock(ss);
return SECSuccess;
loser:
ssl_ReleaseXmitBufLock(ss);
return SECFailure;
}
static SECStatus
tls13_FinishHandshake(sslSocket *ss)
{
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
/* The first handshake is now completed. */
ss->handshake = NULL;
/* Don't need this. */
PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
ss->ssl3.hs.clientHsTrafficSecret = NULL;
PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
ss->ssl3.hs.serverHsTrafficSecret = NULL;
TLS13_SET_HS_STATE(ss, idle_handshake);
return ssl_FinishHandshake(ss);
}
/* Do the parts of sending the client's second round that require
* the XmitBuf lock. */
static SECStatus
tls13_SendClientSecondFlight(sslSocket *ss)
{
SECStatus rv;
unsigned int offset = 0;
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(!ss->ssl3.hs.clientCertificatePending);
PRBool sendClientCert = !ss->ssl3.sendEmptyCert &&
ss->ssl3.clientCertChain != NULL &&
ss->ssl3.clientPrivateKey != NULL;
if (ss->firstHsDone) {
offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
}
if (ss->ssl3.sendEmptyCert) {
ss->ssl3.sendEmptyCert = PR_FALSE;
rv = ssl3_SendEmptyCertificate(ss);
/* Don't send verify */
if (rv != SECSuccess) {
goto alert_error; /* error code is set. */
}
} else if (sendClientCert) {
rv = tls13_SendCertificate(ss);
if (rv != SECSuccess) {
goto alert_error; /* err code was set. */
}
}
if (ss->firstHsDone) {
rv = ssl3_UpdatePostHandshakeHashes(ss,
SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
if (rv != SECSuccess) {
goto alert_error; /* err code was set. */
}
}
if (ss->ssl3.hs.clientCertRequested) {
SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
if (ss->xtnData.certReqAuthorities.arena) {
PORT_FreeArena(ss->xtnData.certReqAuthorities.arena, PR_FALSE);
ss->xtnData.certReqAuthorities.arena = NULL;
}
PORT_Memset(&ss->xtnData.certReqAuthorities, 0,
sizeof(ss->xtnData.certReqAuthorities));
ss->ssl3.hs.clientCertRequested = PR_FALSE;
}
if (sendClientCert) {
if (ss->firstHsDone) {
offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
}
rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
ss->ssl3.clientPrivateKey = NULL;
if (rv != SECSuccess) {
goto alert_error; /* err code was set. */
}
if (ss->firstHsDone) {
rv = ssl3_UpdatePostHandshakeHashes(ss,
SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
if (rv != SECSuccess) {
goto alert_error; /* err code was set. */
}
}
}
rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
if (rv != SECSuccess) {
goto alert_error; /* err code was set. */
}
rv = ssl3_FlushHandshake(ss, 0);
if (rv != SECSuccess) {
/* No point in sending an alert here because we're not going to
* be able to send it if we couldn't flush the handshake. */
goto error;
}
return SECSuccess;
alert_error:
FATAL_ERROR(ss, PORT_GetError(), internal_error);
return SECFailure;
error:
LOG_ERROR(ss, PORT_GetError());
return SECFailure;
}
static SECStatus
tls13_SendClientSecondRound(sslSocket *ss)
{
SECStatus rv;
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
/* Defer client authentication sending if we are still waiting for server
* authentication. This avoids unnecessary disclosure of client credentials
* to an unauthenticated server.
*/
if (ss->ssl3.hs.restartTarget) {
PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (ss->ssl3.hs.authCertificatePending || ss->ssl3.hs.clientCertificatePending) {
SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
" certificate authentication is still pending.",
SSL_GETPID(), ss->fd));
ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
PORT_SetError(PR_WOULD_BLOCK_ERROR);
return SECFailure;
}
rv = tls13_ComputeApplicationSecrets(ss);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
ssl_GetXmitBufLock(ss); /*******************************/
rv = tls13_SendEndOfEarlyData(ss);
ssl_ReleaseXmitBufLock(ss); /*******************************/
if (rv != SECSuccess) {
return SECFailure; /* Error code already set. */
}
} else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
!ss->ssl3.hs.helloRetry) {
ssl_GetXmitBufLock(ss); /*******************************/
rv = ssl3_SendChangeCipherSpecsInt(ss);
ssl_ReleaseXmitBufLock(ss); /*******************************/
if (rv != SECSuccess) {
return rv;
}
}
rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
ssl_secret_write, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
return SECFailure;
}
rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
ssl_secret_read, PR_FALSE);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
ssl_GetXmitBufLock(ss); /*******************************/
/* This call can't block, as clientAuthCertificatePending is checked above */
rv = tls13_SendClientSecondFlight(ss);
ssl_ReleaseXmitBufLock(ss); /*******************************/
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
ssl_secret_write, PR_FALSE);
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
rv = tls13_ComputeFinalSecrets(ss);
if (rv != SECSuccess) {
return SECFailure;
}
/* The handshake is now finished */
return tls13_FinishHandshake(ss);
}
/*
* enum { (65535) } TicketExtensionType;
*
* struct {
* TicketExtensionType extension_type;
* opaque extension_data<0..2^16-1>;
* } TicketExtension;
*
* struct {
* uint32 ticket_lifetime;
* uint32 ticket_age_add;
* opaque ticket_nonce<1..255>;
* opaque ticket<1..2^16-1>;
* TicketExtension extensions<0..2^16-2>;
* } NewSessionTicket;
*/
static SECStatus
tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
unsigned int appTokenLen)
{
PRUint16 message_length;
PK11SymKey *secret;
SECItem ticket_data = { 0, NULL, 0 };
SECStatus rv;
NewSessionTicket ticket = { 0 };
PRUint32 max_early_data_size_len = 0;
PRUint32 greaseLen = 0;
PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce);
SSL_TRC(3, ("%d: TLS13[%d]: send new session ticket message %d",
SSL_GETPID(), ss->fd, ss->ssl3.hs.ticketNonce));
ticket.flags = 0;
if (ss->opt.enable0RttData) {
ticket.flags |= ticket_allow_early_data;
max_early_data_size_len = 8; /* type + len + value. */
}
ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
if (ss->opt.enableGrease) {
greaseLen = 4; /* type + len + 0 (empty) */
}
/* The ticket age obfuscator. */
rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
sizeof(ticket.ticket_age_add));
if (rv != SECSuccess)
goto loser;
rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
sizeof(ticketNonce));
if (rv != SECSuccess) {
goto loser;
}
++ss->ssl3.hs.ticketNonce;
rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
tls13_GetHash(ss),
ticketNonce, sizeof(ticketNonce),
kHkdfLabelResumption,
strlen(kHkdfLabelResumption),
CKM_HKDF_DERIVE,
tls13_GetHashSize(ss),
ss->protocolVariant, &secret);
if (rv != SECSuccess) {
goto loser;
}
rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
secret, &ticket_data);
PK11_FreeSymKey(secret);
if (rv != SECSuccess)
goto loser;
message_length =
4 + /* lifetime */
4 + /* ticket_age_add */
1 + sizeof(ticketNonce) + /* ticket_nonce */
2 + /* extensions lentgh */
max_early_data_size_len + /* max_early_data_size extension length */
greaseLen + /* GREASE extension length */
2 + /* ticket length */
ticket_data.len;
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
message_length);
if (rv != SECSuccess)
goto loser;
/* This is a fixed value. */
rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
if (rv != SECSuccess)
goto loser;
rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
if (rv != SECSuccess)
goto loser;
/* The ticket nonce. */
rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
if (rv != SECSuccess)
goto loser;
/* Encode the ticket. */
rv = ssl3_AppendHandshakeVariable(
ss, ticket_data.data, ticket_data.len, 2);
if (rv != SECSuccess)
goto loser;
/* Extensions */
rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len + greaseLen, 2);
if (rv != SECSuccess)
goto loser;
/* GREASE NewSessionTicket:
* When sending a NewSessionTicket message in TLS 1.3, a server MAY select
* one or more GREASE extension values and advertise them as extensions
* with varying length and contents [RFC8701, SEction 4.1]. */
if (ss->opt.enableGrease) {
PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
PRUint16 grease;
rv = tls13_RandomGreaseValue(&grease);
if (rv != SECSuccess)
goto loser;
/* Extension type */
rv = ssl3_AppendHandshakeNumber(ss, grease, 2);
if (rv != SECSuccess)
goto loser;
/* Extension length */
rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
if (rv != SECSuccess)
goto loser;
}
/* Max early data size extension. */
if (max_early_data_size_len) {
rv = ssl3_AppendHandshakeNumber(
ss, ssl_tls13_early_data_xtn, 2);
if (rv != SECSuccess)
goto loser;
/* Length */
rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
if (rv != SECSuccess)
goto loser;
rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
if (rv != SECSuccess)
goto loser;
}
SECITEM_FreeItem(&ticket_data, PR_FALSE);
return SECSuccess;
loser:
if (ticket_data.data) {
SECITEM_FreeItem(&ticket_data, PR_FALSE);
}
return SECFailure;
}
SECStatus
SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
unsigned int tokenLen)
{
sslSocket *ss;
SECStatus rv;
ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
if (IS_DTLS(ss)) {
PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
return SECFailure;
}
if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
tokenLen > 0xffff) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
/* Disable tickets if we can trace this connection back to a PSK.
* We aren't able to issue tickets (currently) without a certificate.
* As PSK =~ resumption, there is no reason to do this. */
if (ss->sec.authType == ssl_auth_psk) {
PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
return SECFailure;
}
ssl_GetSSL3HandshakeLock(ss);
ssl_GetXmitBufLock(ss);
rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
if (rv == SECSuccess) {
rv = ssl3_FlushHandshake(ss, 0);
}
ssl_ReleaseXmitBufLock(ss);
ssl_ReleaseSSL3HandshakeLock(ss);
return rv;
}
static SECStatus
tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
{
SECStatus rv;
PRUint32 utmp;
NewSessionTicket ticket = { 0 };
SECItem data;
SECItem ticket_nonce;
SECItem ticket_data;
SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",
SSL_GETPID(), ss->fd));
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
idle_handshake);
if (rv != SECSuccess) {
return SECFailure;
}
if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
unexpected_message);
return SECFailure;
}
ticket.received_timestamp = ssl_Time(ss);
rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
&length);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
ticket.ticket.type = siBuffer;
rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
&b, &length);
if (rv != SECSuccess) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
return SECFailure;
}
ticket.ticket_age_add = PR_ntohl(utmp);
/* The nonce. */
rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
/* Get the ticket value. */
rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
if (rv != SECSuccess || !ticket_data.len) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
/* Parse extensions. */
rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
if (rv != SECSuccess || length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
rv = ssl3_HandleExtensions(ss, &data.data,
&data.len, ssl_hs_new_session_ticket);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
if (ss->xtnData.max_early_data_size) {
ticket.flags |= ticket_allow_early_data;
ticket.max_early_data_size = ss->xtnData.max_early_data_size;
}
if (!ss->opt.noCache) {
PK11SymKey *secret;
PORT_Assert(ss->sec.ci.sid);
rv = SECITEM_CopyItem(NULL, &ticket.ticket, &ticket_data);
if (rv != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
PRINT_BUF(50, (ss, "Caching session ticket",
ticket.ticket.data,
ticket.ticket.len));
/* Replace a previous session ticket when
* we receive a second NewSessionTicket message. */
if (ss->sec.ci.sid->cached == in_client_cache ||
ss->sec.ci.sid->cached == in_external_cache) {
/* Create a new session ID. */
sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE);
if (!sid) {
return SECFailure;
}
/* Copy over the peerCert. */
PORT_Assert(ss->sec.ci.sid->peerCert);
sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
if (!sid->peerCert) {
ssl_FreeSID(sid);
return SECFailure;
}
/* Destroy the old SID. */
ssl_UncacheSessionID(ss);
ssl_FreeSID(ss->sec.ci.sid);
ss->sec.ci.sid = sid;
}
ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
PORT_Assert(!ticket.ticket.data);
rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
tls13_GetHash(ss),
ticket_nonce.data, ticket_nonce.len,
kHkdfLabelResumption,
strlen(kHkdfLabelResumption),
CKM_HKDF_DERIVE,
tls13_GetHashSize(ss),
ss->protocolVariant, &secret);
if (rv != SECSuccess) {
return SECFailure;
}
rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
PK11_FreeSymKey(secret);
if (rv != SECSuccess) {
return SECFailure;
}
/* Cache the session. */
ssl_CacheSessionID(ss);
}
return SECSuccess;
}
#define _M_NONE 0
#define _M(a) (1 << PR_MIN(a, 31))
#define _M1(a) (_M(ssl_hs_##a))
#define _M2(a, b) (_M1(a) | _M1(b))
#define _M3(a, b, c) (_M1(a) | _M2(b, c))
static const struct {
PRUint16 ex_value;
PRUint32 messages;
} KnownExtensions[] = {
{ ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
{ ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
{ ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
{ ssl_signature_algorithms_cert_xtn, _M2(client_hello,
certificate_request) },
{ ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
{ ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
{ ssl_padding_xtn, _M1(client_hello) },
{ ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
hello_retry_request) },
{ ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
{ ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
{ ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
new_session_ticket) },
{ ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
certificate) },
{ ssl_cert_status_xtn, _M3(client_hello, certificate_request,
certificate) },
{ ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
{ ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
{ ssl_tls13_certificate_authorities_xtn, _M2(client_hello, certificate_request) },
{ ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
hello_retry_request) },
{ ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
{ ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
{ ssl_tls13_outer_extensions_xtn, _M_NONE /* Encoding/decoding only */ },
{ ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) },
{ ssl_certificate_compression_xtn, _M2(client_hello, certificate_request) }
};
tls13ExtensionStatus
tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
{
unsigned int i;
PORT_Assert((message == ssl_hs_client_hello) ||
(message == ssl_hs_server_hello) ||
(message == ssl_hs_hello_retry_request) ||
(message == ssl_hs_encrypted_extensions) ||
(message == ssl_hs_new_session_ticket) ||
(message == ssl_hs_certificate) ||
(message == ssl_hs_certificate_request));
for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) {
/* Hacky check for message numbers > 30. */
PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)));
if (KnownExtensions[i].ex_value == extension) {
break;
}
}
if (i >= PR_ARRAY_SIZE(KnownExtensions)) {
return tls13_extension_unknown;
}
/* Return "disallowed" if the message mask bit isn't set. */
if (!(_M(message) & KnownExtensions[i].messages)) {
return tls13_extension_disallowed;
}
return tls13_extension_allowed;
}
#undef _M
#undef _M1
#undef _M2
#undef _M3
/* We cheat a bit on additional data because the AEAD interface
* which doesn't have room for the record number. The AAD we
* format is serialized record number followed by the true AD
* (i.e., the record header) plus the serialized record number. */
static SECStatus
tls13_FormatAdditionalData(
sslSocket *ss,
const PRUint8 *header, unsigned int headerLen,
DTLSEpoch epoch, sslSequenceNumber seqNum,
PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
{
SECStatus rv;
sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength);
if (IS_DTLS_1_OR_12(ss)) {
rv = sslBuffer_AppendNumber(&buf, epoch, 2);
if (rv != SECSuccess) {
return SECFailure;
}
}
rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS_1_OR_12(ss) ? 6 : 8);
if (rv != SECSuccess) {
return SECFailure;
}
rv = sslBuffer_Append(&buf, header, headerLen);
if (rv != SECSuccess) {
return SECFailure;
}
*aadLength = buf.len;
return SECSuccess;
}
PRInt32
tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
{
PRInt32 reduced;
PORT_Assert(type == ssl_ct_application_data);
PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
PORT_Assert(!ss->firstHsDone);
if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
return toSend;
}
if (IS_DTLS(ss) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
/* Don't split application data records in DTLS. */
return 0;
}
reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining);
ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
return reduced;
}
SECStatus
tls13_ProtectRecord(sslSocket *ss,
ssl3CipherSpec *cwSpec,
SSLContentType type,
const PRUint8 *pIn,
PRUint32 contentLen,
sslBuffer *wrBuf)
{
const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
const int tagLen = cipher_def->tag_size;
SECStatus rv;
PORT_Assert(cwSpec->direction == ssl_secret_write);
SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",
SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,
cwSpec->nextSeqNum, contentLen));
if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
/* Copy the data into the wrBuf. We're going to encrypt in-place
* in the AEAD branch anyway */
PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), pIn, contentLen);
if (cipher_def->calg == ssl_calg_null) {
/* Shortcut for plaintext */
rv = sslBuffer_Skip(wrBuf, contentLen, NULL);
PORT_Assert(rv == SECSuccess);
} else {
PRUint8 hdr[13];
sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr));
PRBool needsLength;
PRUint8 aad[21];
const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
unsigned char ivOut[MAX_IV_LENGTH];
unsigned int aadLen;
unsigned int len;
PORT_Assert(cipher_def->type == type_aead);
/* If the following condition holds, we can skip the padding logic for
* DTLS 1.3 (4.2.3). This will be the case until we support a cipher
* with tag length < 15B. */
PORT_Assert(tagLen + 1 /* cType */ >= 16);
/* Add the content type at the end. */
*(SSL_BUFFER_NEXT(wrBuf) + contentLen) = type;
/* Create the header (ugly that we have to do it twice). */
rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
&buf, &needsLength);
if (rv != SECSuccess) {
return SECFailure;
}
if (needsLength) {
rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
if (rv != SECSuccess) {
return SECFailure;
}
}
rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf), SSL_BUFFER_LEN(&buf),
cwSpec->epoch, cwSpec->nextSeqNum,
aad, &aadLen, sizeof(aad));
if (rv != SECSuccess) {
return SECFailure;
}
/* set up initial IV value */
ivOffset = tls13_SetupAeadIv(IS_DTLS(ss), cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
ivOffset, ivLen, cwSpec->epoch);
rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE,
CKG_GENERATE_COUNTER_XOR, ivOffset * BPB,
ivOut, ivOut, ivLen, /* iv */
NULL, 0, /* nonce */
aad + sizeof(sslSequenceNumber), /* aad */
aadLen - sizeof(sslSequenceNumber),
SSL_BUFFER_NEXT(wrBuf), /* output */
&len, /* out len */
SSL_BUFFER_SPACE(wrBuf), /* max out */
tagLen,
SSL_BUFFER_NEXT(wrBuf), /* input */
contentLen + 1); /* input len */
if (rv != SECSuccess) {
PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
return SECFailure;
}
rv = sslBuffer_Skip(wrBuf, len, NULL);
PORT_Assert(rv == SECSuccess);
}
return SECSuccess;
}
/* Unprotect a TLS 1.3 record and leave the result in plaintext.
*
* Called by ssl3_HandleRecord. Caller must hold the spec read lock.
* Therefore, we MUST not call SSL3_SendAlert().
*
* If SECFailure is returned, we:
* 1. Set |*alert| to the alert to be sent.
* 2. Call PORT_SetError() with an appropriate code.
*/
SECStatus
tls13_UnprotectRecord(sslSocket *ss,
ssl3CipherSpec *spec,
SSL3Ciphertext *cText,
sslBuffer *plaintext,
SSLContentType *innerType,
SSL3AlertDescription *alert)
{
const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
const int tagLen = cipher_def->tag_size;
const int innerTypeLen = 1;
PRUint8 aad[21];
unsigned int aadLen;
SECStatus rv;
*alert = bad_record_mac; /* Default alert for most issues. */
PORT_Assert(spec->direction == ssl_secret_read);
SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",
SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,
cText->seqNum, cText->buf->len));
/* Verify that the outer content type is right.
*
* For the inner content type as well as lower TLS versions this is checked
* in ssl3con.c/ssl3_HandleNonApllicationData().
*
* For DTLS 1.3 this is checked in ssl3gthr.c/dtls_GatherData(). DTLS drops
* invalid records silently [RFC6347, Section 4.1.2.7].
*
* Also allow the DTLS short header in TLS 1.3. */
if (!(cText->hdr[0] == ssl_ct_application_data ||
(IS_DTLS(ss) &&
ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
(cText->hdr[0] & 0xe0) == 0x20))) {
SSL_TRC(3,
("%d: TLS13[%d]: record has invalid exterior type=%2.2x",
SSL_GETPID(), ss->fd, cText->hdr[0]));
PORT_SetError(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
*alert = unexpected_message;
return SECFailure;
}
/* We can perform this test in variable time because the record's total
* length and the ciphersuite are both public knowledge. */
if (cText->buf->len < tagLen) {
SSL_TRC(3,
("%d: TLS13[%d]: record too short to contain valid AEAD data",
SSL_GETPID(), ss->fd));
PORT_SetError(SSL_ERROR_BAD_MAC_READ);
return SECFailure;
}
/* Check if the ciphertext can be valid if we assume maximum plaintext and
* add the specific ciphersuite expansion.
* This way we detect overlong plaintexts/padding before decryption.
* This check enforces size limitations more strict than the RFC.
* (see RFC8446, Section 5.2) */
if (cText->buf->len > (spec->recordSizeLimit + innerTypeLen + tagLen)) {
*alert = record_overflow;
PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
return SECFailure;
}
/* Check the version number in the record. Stream only. */
if (!IS_DTLS(ss)) {
SSL3ProtocolVersion version =
((SSL3ProtocolVersion)cText->hdr[1] << 8) |
(SSL3ProtocolVersion)cText->hdr[2];
if (version != spec->recordVersion) {
/* Do we need a better error here? */
SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",
SSL_GETPID(), ss->fd));
return SECFailure;
}
}
/* Decrypt */
PORT_Assert(cipher_def->type == type_aead);
rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
spec->epoch, cText->seqNum,
aad, &aadLen, sizeof(aad));
if (rv != SECSuccess) {
return SECFailure;
}
rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
CKG_NO_GENERATE, 0, /* ignored for decrypt */
spec->keyMaterial.iv, NULL, ivLen, /* iv */
aad, sizeof(sslSequenceNumber), /* nonce */
aad + sizeof(sslSequenceNumber), /* aad */
aadLen - sizeof(sslSequenceNumber),
plaintext->buf, /* output */
&plaintext->len, /* outlen */
plaintext->space, /* maxout */
tagLen,
cText->buf->buf, /* in */
cText->buf->len); /* inlen */
if (rv != SECSuccess) {
if (IS_DTLS(ss)) {
spec->deprotectionFailures++;
}
SSL_TRC(3,
("%d: TLS13[%d]: record has bogus MAC",
SSL_GETPID(), ss->fd));
PORT_SetError(SSL_ERROR_BAD_MAC_READ);
return SECFailure;
}
/* There is a similar test in ssl3_HandleRecord, but this test is needed to
* account for padding. */
if (plaintext->len > spec->recordSizeLimit + innerTypeLen) {
*alert = record_overflow;
PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
return SECFailure;
}
/* The record is right-padded with 0s, followed by the true
* content type, so read from the right until we receive a
* nonzero byte. */
while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
--plaintext->len;
}
/* Bogus padding. */
if (plaintext->len < 1) {
SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd));
/* It's safe to report this specifically because it happened
* after the MAC has been verified. */
*alert = unexpected_message;
PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
return SECFailure;
}
/* Record the type. */
*innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
--plaintext->len;
/* Check for zero-length encrypted Alert and Handshake fragments
* (zero-length + inner content type byte).
*
* Implementations MUST NOT send Handshake and Alert records that have a
* zero-length TLSInnerPlaintext.content; if such a message is received,
* the receiving implementation MUST terminate the connection with an
* "unexpected_message" alert [RFC8446, Section 5.4]. */
if (!plaintext->len && ((!IS_DTLS(ss) && cText->hdr[0] == ssl_ct_application_data) ||
(IS_DTLS(ss) && dtls_IsDtls13Ciphertext(spec->version, cText->hdr[0])))) {
switch (*innerType) {
case ssl_ct_alert:
*alert = unexpected_message;
PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
return SECFailure;
case ssl_ct_handshake:
*alert = unexpected_message;
PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
return SECFailure;
default:
break;
}
}
/* Check that we haven't received too much 0-RTT data. */
if (spec->epoch == TrafficKeyEarlyApplicationData &&
*innerType == ssl_ct_application_data) {
if (plaintext->len > spec->earlyDataRemaining) {
*alert = unexpected_message;
PORT_SetError(SSL_ERROR_TOO_MUCH_EARLY_DATA);
return SECFailure;
}
spec->earlyDataRemaining -= plaintext->len;
}
SSL_TRC(10,
("%d: TLS13[%d]: %s received record of length=%d, type=%d",
SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType));
return SECSuccess;
}
/* 0-RTT is only permitted if:
*
* 1. We are doing TLS 1.3
* 2. This isn't a second ClientHello (in response to HelloRetryRequest)
* 3. The 0-RTT option is set.
* 4. We have a valid ticket or an External PSK.
* 5. If resuming:
* 5a. The server is willing to accept 0-RTT.
* 5b. We have not changed our ALPN settings to disallow the ALPN tag
* in the ticket.
*
* Called from tls13_ClientSendEarlyDataXtn().
*/
PRBool
tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
{
/* We checked that the cipher suite was still allowed back in
* ssl3_SendClientHello. */
if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
return PR_FALSE;
}
if (ss->ssl3.hs.helloRetry) {
return PR_FALSE;
}
if (!ss->opt.enable0RttData) {
return PR_FALSE;
}
if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
return PR_FALSE;
}
sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
return PR_FALSE;
}
if (!psk->maxEarlyData) {
return PR_FALSE;
}
if (psk->type == ssl_psk_external) {
return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
}
if (psk->type == ssl_psk_resume) {
if (!ss->statelessResume)
return PR_FALSE;
if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
return PR_FALSE;
return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
}
PORT_Assert(0);
return PR_FALSE;
}
SECStatus
tls13_MaybeDo0RTTHandshake(sslSocket *ss)
{
SECStatus rv;
/* Don't do anything if there is no early_data xtn, which means we're
* not doing early data. */
if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
return SECSuccess;
}
ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
/* Note: Reset the preliminary info here rather than just add 0-RTT. We are
* only guessing what might happen at this point.*/
ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite;
SSL_TRC(3, ("%d: TLS13[%d]: in 0-RTT mode", SSL_GETPID(), ss->fd));
/* Set the ALPN data as if it was negotiated. We check in the ServerHello
* handler that the server negotiates the same value. */
if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
rv = SECITEM_CopyItem(NULL, &ss->xtnData.nextProto,
&ss->sec.ci.sid->u.ssl3.alpnSelection);
if (rv != SECSuccess) {
return SECFailure;
}
}
if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
/* Pretend that this is a proper ChangeCipherSpec even though it is sent
* before receiving the ServerHello. */
ssl_GetSpecWriteLock(ss);
tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
ssl_ReleaseSpecWriteLock(ss);
ssl_GetXmitBufLock(ss);
rv = ssl3_SendChangeCipherSpecsInt(ss);
ssl_ReleaseXmitBufLock(ss);
if (rv != SECSuccess) {
return SECFailure;
}
}
/* If we have any message that was saved for later hashing.
* The updated hash is then used in tls13_DeriveEarlySecrets. */
rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
if (rv != SECSuccess) {
return SECFailure;
}
/* If we're trying 0-RTT, derive from the first PSK */
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk);
ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
rv = tls13_DeriveEarlySecrets(ss);
if (rv != SECSuccess) {
return SECFailure;
}
/* Save cwSpec in case we get a HelloRetryRequest and have to send another
* ClientHello. */
ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
ssl_secret_write, PR_TRUE);
ss->xtnData.selectedPsk = NULL;
if (rv != SECSuccess) {
return SECFailure;
}
return SECSuccess;
}
PRInt32
tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
{
PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData));
PRInt32 offset = 0;
while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
TLS13EarlyData *msg =
(TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData);
unsigned int tocpy = msg->data.len - msg->consumed;
if (tocpy > (len - offset)) {
if (IS_DTLS(ss)) {
/* In DTLS, we only return entire records.
* So offset and consumed are always zero. */
PORT_Assert(offset == 0);
PORT_Assert(msg->consumed == 0);
PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
return -1;
}
tocpy = len - offset;
}
PORT_Memcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
offset += tocpy;
msg->consumed += tocpy;
if (msg->consumed == msg->data.len) {
PR_REMOVE_LINK(&msg->link);
SECITEM_ZfreeItem(&msg->data, PR_FALSE);
PORT_ZFree(msg, sizeof(*msg));
}
/* We are done after one record for DTLS; otherwise, when the buffer fills up. */
if (IS_DTLS(ss) || offset == len) {
break;
}
}
return offset;
}
static SECStatus
tls13_SendEndOfEarlyData(sslSocket *ss)
{
SECStatus rv;
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
if (!ss->opt.suppressEndOfEarlyData) {
SSL_TRC(3, ("%d: TLS13[%d]: send EndOfEarlyData", SSL_GETPID(), ss->fd));
rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
if (rv != SECSuccess) {
return rv; /* err set by AppendHandshake. */
}
}
ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
return SECSuccess;
}
static SECStatus
tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
{
SECStatus rv;
PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA,
wait_end_of_early_data);
if (rv != SECSuccess) {
return SECFailure;
}
/* We shouldn't be getting any more early data, and if we do,
* it is because of reordering and we drop it. */
if (IS_DTLS(ss)) {
ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
TrafficKeyEarlyApplicationData);
dtls_ReceivedFirstMessageInFlight(ss);
}
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
if (length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, decode_error);
return SECFailure;
}
rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
ssl_secret_read, PR_FALSE);
if (rv != SECSuccess) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
if (tls13_ShouldRequestClientAuth(ss)) {
TLS13_SET_HS_STATE(ss, wait_client_cert);
} else {
TLS13_SET_HS_STATE(ss, wait_finished);
}
return SECSuccess;
}
static SECStatus
tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
{
PORT_Assert(ss->sec.isServer);
if (!ss->opt.suppressEndOfEarlyData ||
ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
return SECSuccess;
}
return tls13_HandleEndOfEarlyData(ss, NULL, 0);
}
SECStatus
tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
{
TLS13EarlyData *ed;
SECItem it = { siBuffer, NULL, 0 };
PORT_Assert(ss->sec.isServer);
PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
/* Belt and suspenders. */
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
return SECFailure;
}
PRINT_BUF(3, (NULL, "Received early application data",
origBuf->buf, origBuf->len));
ed = PORT_ZNew(TLS13EarlyData);
if (!ed) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
it.data = origBuf->buf;
it.len = origBuf->len;
if (SECITEM_CopyItem(NULL, &ed->data, &it) != SECSuccess) {
FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
return SECFailure;
}
PR_APPEND_LINK(&ed->link, &ss->ssl3.hs.bufferedEarlyData);
origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
return SECSuccess;
}
PRUint16
tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
{
if (variant == ssl_variant_datagram) {
return dtls_TLSVersionToDTLSVersion(version);
}
/* Stream-variant encodings do not change. */
return (PRUint16)version;
}
SECStatus
tls13_ClientReadSupportedVersion(sslSocket *ss)
{
PRUint32 temp;
TLSExtension *versionExtension;
SECItem it;
SECStatus rv;
/* Update the version based on the extension, as necessary. */
versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
if (!versionExtension) {
return SECSuccess;
}
/* Struct copy so we don't damage the extension. */
it = versionExtension->data;
rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
if (rv != SECSuccess) {
return SECFailure;
}
if (it.len) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
return SECFailure;
}
if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
ss->protocolVariant)) {
/* You cannot negotiate < TLS 1.3 with supported_versions. */
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
return SECFailure;
}
/* Any endpoint receiving a Hello message with...ServerHello.legacy_version
* set to 0x0300 (SSL3) MUST abort the handshake with a "protocol_version"
* alert. [RFC8446, Section D.5]
*
* The ServerHello.legacy_version is read into the ss->version field by
* ssl_ClientReadVersion(). */
if (ss->version == SSL_LIBRARY_VERSION_3_0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, protocol_version);
return SECFailure;
}
ss->version = SSL_LIBRARY_VERSION_TLS_1_3;
return SECSuccess;
}
/* Pick the highest version we support that is also advertised. */
SECStatus
tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
{
PRUint16 version;
/* Make a copy so we're nondestructive. */
SECItem data = supportedVersions->data;
SECItem versions;
SECStatus rv;
rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
&data.data, &data.len);
if (rv != SECSuccess) {
return SECFailure;
}
if (data.len || !versions.len || (versions.len & 1)) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
return SECFailure;
}
for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
if (version < SSL_LIBRARY_VERSION_TLS_1_3 &&
(ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
/* Prevent negotiating to a lower version after 1.3 HRR or ECH
* When accepting ECH, a different alert is generated.
*/
SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, alert);
return SECFailure;
}
PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
unsigned long offset;
for (offset = 0; offset < versions.len; offset += 2) {
PRUint16 supported =
(versions.data[offset] << 8) | versions.data[offset + 1];
if (supported == wire) {
ss->version = version;
return SECSuccess;
}
}
}
FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
return SECFailure;
}
/* This is TLS 1.3 or might negotiate to it. */
PRBool
tls13_MaybeTls13(sslSocket *ss)
{
if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
return PR_TRUE;
}
if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
return PR_FALSE;
}
if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version)) {
return PR_TRUE;
}
return PR_FALSE;
}
/* Setup random client GREASE values according to RFC8701. State must be kept
* so an equal ClientHello might be send on HelloRetryRequest. */
SECStatus
tls13_ClientGreaseSetup(sslSocket *ss)
{
if (!ss->opt.enableGrease) {
return SECSuccess;
}
PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
if (ss->ssl3.hs.grease) {
return SECFailure;
}
ss->ssl3.hs.grease = PORT_Alloc(sizeof(tls13ClientGrease));
if (!ss->ssl3.hs.grease) {
return SECFailure;
}
tls13ClientGrease *grease = ss->ssl3.hs.grease;
/* We require eight GREASE values and randoms. */
PRUint8 random[8];
/* Generate random GREASE values. */
if (PK11_GenerateRandom(random, sizeof(random)) != SECSuccess) {
return SECFailure;
}
for (size_t i = 0; i < PR_ARRAY_SIZE(grease->idx); i++) {
random[i] = ((random[i] & 0xf0) | 0x0a);
grease->idx[i] = ((random[i] << 8) | random[i]);
}
/* Specific PskKeyExchangeMode GREASE value. */
grease->pskKem = 0x0b + ((random[8 - 1] >> 5) * 0x1f);
/* Duplicate extensions are not allowed. */
if (grease->idx[grease_extension1] == grease->idx[grease_extension2]) {
grease->idx[grease_extension2] ^= 0x1010;
}
return SECSuccess;
}
/* Destroy client GREASE state. */
void
tls13_ClientGreaseDestroy(sslSocket *ss)
{
if (ss->ssl3.hs.grease) {
PORT_Free(ss->ssl3.hs.grease);
ss->ssl3.hs.grease = NULL;
}
}
/* Generate a random GREASE value according to RFC8701.
* This function does not provide valid PskKeyExchangeMode GREASE values! */
SECStatus
tls13_RandomGreaseValue(PRUint16 *out)
{
PRUint8 random;
if (PK11_GenerateRandom(&random, sizeof(random)) != SECSuccess) {
return SECFailure;
}
random = ((random & 0xf0) | 0x0a);
*out = ((random << 8) | random);
return SECSuccess;
}
/* Set TLS 1.3 GREASE Extension random GREASE type. */
SECStatus
tls13_MaybeGreaseExtensionType(const sslSocket *ss,
const SSLHandshakeType message,
PRUint16 *exType)
{
if (*exType != ssl_tls13_grease_xtn) {
return SECSuccess;
}
PR_ASSERT(ss->opt.enableGrease);
PR_ASSERT(message == ssl_hs_client_hello ||
message == ssl_hs_certificate_request);
/* GREASE ClientHello:
* A client MAY select one or more GREASE extension values and
* advertise them as extensions with varying length and contents
* [RFC8701, Section 3.1]. */
if (message == ssl_hs_client_hello) {
PR_ASSERT(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
/* Check if the first GREASE extension was already added. */
if (!ssl3_ExtensionAdvertised(ss, ss->ssl3.hs.grease->idx[grease_extension1])) {
*exType = ss->ssl3.hs.grease->idx[grease_extension1];
} else {
*exType = ss->ssl3.hs.grease->idx[grease_extension2];
}
}
/* GREASE CertificateRequest:
* When sending a CertificateRequest in TLS 1.3, a server MAY behave as
* follows: A server MAY select one or more GREASE extension values and
* advertise them as extensions with varying length and contents
* [RFC8701, Section 4.1]. */
else if (message == ssl_hs_certificate_request) {
PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
/* Get random grease extension type. */
SECStatus rv = tls13_RandomGreaseValue(exType);
if (rv != SECSuccess) {
return SECFailure;
}
}
return SECSuccess;
}
|