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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/ssl_client_socket.h"
#include <errno.h>
#include <string.h>
#include <algorithm>
#include <array>
#include <memory>
#include <optional>
#include <ranges>
#include <string_view>
#include <tuple>
#include <utility>
#include "base/containers/span.h"
#include "base/containers/span_reader.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_view_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/rsa_private_key.h"
#include "net/base/address_list.h"
#include "net/base/completion_once_callback.h"
#include "net/base/features.h"
#include "net/base/host_port_pair.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/schemeful_site.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_database.h"
#include "net/cert/ct_policy_status.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/mock_client_cert_verifier.h"
#include "net/cert/sct_auditing_delegate.h"
#include "net/cert/signed_certificate_timestamp_and_status.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_util.h"
#include "net/dns/host_resolver.h"
#include "net/http/transport_security_state.h"
#include "net/http/transport_security_state_test_util.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_util.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/read_buffering_stream_socket.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket_impl.h"
#include "net/socket/ssl_server_socket.h"
#include "net/socket/stream_socket.h"
#include "net/socket/tcp_client_socket.h"
#include "net/socket/tcp_server_socket.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_client_session_cache.h"
#include "net/ssl/ssl_config.h"
#include "net/ssl/ssl_config_service.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_handshake_details.h"
#include "net/ssl/ssl_info.h"
#include "net/ssl/ssl_server_config.h"
#include "net/ssl/test_ssl_config_service.h"
#include "net/ssl/test_ssl_private_key.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/gtest_util.h"
#include "net/test/key_util.h"
#include "net/test/ssl_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_task_environment.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#include "third_party/boringssl/src/include/openssl/bio.h"
#include "third_party/boringssl/src/include/openssl/evp.h"
#include "third_party/boringssl/src/include/openssl/hpke.h"
#include "third_party/boringssl/src/include/openssl/pem.h"
#include "third_party/boringssl/src/include/openssl/ssl.h"
#include "url/gurl.h"
using net::test::IsError;
using net::test::IsOk;
using testing::_;
using testing::Bool;
using testing::Combine;
using testing::Return;
using testing::Values;
using testing::ValuesIn;
namespace net {
class NetLogWithSource;
namespace {
// When passed to |MakeHashValueVector|, this will generate a key pin that is
// sha256/AA...=, and hence will cause pin validation success with the TestSPKI
// pin from transport_security_state_static.pins. ("A" is the 0th element of the
// base-64 alphabet.)
const uint8_t kGoodHashValueVectorInput = 0;
// When passed to |MakeHashValueVector|, this will generate a key pin that is
// not sha256/AA...=, and hence will cause pin validation failure with the
// TestSPKI pin.
const uint8_t kBadHashValueVectorInput = 3;
// TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
constexpr uint16_t kModernTLS12Cipher = 0xc02f;
// TLS_RSA_WITH_AES_128_GCM_SHA256
constexpr uint16_t kRSACipher = 0x009c;
// TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
constexpr uint16_t kCBCCipher = 0xc013;
// TLS_RSA_WITH_3DES_EDE_CBC_SHA
constexpr uint16_t k3DESCipher = 0x000a;
// Simulates synchronously receiving an error during Read() or Write()
class SynchronousErrorStreamSocket : public WrappedStreamSocket {
public:
explicit SynchronousErrorStreamSocket(std::unique_ptr<StreamSocket> transport)
: WrappedStreamSocket(std::move(transport)) {}
SynchronousErrorStreamSocket(const SynchronousErrorStreamSocket&) = delete;
SynchronousErrorStreamSocket& operator=(const SynchronousErrorStreamSocket&) =
delete;
~SynchronousErrorStreamSocket() override = default;
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override;
int ReadIfReady(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override;
int Write(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) override;
// Sets the next Read() call and all future calls to return |error|.
// If there is already a pending asynchronous read, the configured error
// will not be returned until that asynchronous read has completed and Read()
// is called again.
void SetNextReadError(int error) {
DCHECK_GE(0, error);
have_read_error_ = true;
pending_read_error_ = error;
}
// Sets the next Write() call and all future calls to return |error|.
// If there is already a pending asynchronous write, the configured error
// will not be returned until that asynchronous write has completed and
// Write() is called again.
void SetNextWriteError(int error) {
DCHECK_GE(0, error);
have_write_error_ = true;
pending_write_error_ = error;
}
private:
bool have_read_error_ = false;
int pending_read_error_ = OK;
bool have_write_error_ = false;
int pending_write_error_ = OK;
};
int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) {
if (have_read_error_)
return pending_read_error_;
return transport_->Read(buf, buf_len, std::move(callback));
}
int SynchronousErrorStreamSocket::ReadIfReady(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) {
if (have_read_error_)
return pending_read_error_;
return transport_->ReadIfReady(buf, buf_len, std::move(callback));
}
int SynchronousErrorStreamSocket::Write(
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) {
if (have_write_error_)
return pending_write_error_;
return transport_->Write(buf, buf_len, std::move(callback),
traffic_annotation);
}
// FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
// underlying transport needing to complete things asynchronously in a
// deterministic manner (e.g.: independent of the TestServer and the OS's
// semantics).
class FakeBlockingStreamSocket : public WrappedStreamSocket {
public:
explicit FakeBlockingStreamSocket(std::unique_ptr<StreamSocket> transport)
: WrappedStreamSocket(std::move(transport)) {}
~FakeBlockingStreamSocket() override = default;
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override;
int ReadIfReady(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override;
int CancelReadIfReady() override;
int Write(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) override;
int pending_read_result() const { return pending_read_result_; }
IOBuffer* pending_read_buf() const { return pending_read_buf_.get(); }
// Blocks read results on the socket. Reads will not complete until
// UnblockReadResult() has been called and a result is ready from the
// underlying transport. Note: if BlockReadResult() is called while there is a
// hanging asynchronous Read(), that Read is blocked.
void BlockReadResult();
void UnblockReadResult();
// Replaces the pending read with |data|. Returns true on success or false if
// the caller's reads were too small.
bool ReplaceReadResult(const std::string& data);
// Waits for the blocked Read() call to be complete at the underlying
// transport.
void WaitForReadResult();
// Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
// underlying transport until UnblockWrite() has been called. Note: if there
// is a pending asynchronous write, it is NOT blocked. For purposes of
// blocking writes, data is considered to have reached the underlying
// transport as soon as Write() is called.
void BlockWrite();
void UnblockWrite();
// Waits for the blocked Write() call to be scheduled.
void WaitForWrite();
private:
// Handles completion from the underlying transport read.
void OnReadCompleted(int result);
// Handles async completion of ReadIfReady().
void CompleteReadIfReady(scoped_refptr<IOBuffer> buffer, int rv);
// Finishes the current read.
void ReturnReadResult();
// Callback for writes.
void CallPendingWriteCallback(int result);
// True if read callbacks are blocked.
bool should_block_read_ = false;
// Used to buffer result returned by a completed ReadIfReady().
std::string read_if_ready_buf_;
// Non-null if there is a pending ReadIfReady().
CompletionOnceCallback read_if_ready_callback_;
// The buffer for the pending read, or NULL if not consumed.
scoped_refptr<IOBuffer> pending_read_buf_;
// The size of the pending read buffer, or -1 if not set.
int pending_read_buf_len_ = -1;
// The user callback for the pending read call.
CompletionOnceCallback pending_read_callback_;
// The result for the blocked read callback, or ERR_IO_PENDING if not
// completed.
int pending_read_result_ = ERR_IO_PENDING;
// WaitForReadResult() wait loop.
std::unique_ptr<base::RunLoop> read_loop_;
// True if write calls are blocked.
bool should_block_write_ = false;
// The buffer for the pending write, or NULL if not scheduled.
scoped_refptr<IOBuffer> pending_write_buf_;
// The callback for the pending write call.
CompletionOnceCallback pending_write_callback_;
// The length for the pending write, or -1 if not scheduled.
int pending_write_len_ = -1;
// WaitForWrite() wait loop.
std::unique_ptr<base::RunLoop> write_loop_;
};
int FakeBlockingStreamSocket::Read(IOBuffer* buf,
int len,
CompletionOnceCallback callback) {
DCHECK(!pending_read_buf_);
DCHECK(pending_read_callback_.is_null());
DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
DCHECK(!callback.is_null());
int rv = transport_->Read(
buf, len,
base::BindOnce(&FakeBlockingStreamSocket::OnReadCompleted,
base::Unretained(this)));
if (rv == ERR_IO_PENDING || should_block_read_) {
// Save the callback to be called later.
pending_read_buf_ = buf;
pending_read_buf_len_ = len;
pending_read_callback_ = std::move(callback);
// Save the read result.
if (rv != ERR_IO_PENDING) {
OnReadCompleted(rv);
rv = ERR_IO_PENDING;
}
}
return rv;
}
int FakeBlockingStreamSocket::ReadIfReady(IOBuffer* buf,
int len,
CompletionOnceCallback callback) {
if (!read_if_ready_buf_.empty()) {
// If ReadIfReady() is used, asynchronous reads with a large enough buffer
// and no BlockReadResult() are supported by this class. Explicitly check
// that |should_block_read_| doesn't apply and |len| is greater than the
// size of the buffered data.
CHECK(!should_block_read_);
CHECK_GE(len, static_cast<int>(read_if_ready_buf_.size()));
int rv = read_if_ready_buf_.size();
buf->span().copy_prefix_from(base::as_byte_span(read_if_ready_buf_));
read_if_ready_buf_.clear();
return rv;
}
auto buf_copy = base::MakeRefCounted<IOBufferWithSize>(len);
int rv = Read(buf_copy.get(), len,
base::BindOnce(&FakeBlockingStreamSocket::CompleteReadIfReady,
base::Unretained(this), buf_copy));
if (rv > 0)
buf->span().copy_prefix_from(buf_copy->first(rv));
if (rv == ERR_IO_PENDING)
read_if_ready_callback_ = std::move(callback);
return rv;
}
int FakeBlockingStreamSocket::CancelReadIfReady() {
DCHECK(!read_if_ready_callback_.is_null());
read_if_ready_callback_.Reset();
return OK;
}
int FakeBlockingStreamSocket::Write(
IOBuffer* buf,
int len,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK(buf);
DCHECK_LE(0, len);
if (!should_block_write_)
return transport_->Write(buf, len, std::move(callback), traffic_annotation);
// Schedule the write, but do nothing.
DCHECK(!pending_write_buf_.get());
DCHECK_EQ(-1, pending_write_len_);
DCHECK(pending_write_callback_.is_null());
DCHECK(!callback.is_null());
pending_write_buf_ = buf;
pending_write_len_ = len;
pending_write_callback_ = std::move(callback);
// Stop the write loop, if any.
if (write_loop_)
write_loop_->Quit();
return ERR_IO_PENDING;
}
void FakeBlockingStreamSocket::BlockReadResult() {
DCHECK(!should_block_read_);
should_block_read_ = true;
}
void FakeBlockingStreamSocket::UnblockReadResult() {
DCHECK(should_block_read_);
should_block_read_ = false;
// If the operation has since completed, return the result to the caller.
if (pending_read_result_ != ERR_IO_PENDING)
ReturnReadResult();
}
bool FakeBlockingStreamSocket::ReplaceReadResult(const std::string& data) {
DCHECK(should_block_read_);
DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
DCHECK(pending_read_buf_);
DCHECK_NE(-1, pending_read_buf_len_);
if (static_cast<size_t>(pending_read_buf_len_) < data.size())
return false;
pending_read_buf_->span().copy_prefix_from(base::as_byte_span(data));
pending_read_result_ = data.size();
return true;
}
void FakeBlockingStreamSocket::WaitForReadResult() {
DCHECK(should_block_read_);
DCHECK(!read_loop_);
if (pending_read_result_ != ERR_IO_PENDING)
return;
read_loop_ = std::make_unique<base::RunLoop>();
read_loop_->Run();
read_loop_.reset();
DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
}
void FakeBlockingStreamSocket::BlockWrite() {
DCHECK(!should_block_write_);
should_block_write_ = true;
}
void FakeBlockingStreamSocket::CallPendingWriteCallback(int rv) {
std::move(pending_write_callback_).Run(rv);
}
void FakeBlockingStreamSocket::UnblockWrite() {
DCHECK(should_block_write_);
should_block_write_ = false;
// Do nothing if UnblockWrite() was called after BlockWrite(),
// without a Write() in between.
if (!pending_write_buf_.get())
return;
int rv = transport_->Write(
pending_write_buf_.get(), pending_write_len_,
base::BindOnce(&FakeBlockingStreamSocket::CallPendingWriteCallback,
base::Unretained(this)),
TRAFFIC_ANNOTATION_FOR_TESTS);
pending_write_buf_ = nullptr;
pending_write_len_ = -1;
if (rv != ERR_IO_PENDING) {
std::move(pending_write_callback_).Run(rv);
}
}
void FakeBlockingStreamSocket::WaitForWrite() {
DCHECK(should_block_write_);
DCHECK(!write_loop_);
if (pending_write_buf_.get())
return;
write_loop_ = std::make_unique<base::RunLoop>();
write_loop_->Run();
write_loop_.reset();
DCHECK(pending_write_buf_.get());
}
void FakeBlockingStreamSocket::OnReadCompleted(int result) {
DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
DCHECK(!pending_read_callback_.is_null());
pending_read_result_ = result;
if (should_block_read_) {
// Defer the result until UnblockReadResult is called.
if (read_loop_)
read_loop_->Quit();
return;
}
ReturnReadResult();
}
void FakeBlockingStreamSocket::CompleteReadIfReady(scoped_refptr<IOBuffer> buf,
int rv) {
DCHECK(read_if_ready_buf_.empty());
DCHECK(!should_block_read_);
if (rv > 0)
read_if_ready_buf_ = base::as_string_view(buf->first(rv));
// The callback may be null if CancelReadIfReady() was called.
if (!read_if_ready_callback_.is_null())
std::move(read_if_ready_callback_).Run(rv > 0 ? OK : rv);
}
void FakeBlockingStreamSocket::ReturnReadResult() {
int result = pending_read_result_;
pending_read_result_ = ERR_IO_PENDING;
pending_read_buf_ = nullptr;
pending_read_buf_len_ = -1;
std::move(pending_read_callback_).Run(result);
}
// CountingStreamSocket wraps an existing StreamSocket and maintains a count of
// reads and writes on the socket.
class CountingStreamSocket : public WrappedStreamSocket {
public:
explicit CountingStreamSocket(std::unique_ptr<StreamSocket> transport)
: WrappedStreamSocket(std::move(transport)) {}
~CountingStreamSocket() override = default;
// Socket implementation:
int Read(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override {
read_count_++;
return transport_->Read(buf, buf_len, std::move(callback));
}
int Write(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) override {
write_count_++;
return transport_->Write(buf, buf_len, std::move(callback),
traffic_annotation);
}
int read_count() const { return read_count_; }
int write_count() const { return write_count_; }
private:
int read_count_ = 0;
int write_count_ = 0;
};
// A helper class that will delete |socket| when the callback is invoked.
class DeleteSocketCallback : public TestCompletionCallbackBase {
public:
explicit DeleteSocketCallback(StreamSocket* socket) : socket_(socket) {}
DeleteSocketCallback(const DeleteSocketCallback&) = delete;
DeleteSocketCallback& operator=(const DeleteSocketCallback&) = delete;
~DeleteSocketCallback() override = default;
CompletionOnceCallback callback() {
return base::BindOnce(&DeleteSocketCallback::OnComplete,
base::Unretained(this));
}
private:
void OnComplete(int result) {
if (socket_) {
delete socket_;
socket_ = nullptr;
} else {
ADD_FAILURE() << "Deleting socket twice";
}
SetResult(result);
}
raw_ptr<StreamSocket, DanglingUntriaged> socket_;
};
class MockSCTAuditingDelegate : public SCTAuditingDelegate {
public:
MOCK_METHOD(bool, IsSCTAuditingEnabled, ());
MOCK_METHOD(void,
MaybeEnqueueReport,
(const net::HostPortPair&,
const net::X509Certificate*,
const net::SignedCertificateTimestampAndStatusList&));
};
class ManySmallRecordsHttpResponse : public test_server::HttpResponse {
public:
static std::unique_ptr<test_server::HttpResponse> HandleRequest(
const test_server::HttpRequest& request) {
if (request.relative_url != "/ssl-many-small-records") {
return nullptr;
}
// Write ~26K of data, in 1350 byte chunks
return std::make_unique<ManySmallRecordsHttpResponse>(/*chunk_size=*/1350,
/*chunk_count=*/20);
}
ManySmallRecordsHttpResponse(size_t chunk_size, size_t chunk_count)
: chunk_size_(chunk_size), chunk_count_(chunk_count) {}
void SendResponse(
base::WeakPtr<test_server::HttpResponseDelegate> delegate) override {
base::StringPairs headers = {
{"Connection", "close"},
{"Content-Length", base::NumberToString(chunk_size_ * chunk_count_)},
{"Content-Type", "text/plain"}};
delegate->SendResponseHeaders(HTTP_OK, "OK", headers);
SendChunks(chunk_size_, chunk_count_, delegate);
}
private:
static void SendChunks(
size_t chunk_size,
size_t chunk_count,
base::WeakPtr<test_server::HttpResponseDelegate> delegate) {
if (!delegate)
return;
if (chunk_count == 0) {
delegate->FinishResponse();
return;
}
std::string chunk(chunk_size, '*');
// This assumes that splitting output into separate |send| calls will
// produce separate TLS records.
delegate->SendContents(chunk, base::BindOnce(&SendChunks, chunk_size,
chunk_count - 1, delegate));
}
size_t chunk_size_;
size_t chunk_count_;
};
class SSLClientSocketTest : public PlatformTest, public WithTaskEnvironment {
public:
SSLClientSocketTest()
: socket_factory_(ClientSocketFactory::GetDefaultFactory()),
ssl_config_service_(
std::make_unique<TestSSLConfigService>(SSLContextConfig())),
cert_verifier_(std::make_unique<ParamRecordingMockCertVerifier>()),
transport_security_state_(std::make_unique<TransportSecurityState>()),
ssl_client_session_cache_(std::make_unique<SSLClientSessionCache>(
SSLClientSessionCache::Config())),
context_(
std::make_unique<SSLClientContext>(ssl_config_service_.get(),
cert_verifier_.get(),
transport_security_state_.get(),
ssl_client_session_cache_.get(),
nullptr)) {
cert_verifier_->set_default_result(OK);
cert_verifier_->set_async(true);
}
protected:
// The address of the test server, after calling StartEmbeddedTestServer().
const AddressList& addr() const { return addr_; }
// The hostname of the test server, after calling StartEmbeddedTestServer().
const HostPortPair& host_port_pair() const { return host_port_pair_; }
// The EmbeddedTestServer object, after calling StartEmbeddedTestServer().
EmbeddedTestServer* embedded_test_server() {
return embedded_test_server_.get();
}
// Starts the embedded test server with the specified parameters. Returns true
// on success.
bool StartEmbeddedTestServer(EmbeddedTestServer::ServerCertificate cert,
const SSLServerConfig& server_config) {
embedded_test_server_ =
std::make_unique<EmbeddedTestServer>(EmbeddedTestServer::TYPE_HTTPS);
embedded_test_server_->SetSSLConfig(cert, server_config);
return FinishStartingEmbeddedTestServer();
}
// Starts the embedded test server with the specified parameters. Returns true
// on success.
bool StartEmbeddedTestServer(
const EmbeddedTestServer::ServerCertificateConfig& cert_config,
const SSLServerConfig& server_config) {
embedded_test_server_ =
std::make_unique<EmbeddedTestServer>(EmbeddedTestServer::TYPE_HTTPS);
embedded_test_server_->SetSSLConfig(cert_config, server_config);
return FinishStartingEmbeddedTestServer();
}
bool FinishStartingEmbeddedTestServer() {
RegisterEmbeddedTestServerHandlers(embedded_test_server_.get());
if (!embedded_test_server_->Start()) {
LOG(ERROR) << "Could not start EmbeddedTestServer";
return false;
}
if (!embedded_test_server_->GetAddressList(&addr_)) {
LOG(ERROR) << "Could not get EmbeddedTestServer address list";
return false;
}
host_port_pair_ = embedded_test_server_->host_port_pair();
return true;
}
// May be overridden by the subclass to customize the EmbeddedTestServer.
virtual void RegisterEmbeddedTestServerHandlers(EmbeddedTestServer* server) {
server->AddDefaultHandlers(base::FilePath());
server->RegisterRequestHandler(
base::BindRepeating(&ManySmallRecordsHttpResponse::HandleRequest));
server->RegisterRequestHandler(
base::BindRepeating(&HandleSSLInfoRequest, base::Unretained(this)));
}
std::unique_ptr<SSLClientSocket> CreateSSLClientSocket(
std::unique_ptr<StreamSocket> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config) {
return socket_factory_->CreateSSLClientSocket(
context_.get(), std::move(transport_socket), host_and_port, ssl_config);
}
// Create an SSLClientSocket object and use it to connect to a test server,
// then wait for connection results. This must be called after a successful
// StartEmbeddedTestServer() call.
//
// |ssl_config| The SSL configuration to use.
// |host_port_pair| The hostname and port to use at the SSL layer. (The
// socket connection will still be made to |embedded_test_server_|.)
// |result| will retrieve the ::Connect() result value.
//
// Returns true on success, false otherwise. Success means that the SSL
// socket could be created and its Connect() was called, not that the
// connection itself was a success.
bool CreateAndConnectSSLClientSocketWithHost(
const SSLConfig& ssl_config,
const HostPortPair& host_port_pair,
int* result) {
auto transport = std::make_unique<TCPClientSocket>(
addr_, nullptr, nullptr, NetLog::Get(), NetLogSource());
int rv = callback_.GetResult(transport->Connect(callback_.callback()));
if (rv != OK) {
LOG(ERROR) << "Could not connect to test server";
return false;
}
sock_ =
CreateSSLClientSocket(std::move(transport), host_port_pair, ssl_config);
EXPECT_FALSE(sock_->IsConnected());
*result = callback_.GetResult(sock_->Connect(callback_.callback()));
return true;
}
bool CreateAndConnectSSLClientSocket(const SSLConfig& ssl_config,
int* result) {
return CreateAndConnectSSLClientSocketWithHost(ssl_config, host_port_pair(),
result);
}
std::optional<SSLInfo> LastSSLInfoFromServer() {
// EmbeddedTestServer callbacks run on another thread, so protect this
// with a lock.
base::AutoLock lock(server_ssl_info_lock_);
return std::exchange(server_ssl_info_, std::nullopt);
}
RecordingNetLogObserver log_observer_;
raw_ptr<ClientSocketFactory, DanglingUntriaged> socket_factory_;
std::unique_ptr<TestSSLConfigService> ssl_config_service_;
std::unique_ptr<ParamRecordingMockCertVerifier> cert_verifier_;
std::unique_ptr<TransportSecurityState> transport_security_state_;
std::unique_ptr<SSLClientSessionCache> ssl_client_session_cache_;
std::unique_ptr<SSLClientContext> context_;
std::unique_ptr<SSLClientSocket> sock_;
private:
static std::unique_ptr<test_server::HttpResponse> HandleSSLInfoRequest(
SSLClientSocketTest* test,
const test_server::HttpRequest& request) {
if (request.relative_url != "/ssl-info") {
return nullptr;
}
{
// EmbeddedTestServer callbacks run on another thread, so protect this
// with a lock.
base::AutoLock lock(test->server_ssl_info_lock_);
test->server_ssl_info_ = request.ssl_info;
}
return std::make_unique<test_server::BasicHttpResponse>();
}
std::unique_ptr<EmbeddedTestServer> embedded_test_server_;
base::Lock server_ssl_info_lock_;
std::optional<SSLInfo> server_ssl_info_ GUARDED_BY(server_ssl_info_lock_);
TestCompletionCallback callback_;
AddressList addr_;
HostPortPair host_port_pair_;
};
enum ReadIfReadyTransport {
// ReadIfReady() is implemented by the underlying transport.
READ_IF_READY_SUPPORTED,
// ReadIfReady() is not implemented by the underlying transport.
READ_IF_READY_NOT_SUPPORTED,
};
enum ReadIfReadySSL {
// Test reads by calling ReadIfReady() on the SSL socket.
TEST_SSL_READ_IF_READY,
// Test reads by calling Read() on the SSL socket.
TEST_SSL_READ,
};
class StreamSocketWithoutReadIfReady : public WrappedStreamSocket {
public:
explicit StreamSocketWithoutReadIfReady(
std::unique_ptr<StreamSocket> transport)
: WrappedStreamSocket(std::move(transport)) {}
int ReadIfReady(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override {
return ERR_READ_IF_READY_NOT_IMPLEMENTED;
}
int CancelReadIfReady() override { return ERR_READ_IF_READY_NOT_IMPLEMENTED; }
};
class ClientSocketFactoryWithoutReadIfReady : public ClientSocketFactory {
public:
explicit ClientSocketFactoryWithoutReadIfReady(ClientSocketFactory* factory)
: factory_(factory) {}
std::unique_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
NetLog* net_log,
const NetLogSource& source) override {
return factory_->CreateDatagramClientSocket(bind_type, net_log, source);
}
std::unique_ptr<TransportClientSocket> CreateTransportClientSocket(
const AddressList& addresses,
std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
NetworkQualityEstimator* network_quality_estimator,
NetLog* net_log,
const NetLogSource& source) override {
return factory_->CreateTransportClientSocket(
addresses, std::move(socket_performance_watcher),
network_quality_estimator, net_log, source);
}
std::unique_ptr<SSLClientSocket> CreateSSLClientSocket(
SSLClientContext* context,
std::unique_ptr<StreamSocket> stream_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config) override {
stream_socket = std::make_unique<StreamSocketWithoutReadIfReady>(
std::move(stream_socket));
return factory_->CreateSSLClientSocket(context, std::move(stream_socket),
host_and_port, ssl_config);
}
private:
const raw_ptr<ClientSocketFactory> factory_;
};
std::vector<uint16_t> GetTLSVersions() {
return {SSL_PROTOCOL_VERSION_TLS1_2, SSL_PROTOCOL_VERSION_TLS1_3};
}
class SSLClientSocketVersionTest
: public SSLClientSocketTest,
public ::testing::WithParamInterface<uint16_t> {
protected:
SSLClientSocketVersionTest() = default;
uint16_t version() const { return GetParam(); }
SSLServerConfig GetServerConfig() {
SSLServerConfig config;
config.version_max = version();
config.version_min = version();
return config;
}
};
// If GetParam(), try ReadIfReady() and fall back to Read() if needed.
class SSLClientSocketReadTest
: public SSLClientSocketTest,
public ::testing::WithParamInterface<
std::tuple<ReadIfReadyTransport, ReadIfReadySSL, uint16_t>> {
protected:
SSLClientSocketReadTest() : SSLClientSocketTest() {
if (!read_if_ready_supported()) {
wrapped_socket_factory_ =
std::make_unique<ClientSocketFactoryWithoutReadIfReady>(
socket_factory_);
socket_factory_ = wrapped_socket_factory_.get();
}
}
// Convienient wrapper to call Read()/ReadIfReady() depending on whether
// ReadyIfReady() is enabled.
int Read(StreamSocket* socket,
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) {
if (test_ssl_read_if_ready())
return socket->ReadIfReady(buf, buf_len, std::move(callback));
return socket->Read(buf, buf_len, std::move(callback));
}
// Wait for Read()/ReadIfReady() to complete.
int WaitForReadCompletion(StreamSocket* socket,
IOBuffer* buf,
int buf_len,
TestCompletionCallback* callback,
int rv) {
if (!test_ssl_read_if_ready())
return callback->GetResult(rv);
while (rv == ERR_IO_PENDING) {
rv = callback->GetResult(rv);
if (rv != OK)
return rv;
rv = socket->ReadIfReady(buf, buf_len, callback->callback());
}
return rv;
}
// Calls Read()/ReadIfReady() and waits for it to return data.
int ReadAndWaitForCompletion(StreamSocket* socket,
IOBuffer* buf,
int buf_len) {
TestCompletionCallback callback;
int rv = Read(socket, buf, buf_len, callback.callback());
return WaitForReadCompletion(socket, buf, buf_len, &callback, rv);
}
SSLServerConfig GetServerConfig() {
SSLServerConfig config;
config.version_max = version();
config.version_min = version();
return config;
}
bool test_ssl_read_if_ready() const {
return std::get<1>(GetParam()) == TEST_SSL_READ_IF_READY;
}
bool read_if_ready_supported() const {
return std::get<0>(GetParam()) == READ_IF_READY_SUPPORTED;
}
uint16_t version() const { return std::get<2>(GetParam()); }
private:
std::unique_ptr<ClientSocketFactory> wrapped_socket_factory_;
};
INSTANTIATE_TEST_SUITE_P(All,
SSLClientSocketReadTest,
Combine(Values(READ_IF_READY_SUPPORTED,
READ_IF_READY_NOT_SUPPORTED),
Values(TEST_SSL_READ_IF_READY, TEST_SSL_READ),
ValuesIn(GetTLSVersions())));
// Verifies the correctness of GetSSLCertRequestInfo.
class SSLClientSocketCertRequestInfoTest : public SSLClientSocketVersionTest {
protected:
// Connects to the test server and returns the SSLCertRequestInfo reported by
// the socket.
scoped_refptr<SSLCertRequestInfo> GetCertRequest() {
int rv;
if (!CreateAndConnectSSLClientSocket(SSLConfig(), &rv)) {
return nullptr;
}
EXPECT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
auto request_info = base::MakeRefCounted<SSLCertRequestInfo>();
sock_->GetSSLCertRequestInfo(request_info.get());
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
EXPECT_EQ(host_port_pair(), request_info->host_and_port);
return request_info;
}
};
class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
protected:
// Creates an SSLClientSocket with |client_config| attached to a
// FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
// |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
// so |*out_raw_transport| is a raw pointer.
//
// The client socket will begin a connect using |callback| but stop before the
// server's finished message is received. The finished message will be blocked
// in |*out_raw_transport|. To complete the handshake and successfully read
// data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
// the client successfully false started, |callback.WaitForResult()| will
// return OK without unblocking transport reads. But Read() will still block.)
//
// Must be called after StartEmbeddedTestServer is called.
void CreateAndConnectUntilServerFinishedReceived(
const SSLConfig& client_config,
TestCompletionCallback* callback,
FakeBlockingStreamSocket** out_raw_transport,
std::unique_ptr<SSLClientSocket>* out_sock) {
CHECK(embedded_test_server());
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
int rv = callback->GetResult(transport->Connect(callback->callback()));
EXPECT_THAT(rv, IsOk());
FakeBlockingStreamSocket* raw_transport = transport.get();
std::unique_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
std::move(transport), host_port_pair(), client_config);
// Connect. Stop before the client processes the first server leg
// (ServerHello, etc.)
raw_transport->BlockReadResult();
rv = sock->Connect(callback->callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write
// ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
// server's leg to complete, since it may span multiple reads.)
EXPECT_FALSE(callback->have_result());
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// And, finally, release that and block the next server leg
// (ChangeCipherSpec, Finished).
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
*out_raw_transport = raw_transport;
*out_sock = std::move(sock);
}
void TestFalseStart(const SSLServerConfig& server_config,
const SSLConfig& client_config,
bool expect_false_start) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
FakeBlockingStreamSocket* raw_transport = nullptr;
std::unique_ptr<SSLClientSocket> sock;
ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
client_config, &callback, &raw_transport, &sock));
if (expect_false_start) {
// When False Starting, the handshake should complete before receiving the
// Change Cipher Spec and Finished messages.
//
// Note: callback.have_result() may not be true without waiting. The NSS
// state machine sometimes lives on a separate thread, so this thread may
// not yet have processed the signal that the handshake has completed.
int rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer = base::MakeRefCounted<VectorIOBuffer>(
base::as_byte_span(request_text));
// Write the request.
rv = callback.GetResult(
sock->Write(request_buffer.get(), request_text.size(),
callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(request_text.size(), rv);
// The read will hang; it's waiting for the peer to complete the
// handshake, and the handshake is still blocked.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
rv = sock->Read(buf.get(), 4096, callback.callback());
// After releasing reads, the connection proceeds.
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_LT(0, rv);
} else {
// False Start is not enabled, so the handshake will not complete because
// the server second leg is blocked.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
}
}
};
// Sends an HTTP request on the socket and reads the response. This may be used
// to ensure some data has been consumed from the server.
int MakeHTTPRequest(StreamSocket* socket, const char* path = "/") {
std::string request = base::StringPrintf("GET %s HTTP/1.0\r\n\r\n", path);
TestCompletionCallback callback;
while (!request.empty()) {
auto request_buffer =
base::MakeRefCounted<StringIOBuffer>(std::string(request));
int rv = callback.GetResult(
socket->Write(request_buffer.get(), request_buffer->size(),
callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
if (rv < 0) {
return rv;
}
request = request.substr(rv);
}
auto response_buffer = base::MakeRefCounted<IOBufferWithSize>(1024);
int rv = callback.GetResult(
socket->Read(response_buffer.get(), 1024, callback.callback()));
if (rv < 0) {
return rv;
}
return OK;
}
// Provides a response to the 0RTT request indicating whether it was received
// as early data.
class ZeroRTTResponse : public test_server::HttpResponse {
public:
explicit ZeroRTTResponse(bool zero_rtt) : zero_rtt_(zero_rtt) {}
ZeroRTTResponse(const ZeroRTTResponse&) = delete;
ZeroRTTResponse& operator=(const ZeroRTTResponse&) = delete;
~ZeroRTTResponse() override = default;
void SendResponse(
base::WeakPtr<test_server::HttpResponseDelegate> delegate) override {
std::string response;
if (zero_rtt_) {
response = "1";
} else {
response = "0";
}
// Since the EmbeddedTestServer doesn't keep the socket open by default, it
// is explicitly kept alive to allow the remaining leg of the 0RTT handshake
// to be received after the early data.
delegate->SendContents(response);
}
private:
bool zero_rtt_;
};
std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
const test_server::HttpRequest& request) {
if (request.GetURL().path() != "/zerortt" || !request.ssl_info)
return nullptr;
return std::make_unique<ZeroRTTResponse>(
request.ssl_info->early_data_received);
}
class SSLClientSocketZeroRTTTest : public SSLClientSocketTest {
protected:
SSLClientSocketZeroRTTTest() : SSLClientSocketTest() {
SSLContextConfig config;
config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
ssl_config_service_->UpdateSSLConfigAndNotify(config);
}
bool StartServer() {
SSLServerConfig server_config;
server_config.early_data_enabled = true;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
return StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config);
}
void RegisterEmbeddedTestServerHandlers(EmbeddedTestServer* server) override {
SSLClientSocketTest::RegisterEmbeddedTestServerHandlers(server);
server->RegisterRequestHandler(base::BindRepeating(&HandleZeroRTTRequest));
}
void SetServerConfig(SSLServerConfig server_config) {
embedded_test_server()->ResetSSLConfig(net::EmbeddedTestServer::CERT_OK,
server_config);
}
// Makes a new connection to the test server and returns a
// FakeBlockingStreamSocket which may be used to block transport I/O.
//
// Most tests should call BlockReadResult() before calling Connect(). This
// avoid race conditions by controlling the order of events. 0-RTT typically
// races the ServerHello from the server with early data from the client. If
// the ServerHello arrives before client calls Write(), the data may be sent
// with 1-RTT keys rather than 0-RTT keys.
FakeBlockingStreamSocket* MakeClient(bool early_data_enabled) {
SSLConfig ssl_config;
ssl_config.early_data_enabled = early_data_enabled;
real_transport_ = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport_));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback_.GetResult(transport->Connect(callback_.callback()));
EXPECT_THAT(rv, IsOk());
ssl_socket_ = CreateSSLClientSocket(std::move(transport), host_port_pair(),
ssl_config);
EXPECT_FALSE(ssl_socket_->IsConnected());
return raw_transport;
}
int Connect() {
return callback_.GetResult(ssl_socket_->Connect(callback_.callback()));
}
int WriteAndWait(std::string_view request) {
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request));
return callback_.GetResult(
ssl_socket_->Write(request_buffer.get(), request.size(),
callback_.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
}
int ReadAndWait(IOBuffer* buf, size_t len) {
return callback_.GetResult(
ssl_socket_->Read(buf, len, callback_.callback()));
}
bool GetSSLInfo(SSLInfo* ssl_info) {
return ssl_socket_->GetSSLInfo(ssl_info);
}
bool RunInitialConnection() {
if (MakeClient(true) == nullptr)
return false;
EXPECT_THAT(Connect(), IsOk());
// Use the socket for an HTTP request to ensure we've processed the
// post-handshake TLS 1.3 ticket.
EXPECT_THAT(MakeHTTPRequest(ssl_socket_.get()), IsOk());
SSLInfo ssl_info;
EXPECT_TRUE(GetSSLInfo(&ssl_info));
// Make sure all asynchronous histogram logging is complete.
base::RunLoop().RunUntilIdle();
return SSLInfo::HANDSHAKE_FULL == ssl_info.handshake_type;
}
SSLClientSocket* ssl_socket() { return ssl_socket_.get(); }
private:
TestCompletionCallback callback_;
std::unique_ptr<StreamSocket> real_transport_;
std::unique_ptr<SSLClientSocket> ssl_socket_;
};
// Returns a serialized unencrypted TLS 1.2 alert record for the given alert
// value.
std::string FormatTLS12Alert(uint8_t alert) {
std::string ret;
// ContentType.alert
ret.push_back(21);
// Record-layer version. Assume TLS 1.2.
ret.push_back(0x03);
ret.push_back(0x03);
// Record length.
ret.push_back(0);
ret.push_back(2);
// AlertLevel.fatal.
ret.push_back(2);
// The alert itself.
ret.push_back(alert);
return ret;
}
// A CertVerifier that never returns on any requests.
class HangingCertVerifier : public CertVerifier {
public:
int num_active_requests() const { return num_active_requests_; }
void WaitForRequest() {
if (!num_active_requests_) {
run_loop_.Run();
}
}
int Verify(const RequestParams& params,
CertVerifyResult* verify_result,
CompletionOnceCallback callback,
std::unique_ptr<Request>* out_req,
const NetLogWithSource& net_log) override {
*out_req = std::make_unique<HangingRequest>(this);
return ERR_IO_PENDING;
}
void Verify2QwacBinding(
const std::string& binding,
const std::string& hostname,
const scoped_refptr<net::X509Certificate>& tls_cert,
base::OnceCallback<void(const scoped_refptr<net::X509Certificate>&)>
callback,
const net::NetLogWithSource& net_log) override {
ADD_FAILURE();
std::move(callback).Run(nullptr);
}
void SetConfig(const Config& config) override {}
void AddObserver(Observer* observer) override {}
void RemoveObserver(Observer* observer) override {}
private:
class HangingRequest : public Request {
public:
explicit HangingRequest(HangingCertVerifier* verifier)
: verifier_(verifier) {
verifier_->num_active_requests_++;
verifier_->run_loop_.Quit();
}
~HangingRequest() override { verifier_->num_active_requests_--; }
private:
raw_ptr<HangingCertVerifier> verifier_;
};
base::RunLoop run_loop_;
int num_active_requests_ = 0;
};
class MockSSLClientContextObserver : public SSLClientContext::Observer {
public:
MOCK_METHOD1(OnSSLConfigChanged, void(SSLClientContext::SSLConfigChangeType));
MOCK_METHOD1(OnSSLConfigForServersChanged,
void(const base::flat_set<HostPortPair>&));
};
} // namespace
INSTANTIATE_TEST_SUITE_P(TLSVersion,
SSLClientSocketVersionTest,
ValuesIn(GetTLSVersions()));
TEST_P(SSLClientSocketVersionTest, Connect) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
EXPECT_FALSE(sock->IsConnected());
rv = sock->Connect(callback.callback());
auto entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLogEventType::SSL_CONNECT));
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLogEventType::SSL_CONNECT));
sock->Disconnect();
EXPECT_FALSE(sock->IsConnected());
}
TEST_P(SSLClientSocketVersionTest, ConnectSyncVerify) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
cert_verifier_->set_async(false);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(OK));
}
TEST_P(SSLClientSocketVersionTest, ConnectExpired) {
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_EXPIRED,
GetServerConfig()));
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_DATE_INVALID));
// Rather than testing whether or not the underlying socket is connected,
// test that the handshake has finished. This is because it may be
// desirable to disconnect the socket before showing a user prompt, since
// the user may take indefinitely long to respond.
auto entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLogEventType::SSL_CONNECT));
}
TEST_P(SSLClientSocketVersionTest, ConnectExpiredSyncVerify) {
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_EXPIRED,
GetServerConfig()));
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
cert_verifier_->set_async(false);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_DATE_INVALID));
}
// Test that SSLClientSockets may be destroyed while waiting on a certificate
// verification.
TEST_P(SSLClientSocketVersionTest, SocketDestroyedDuringVerify) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
HangingCertVerifier verifier;
context_ = std::make_unique<SSLClientContext>(
ssl_config_service_.get(), &verifier, transport_security_state_.get(),
ssl_client_session_cache_.get(), nullptr);
TestCompletionCallback callback;
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig());
rv = sock->Connect(callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// The socket should attempt a certificate verification.
verifier.WaitForRequest();
EXPECT_EQ(1, verifier.num_active_requests());
// Destroying the socket should cancel it.
sock = nullptr;
EXPECT_EQ(0, verifier.num_active_requests());
context_ = nullptr;
}
TEST_P(SSLClientSocketVersionTest, ConnectMismatched) {
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_MISMATCHED_NAME,
GetServerConfig()));
cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_COMMON_NAME_INVALID));
// Rather than testing whether or not the underlying socket is connected,
// test that the handshake has finished. This is because it may be
// desirable to disconnect the socket before showing a user prompt, since
// the user may take indefinitely long to respond.
auto entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLogEventType::SSL_CONNECT));
}
// Tests that certificates parsable by SSLClientSocket's internal SSL
// implementation, but not parsable by X509Certificate are treated as fatal
// connection errors. This is a regression test for https://crbug.com/91341.
TEST_P(SSLClientSocketVersionTest, ConnectInvalidCert) {
EmbeddedTestServer::ServerCertificateConfig cert_config;
// Set the leaf certificate subject field to an invalid Name. The subject
// field isn't parsed by the SSL implementation, so this only fails when
// trying to construct an X509Certificate for the leaf.
// SEQUENCE { NULL }
cert_config.subject_tlv = {0x30, 0x01, 0x05};
ASSERT_TRUE(StartEmbeddedTestServer(cert_config, GetServerConfig()));
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_SERVER_CERT_BAD_FORMAT));
}
// If the certificate could not be parsed as an X509Certificate, overriding the
// error is not possible.
TEST_P(SSLClientSocketVersionTest, ConnectInvalidCertCannotIgnoreCertErrors) {
EmbeddedTestServer::ServerCertificateConfig cert_config;
// Set the leaf certificate subject field to an invalid Name. The subject
// field isn't parsed by the SSL implementation, so this only fails when
// trying to construct an X509Certificate for the leaf.
// SEQUENCE { NULL }
cert_config.subject_tlv = {0x30, 0x01, 0x05};
ASSERT_TRUE(StartEmbeddedTestServer(cert_config, GetServerConfig()));
SSLConfig ssl_config;
ssl_config.ignore_certificate_errors = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_SERVER_CERT_BAD_FORMAT));
}
// Ignoring the certificate error from an untrusted certificate should
// allow a complete connection.
TEST_P(SSLClientSocketVersionTest, ConnectUntrustedCertIgnoreCertErrors) {
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_EXPIRED,
GetServerConfig()));
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
SSLConfig ssl_config;
ssl_config.ignore_certificate_errors = true;
int rv;
CreateAndConnectSSLClientSocket(ssl_config, &rv);
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
}
// Client certificates are disabled on iOS.
#if BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
// Attempt to connect to a page which requests a client certificate. It should
// return an error code on connect.
TEST_P(SSLClientSocketVersionTest, ConnectClientAuthCertRequested) {
SSLServerConfig server_config = GetServerConfig();
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
auto entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLogEventType::SSL_CONNECT));
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server requesting optional client authentication. Send it a
// null certificate. It should allow the connection.
TEST_P(SSLClientSocketVersionTest, ConnectClientAuthSendNullCert) {
SSLServerConfig server_config = GetServerConfig();
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Our test server accepts certificate-less connections.
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
// We responded to the server's certificate request with a Certificate
// message with no client certificate in it. ssl_info.client_cert_sent
// should be false in this case.
SSLInfo ssl_info;
sock_->GetSSLInfo(&ssl_info);
EXPECT_FALSE(ssl_info.client_cert_sent);
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
#endif // BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
// TODO(wtc): Add unit tests for IsConnectedAndIdle:
// - Server closes an SSL connection (with a close_notify alert message).
// - Server closes the underlying TCP connection directly.
// - Server sends data unexpectedly.
// Tests that the socket can be read from successfully. Also test that a peer's
// close_notify alert is successfully processed without error.
TEST_P(SSLClientSocketReadTest, Read) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto transport = std::make_unique<TCPClientSocket>(addr(), nullptr, nullptr,
nullptr, NetLogSource());
EXPECT_EQ(0, transport->GetTotalReceivedBytes());
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
EXPECT_EQ(0, sock->GetTotalReceivedBytes());
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
// Number of network bytes received should increase because of SSL socket
// establishment.
EXPECT_GT(sock->GetTotalReceivedBytes(), 0);
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(request_text.size(), rv);
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int64_t unencrypted_bytes_read = 0;
int64_t network_bytes_read_during_handshake = sock->GetTotalReceivedBytes();
do {
rv = ReadAndWaitForCompletion(sock.get(), buf.get(), 4096);
EXPECT_GE(rv, 0);
if (rv >= 0) {
unencrypted_bytes_read += rv;
}
} while (rv > 0);
EXPECT_GT(unencrypted_bytes_read, 0);
// Reading the payload should increase the number of bytes on network layer.
EXPECT_GT(sock->GetTotalReceivedBytes(), network_bytes_read_during_handshake);
// Number of bytes received on the network after the handshake should be
// higher than the number of encrypted bytes read.
EXPECT_GE(sock->GetTotalReceivedBytes() - network_bytes_read_during_handshake,
unencrypted_bytes_read);
// The peer should have cleanly closed the connection with a close_notify.
EXPECT_EQ(0, rv);
}
// Tests that SSLClientSocket properly handles when the underlying transport
// synchronously fails a transport write in during the handshake.
TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SynchronousErrorStreamSocket* raw_transport = transport.get();
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
EXPECT_FALSE(sock->IsConnected());
}
// Tests that the SSLClientSocket properly handles when the underlying transport
// synchronously returns an error code - such as if an intermediary terminates
// the socket connection uncleanly.
// This is a regression test for http://crbug.com/238536
TEST_P(SSLClientSocketReadTest, Read_WithSynchronousError) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
SynchronousErrorStreamSocket* raw_transport = transport.get();
std::unique_ptr<SSLClientSocket> sock(
CreateSSLClientSocket(std::move(transport), host_port_pair(), config));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(request_text.size(), rv);
// Simulate an unclean/forcible shutdown.
raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
// Note: This test will hang if this bug has regressed. Simply checking that
// rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
// result when using a dedicated task runner for NSS.
rv = ReadAndWaitForCompletion(sock.get(), buf.get(), 4096);
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
// Tests that the SSLClientSocket properly handles when the underlying transport
// asynchronously returns an error code while writing data - such as if an
// intermediary terminates the socket connection uncleanly.
// This is a regression test for http://crbug.com/249848
TEST_P(SSLClientSocketVersionTest, Write_WithSynchronousError) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
// Note: |error_socket|'s ownership is handed to |transport|, but a pointer
// is retained in order to configure additional errors.
auto error_socket =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(error_socket));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
// Simulate an unclean/forcible shutdown on the underlying socket.
// However, simulate this error asynchronously.
raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
raw_transport->BlockWrite();
// This write should complete synchronously, because the TLS ciphertext
// can be created and placed into the outgoing buffers independent of the
// underlying transport.
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(request_text.size(), rv);
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
rv = sock->Read(buf.get(), 4096, callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Now unblock the outgoing request, having it fail with the connection
// being reset.
raw_transport->UnblockWrite();
// Note: This will cause an inifite loop if this bug has regressed. Simply
// checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
// is a legitimate result when using a dedicated task runner for NSS.
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
// If there is a Write failure at the transport with no follow-up Read, although
// the write error will not be returned to the client until a future Read or
// Write operation, SSLClientSocket should not spin attempting to re-write on
// the socket. This is a regression test for part of https://crbug.com/381160.
TEST_P(SSLClientSocketVersionTest, Write_WithSynchronousErrorNoRead) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
// Note: intermediate sockets' ownership are handed to |sock|, but a pointer
// is retained in order to query them.
auto error_socket =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
auto counting_socket =
std::make_unique<CountingStreamSocket>(std::move(error_socket));
CountingStreamSocket* raw_counting_socket = counting_socket.get();
int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(counting_socket), host_port_pair(), SSLConfig()));
rv = callback.GetResult(sock->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock->IsConnected());
// Simulate an unclean/forcible shutdown on the underlying socket.
raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
// This write should complete synchronously, because the TLS ciphertext
// can be created and placed into the outgoing buffers independent of the
// underlying transport.
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
ASSERT_EQ(request_text.size(), rv);
// Let the event loop spin for a little bit of time. Even on platforms where
// pumping the state machine involve thread hops, there should be no further
// writes on the transport socket.
//
// TODO(davidben): Avoid the arbitrary timeout?
int old_write_count = raw_counting_socket->write_count();
base::RunLoop loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, loop.QuitClosure(), base::Milliseconds(100));
loop.Run();
EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
}
// Test the full duplex mode, with Read and Write pending at the same time.
// This test also serves as a regression test for http://crbug.com/29815.
TEST_P(SSLClientSocketReadTest, Read_FullDuplex) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
// Issue a "hanging" Read first.
TestCompletionCallback callback;
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int read_rv = Read(sock_.get(), buf.get(), 4096, callback.callback());
// We haven't written the request, so there should be no response yet.
ASSERT_THAT(read_rv, IsError(ERR_IO_PENDING));
// Write the request.
// The request is padded with a User-Agent header to a size that causes the
// memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
// This tests the fix for http://crbug.com/29815.
std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
for (int i = 0; i < 3770; ++i)
request_text.push_back('*');
request_text.append("\r\n\r\n");
auto request_buffer = base::MakeRefCounted<StringIOBuffer>(request_text);
TestCompletionCallback callback2; // Used for Write only.
rv = callback2.GetResult(
sock_->Write(request_buffer.get(), request_text.size(),
callback2.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(static_cast<int>(request_text.size()), rv);
// Now get the Read result.
read_rv =
WaitForReadCompletion(sock_.get(), buf.get(), 4096, &callback, read_rv);
EXPECT_GT(read_rv, 0);
}
// Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
// mode when the underlying transport is blocked on sending data. When the
// underlying transport completes due to an error, it should invoke both the
// Read() and Write() callbacks. If the socket is deleted by the Read()
// callback, the Write() callback should not be invoked.
// Regression test for http://crbug.com/232633
TEST_P(SSLClientSocketReadTest, Read_DeleteWhilePendingFullDuplex) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
// Note: |error_socket|'s ownership is handed to |transport|, but a pointer
// is retained in order to configure additional errors.
auto error_socket =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(error_socket));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
std::unique_ptr<SSLClientSocket> sock =
CreateSSLClientSocket(std::move(transport), host_port_pair(), config);
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
request_text.append(20 * 1024, '*');
request_text.append("\r\n\r\n");
scoped_refptr<DrainableIOBuffer> request_buffer =
base::MakeRefCounted<DrainableIOBuffer>(
base::MakeRefCounted<StringIOBuffer>(request_text),
request_text.size());
// Simulate errors being returned from the underlying Read() and Write() ...
raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
// ... but have those errors returned asynchronously. Because the Write() will
// return first, this will trigger the error.
raw_transport->BlockReadResult();
raw_transport->BlockWrite();
// Enqueue a Read() before calling Write(), which should "hang" due to
// the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
SSLClientSocket* raw_sock = sock.get();
DeleteSocketCallback read_callback(sock.release());
auto read_buf = base::MakeRefCounted<IOBufferWithSize>(4096);
rv = Read(raw_sock, read_buf.get(), 4096, read_callback.callback());
// Ensure things didn't complete synchronously, otherwise |sock| is invalid.
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
ASSERT_FALSE(read_callback.have_result());
// Attempt to write the remaining data. OpenSSL will return that its blocked
// because the underlying transport is blocked.
rv = raw_sock->Write(request_buffer.get(), request_buffer->BytesRemaining(),
callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
ASSERT_FALSE(callback.have_result());
// Now unblock Write(), which will invoke OnSendComplete and (eventually)
// call the Read() callback, deleting the socket and thus aborting calling
// the Write() callback.
raw_transport->UnblockWrite();
// |read_callback| deletes |sock| so if ReadIfReady() is used, we will get OK
// asynchronously but can't continue reading because the socket is gone.
rv = read_callback.WaitForResult();
if (test_ssl_read_if_ready()) {
EXPECT_THAT(rv, IsOk());
} else {
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
// The Write callback should not have been called.
EXPECT_FALSE(callback.have_result());
}
// Tests that the SSLClientSocket does not crash if data is received on the
// transport socket after a failing write. This can occur if we have a Write
// error in a SPDY socket.
// Regression test for http://crbug.com/335557
TEST_P(SSLClientSocketReadTest, Read_WithWriteError) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
// Note: |error_socket|'s ownership is handed to |transport|, but a pointer
// is retained in order to configure additional errors.
auto error_socket =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(error_socket));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
// Send a request so there is something to read from the socket.
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(request_text.size(), rv);
// Start a hanging read.
TestCompletionCallback read_callback;
raw_transport->BlockReadResult();
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
rv = Read(sock.get(), buf.get(), 4096, read_callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Perform another write, but have it fail. Write a request larger than the
// internal socket buffers so that the request hits the underlying transport
// socket and detects the error.
std::string long_request_text =
"GET / HTTP/1.1\r\nUser-Agent: long browser name ";
long_request_text.append(20 * 1024, '*');
long_request_text.append("\r\n\r\n");
scoped_refptr<DrainableIOBuffer> long_request_buffer =
base::MakeRefCounted<DrainableIOBuffer>(
base::MakeRefCounted<StringIOBuffer>(long_request_text),
long_request_text.size());
raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
// Write as much data as possible until hitting an error.
do {
rv = callback.GetResult(sock->Write(
long_request_buffer.get(), long_request_buffer->BytesRemaining(),
callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
if (rv > 0) {
long_request_buffer->DidConsume(rv);
// Abort if the entire input is ever consumed. The input is larger than
// the SSLClientSocket's write buffers.
ASSERT_LT(0, long_request_buffer->BytesRemaining());
}
} while (rv > 0);
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
// At this point the Read result is available. Transport write errors are
// surfaced through Writes. See https://crbug.com/249848.
rv = WaitForReadCompletion(sock.get(), buf.get(), 4096, &read_callback, rv);
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
// Release the read. This does not cause a crash.
raw_transport->UnblockReadResult();
base::RunLoop().RunUntilIdle();
}
// Tests that SSLClientSocket fails the handshake if the underlying
// transport is cleanly closed.
TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
// There is no need to vary by TLS version because this test never reads a
// response from the server.
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SynchronousErrorStreamSocket* raw_transport = transport.get();
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
raw_transport->SetNextReadError(0);
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsError(ERR_CONNECTION_CLOSED));
EXPECT_FALSE(sock->IsConnected());
}
// Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
// is cleanly closed, but the peer does not send close_notify.
// This is a regression test for https://crbug.com/422246
TEST_P(SSLClientSocketReadTest, Read_WithZeroReturn) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
SynchronousErrorStreamSocket* raw_transport = transport.get();
std::unique_ptr<SSLClientSocket> sock(
CreateSSLClientSocket(std::move(transport), host_port_pair(), config));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
raw_transport->SetNextReadError(0);
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
rv = ReadAndWaitForCompletion(sock.get(), buf.get(), 4096);
EXPECT_EQ(0, rv);
}
// Tests that SSLClientSocket cleanly returns a Read of size 0 if the
// underlying socket is cleanly closed asynchronously.
// This is a regression test for https://crbug.com/422246
TEST_P(SSLClientSocketReadTest, Read_WithAsyncZeroReturn) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto error_socket =
std::make_unique<SynchronousErrorStreamSocket>(std::move(real_transport));
SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(error_socket));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
std::unique_ptr<SSLClientSocket> sock(
CreateSSLClientSocket(std::move(transport), host_port_pair(), config));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
raw_error_socket->SetNextReadError(0);
raw_transport->BlockReadResult();
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
TestCompletionCallback read_callback;
rv = Read(sock.get(), buf.get(), 4096, read_callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->UnblockReadResult();
rv = WaitForReadCompletion(sock.get(), buf.get(), 4096, &read_callback, rv);
EXPECT_EQ(0, rv);
}
// Tests that fatal alerts from the peer are processed. This is a regression
// test for https://crbug.com/466303.
TEST_P(SSLClientSocketReadTest, Read_WithFatalAlert) {
SSLServerConfig server_config = GetServerConfig();
server_config.alert_after_handshake_for_testing = SSL_AD_INTERNAL_ERROR;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
// Receive the fatal alert.
TestCompletionCallback callback;
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR,
ReadAndWaitForCompletion(sock_.get(), buf.get(), 4096));
}
TEST_P(SSLClientSocketReadTest, Read_SmallChunks) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
TestCompletionCallback callback;
rv = callback.GetResult(sock_->Write(request_buffer.get(),
request_text.size(), callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(static_cast<int>(request_text.size()), rv);
auto buf = base::MakeRefCounted<IOBufferWithSize>(1);
do {
rv = ReadAndWaitForCompletion(sock_.get(), buf.get(), 1);
EXPECT_GE(rv, 0);
} while (rv > 0);
}
TEST_P(SSLClientSocketReadTest, Read_ManySmallRecords) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<ReadBufferingStreamSocket>(std::move(real_transport));
ReadBufferingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
std::unique_ptr<SSLClientSocket> sock(
CreateSSLClientSocket(std::move(transport), host_port_pair(), config));
rv = callback.GetResult(sock->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock->IsConnected());
static constexpr std::string_view request_text =
"GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
ASSERT_GT(rv, 0);
ASSERT_EQ(static_cast<int>(request_text.size()), rv);
// Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
// data (the max SSL record size) at a time. Ensure that at least 15K worth
// of SSL data is buffered first. The 15K of buffered data is made up of
// many smaller SSL records (the TestServer writes along 1350 byte
// plaintext boundaries), although there may also be a few records that are
// smaller or larger, due to timing and SSL False Start.
// 15K was chosen because 15K is smaller than the 17K (max) read issued by
// the SSLClientSocket implementation, and larger than the minimum amount
// of ciphertext necessary to contain the 8K of plaintext requested below.
raw_transport->BufferNextRead(15000);
auto buffer = base::MakeRefCounted<IOBufferWithSize>(8192);
rv = ReadAndWaitForCompletion(sock.get(), buffer.get(), 8192);
ASSERT_EQ(rv, 8192);
}
TEST_P(SSLClientSocketReadTest, Read_Interrupted) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
TestCompletionCallback callback;
rv = callback.GetResult(sock_->Write(request_buffer.get(),
request_text.size(), callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(static_cast<int>(request_text.size()), rv);
// Do a partial read and then exit. This test should not crash!
auto buf = base::MakeRefCounted<IOBufferWithSize>(512);
rv = ReadAndWaitForCompletion(sock_.get(), buf.get(), 512);
EXPECT_GT(rv, 0);
}
TEST_P(SSLClientSocketReadTest, Read_FullLogging) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
log_observer_.SetObserverCaptureMode(NetLogCaptureMode::kEverything);
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock->IsConnected());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
rv = callback.GetResult(sock->Write(request_buffer.get(), request_text.size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(static_cast<int>(request_text.size()), rv);
auto entries = log_observer_.GetEntries();
size_t last_index = ExpectLogContainsSomewhereAfter(
entries, 5, NetLogEventType::SSL_SOCKET_BYTES_SENT,
NetLogEventPhase::NONE);
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
for (;;) {
rv = ReadAndWaitForCompletion(sock.get(), buf.get(), 4096);
EXPECT_GE(rv, 0);
if (rv <= 0)
break;
entries = log_observer_.GetEntries();
last_index = ExpectLogContainsSomewhereAfter(
entries, last_index + 1, NetLogEventType::SSL_SOCKET_BYTES_RECEIVED,
NetLogEventPhase::NONE);
}
}
// Regression test for http://crbug.com/42538
TEST_F(SSLClientSocketTest, PrematureApplicationData) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
static const unsigned char application_data[] = {
0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
0x0a};
// All reads and writes complete synchronously (async=false).
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, reinterpret_cast<const char*>(application_data),
std::size(application_data)),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
TestCompletionCallback callback;
std::unique_ptr<StreamSocket> transport(
std::make_unique<MockTCPClientSocket>(addr(), nullptr, &data));
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
}
TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLContextConfig ssl_context_config;
ssl_context_config.disabled_cipher_suites.push_back(kModernTLS12Cipher);
ssl_config_service_->UpdateSSLConfigAndNotify(ssl_context_config);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
// Test that TLS versions prior to TLS 1.2 cannot be configured in
// SSLClientSocket.
TEST_F(SSLClientSocketTest, LegacyTLSVersions) {
// Start a server, just so the underlying socket can connect somewhere, but it
// will fail before talking to the server, so it is fine that the server does
// not speak these versions.
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
// Although we don't have `SSL_PROTOCOL_VERSION_*` constants for SSL 3.0
// through TLS 1.1, these values are just passed through to the BoringSSL API,
// which means the underlying protocol version numbers can be used here.
//
// TODO(crbug.com/40893435): Ideally SSLConfig would just take an enum,
// at which point this test can be removed.
for (uint16_t version : {SSL3_VERSION, TLS1_VERSION, TLS1_1_VERSION}) {
SCOPED_TRACE(version);
SSLConfig config;
config.version_min_override = version;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsError(ERR_UNEXPECTED));
config.version_min_override = std::nullopt;
config.version_max_override = version;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsError(ERR_UNEXPECTED));
}
}
// When creating an SSLClientSocket, it is allowed to pass in a
// ClientSocketHandle that is not obtained from a client socket pool.
// Here we verify that such a simple ClientSocketHandle, not associated with any
// client socket pool, can be destroyed safely.
TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
TestCompletionCallback callback;
auto transport = std::make_unique<TCPClientSocket>(addr(), nullptr, nullptr,
nullptr, NetLogSource());
int rv = callback.GetResult(transport->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(socket_factory_->CreateSSLClientSocket(
context_.get(), std::move(transport), host_port_pair(), SSLConfig()));
EXPECT_FALSE(sock->IsConnected());
rv = callback.GetResult(sock->Connect(callback.callback()));
EXPECT_THAT(rv, IsOk());
}
// Verifies that SSLClientSocket::ExportKeyingMaterial return a success
// code and different keying label results in different keying material.
TEST_P(SSLClientSocketVersionTest, ExportKeyingMaterial) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
const int kKeyingMaterialSize = 32;
const char kKeyingLabel1[] = "client-socket-test-1";
std::array<uint8_t, kKeyingMaterialSize> client_out1;
rv = sock_->ExportKeyingMaterial(kKeyingLabel1, std::nullopt, client_out1);
EXPECT_EQ(rv, OK);
const char kKeyingLabel2[] = "client-socket-test-2";
std::array<uint8_t, kKeyingMaterialSize> client_out2;
rv = sock_->ExportKeyingMaterial(kKeyingLabel2, std::nullopt, client_out2);
EXPECT_EQ(rv, OK);
EXPECT_NE(client_out1, client_out2);
const char kKeyingContext2[] = "context";
client_out2.fill(0);
rv = sock_->ExportKeyingMaterial(
kKeyingLabel1, base::as_byte_span(kKeyingContext2), client_out2);
EXPECT_EQ(rv, OK);
EXPECT_NE(client_out1, client_out2);
// Prior to TLS 1.3, using an empty context should give different key material
// from not using a context at all. In TLS 1.3, the distinction is deprecated
// and they are the same.
client_out2.fill(0);
rv = sock_->ExportKeyingMaterial(kKeyingLabel1, base::span<const uint8_t>(),
client_out2);
EXPECT_EQ(rv, OK);
if (version() >= SSL_PROTOCOL_VERSION_TLS1_3) {
EXPECT_EQ(client_out1, client_out2);
} else {
EXPECT_NE(client_out1, client_out2);
}
}
TEST(SSLClientSocket, SerializeNextProtos) {
NextProtoVector next_protos;
next_protos.push_back(NextProto::kProtoHTTP11);
next_protos.push_back(NextProto::kProtoHTTP2);
static std::vector<uint8_t> serialized =
SSLClientSocket::SerializeNextProtos(next_protos);
ASSERT_EQ(12u, serialized.size());
EXPECT_EQ(8, serialized[0]); // length("http/1.1")
EXPECT_EQ('h', serialized[1]);
EXPECT_EQ('t', serialized[2]);
EXPECT_EQ('t', serialized[3]);
EXPECT_EQ('p', serialized[4]);
EXPECT_EQ('/', serialized[5]);
EXPECT_EQ('1', serialized[6]);
EXPECT_EQ('.', serialized[7]);
EXPECT_EQ('1', serialized[8]);
EXPECT_EQ(2, serialized[9]); // length("h2")
EXPECT_EQ('h', serialized[10]);
EXPECT_EQ('2', serialized[11]);
}
// Test that the server certificates are properly retrieved from the underlying
// SSL stack.
TEST_P(SSLClientSocketVersionTest, VerifyServerChainProperlyOrdered) {
// The connection does not have to be successful.
cert_verifier_->set_default_result(ERR_CERT_INVALID);
// Set up a test server with CERT_CHAIN_WRONG_ROOT.
// This makes the server present redundant-server-chain.pem, which contains
// intermediate certificates.
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_CHAIN_WRONG_ROOT,
GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_INVALID));
EXPECT_FALSE(sock_->IsConnected());
// When given option CERT_CHAIN_WRONG_ROOT, EmbeddedTestServer will present
// certs from redundant-server-chain.pem.
CertificateList server_certs =
CreateCertificateListFromFile(GetTestCertsDirectory(),
"redundant-server-chain.pem",
X509Certificate::FORMAT_AUTO);
// Get the server certificate as received client side.
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
scoped_refptr<X509Certificate> server_certificate = ssl_info.unverified_cert;
// Get the intermediates as received client side.
const auto& server_intermediates = server_certificate->intermediate_buffers();
// Check that the unverified server certificate chain is properly retrieved
// from the underlying ssl stack.
ASSERT_EQ(4U, server_certs.size());
EXPECT_TRUE(x509_util::CryptoBufferEqual(server_certificate->cert_buffer(),
server_certs[0]->cert_buffer()));
ASSERT_EQ(3U, server_intermediates.size());
EXPECT_TRUE(x509_util::CryptoBufferEqual(server_intermediates[0].get(),
server_certs[1]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(server_intermediates[1].get(),
server_certs[2]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(server_intermediates[2].get(),
server_certs[3]->cert_buffer()));
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// This tests that SSLInfo contains a properly re-constructed certificate
// chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
// verified, not the chain as served by the server. (They may be different.)
//
// CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
// (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
// contains a chain of A -> B -> C2, where C2 is the same public key as C, but
// a self-signed root. Such a situation can occur when a new root (C2) is
// cross-certified by an old root (D) and has two different versions of its
// floating around. Servers may supply C2 as an intermediate, but the
// SSLClientSocket should return the chain that was verified, from
// verify_result, instead.
TEST_P(SSLClientSocketVersionTest, VerifyReturnChainProperlyOrdered) {
// By default, cause the CertVerifier to treat all certificates as
// expired.
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
CertificateList unverified_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "redundant-server-chain.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(4u, unverified_certs.size());
// We will expect SSLInfo to ultimately contain this chain.
CertificateList certs =
CreateCertificateListFromFile(GetTestCertsDirectory(),
"redundant-validated-chain.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
ASSERT_TRUE(certs[0]->EqualsExcludingChain(unverified_certs[0].get()));
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> temp_intermediates;
temp_intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer()));
temp_intermediates.push_back(bssl::UpRef(certs[2]->cert_buffer()));
CertVerifyResult verify_result;
verify_result.verified_cert = X509Certificate::CreateFromBuffer(
bssl::UpRef(certs[0]->cert_buffer()), std::move(temp_intermediates));
ASSERT_TRUE(verify_result.verified_cert);
// Add a rule that maps the server cert (A) to the chain of A->B->C2
// rather than A->B->C.
cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
// Load and install the root for the validated chain.
scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
ASSERT_NE(static_cast<X509Certificate*>(nullptr), root_cert.get());
ScopedTestRoot scoped_root(root_cert);
// Set up a test server with CERT_CHAIN_WRONG_ROOT.
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_CHAIN_WRONG_ROOT,
GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
auto entries = log_observer_.GetEntries();
EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLogEventType::SSL_CONNECT));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
// Verify that SSLInfo contains the corrected re-constructed chain A -> B
// -> C2.
ASSERT_TRUE(ssl_info.cert);
const auto& intermediates = ssl_info.cert->intermediate_buffers();
ASSERT_EQ(2U, intermediates.size());
EXPECT_TRUE(x509_util::CryptoBufferEqual(ssl_info.cert->cert_buffer(),
certs[0]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(intermediates[0].get(),
certs[1]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(intermediates[1].get(),
certs[2]->cert_buffer()));
// Verify that SSLInfo also contains the chain as received from the server.
ASSERT_TRUE(ssl_info.unverified_cert);
const auto& served_intermediates =
ssl_info.unverified_cert->intermediate_buffers();
ASSERT_EQ(3U, served_intermediates.size());
EXPECT_TRUE(x509_util::CryptoBufferEqual(ssl_info.cert->cert_buffer(),
unverified_certs[0]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(served_intermediates[0].get(),
unverified_certs[1]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(served_intermediates[1].get(),
unverified_certs[2]->cert_buffer()));
EXPECT_TRUE(x509_util::CryptoBufferEqual(served_intermediates[2].get(),
unverified_certs[3]->cert_buffer()));
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// Client certificates are disabled on iOS.
#if BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
INSTANTIATE_TEST_SUITE_P(TLSVersion,
SSLClientSocketCertRequestInfoTest,
ValuesIn(GetTLSVersions()));
TEST_P(SSLClientSocketCertRequestInfoTest,
DontRequestClientCertsIfServerCertInvalid) {
SSLServerConfig config = GetServerConfig();
config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_EXPIRED, config));
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_DATE_INVALID));
}
TEST_P(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
SSLServerConfig config = GetServerConfig();
config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, config));
scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest();
ASSERT_TRUE(request_info.get());
EXPECT_EQ(0u, request_info->cert_authorities.size());
}
TEST_P(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
const unsigned char kThawteDN[] = {
0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
const unsigned char kDiginotarDN[] = {
0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
0x6c};
SSLServerConfig config = GetServerConfig();
config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
config.cert_authorities.emplace_back(std::begin(kThawteDN),
std::end(kThawteDN));
config.cert_authorities.emplace_back(std::begin(kDiginotarDN),
std::end(kDiginotarDN));
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, config));
scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest();
ASSERT_TRUE(request_info.get());
EXPECT_EQ(config.cert_authorities, request_info->cert_authorities);
}
TEST_P(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
SSLServerConfig config = GetServerConfig();
config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, config));
scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest();
ASSERT_TRUE(request_info);
// Look for some values we expect BoringSSL to always send.
EXPECT_THAT(request_info->signature_algorithms,
testing::Contains(SSL_SIGN_ECDSA_SECP256R1_SHA256));
EXPECT_THAT(request_info->signature_algorithms,
testing::Contains(SSL_SIGN_RSA_PSS_RSAE_SHA256));
}
#endif // BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
// Tests that the Certificate Transparency (RFC 6962) TLS extension is
// supported.
TEST_P(SSLClientSocketVersionTest, ConnectSignedCertTimestampsTLSExtension) {
// Encoding of SCT List containing 'test'.
std::string_view sct_ext("\x00\x06\x00\x04test", 8);
SSLServerConfig server_config = GetServerConfig();
server_config.signed_cert_timestamp_list =
std::vector<uint8_t>(sct_ext.begin(), sct_ext.end());
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_EQ(cert_verifier_->GetVerifyParams().size(), 1u);
const auto& params = cert_verifier_->GetVerifyParams().front();
EXPECT_TRUE(params.certificate()->EqualsIncludingChain(
embedded_test_server()->GetCertificate().get()));
EXPECT_EQ(params.hostname(), embedded_test_server()->host_port_pair().host());
EXPECT_EQ(params.ocsp_response(), "");
EXPECT_EQ(params.sct_list(), sct_ext);
sock_ = nullptr;
context_ = nullptr;
}
// Tests that Trust Anchor IDs are sent when configured via SSLConfig.
TEST_P(SSLClientSocketVersionTest, ConnectWithTrustAnchorIDs) {
SSLConfig ssl_config;
ssl_config.trust_anchor_ids = {0x03, 0x01, 0x02, 0x03};
bool ran_callback = false;
SSLServerConfig server_config = GetServerConfig();
server_config.client_hello_callback_for_testing =
base::BindLambdaForTesting([&](const SSL_CLIENT_HELLO* client_hello) {
const uint8_t* data;
size_t len = 0;
EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_trust_anchors, &data, &len));
// The TLS extension should contain the configured trust anchor IDs
// list, plus a 2-byte length prefix.
if (len != ssl_config.trust_anchor_ids.size() + 2) {
// Ideally this would be ASSERT_EQ(len,
// ssl_config.trust_anchor_ids.size() + 2), but we can't ASSERT in a
// function with a return value.
return false;
}
EXPECT_EQ(
base::span(ssl_config.trust_anchor_ids),
// SAFETY:
// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_early_callback_ctx_extension_get
// The comment of `SSL_early_callback_ctx_extension_get` says
// that `data` is set to extension contents, and `len` is the
// length of the extension contents.
//
// Earlier, we checked that ssl_config.trust_anchor_ids.size() + 2
// == len.
UNSAFE_BUFFERS(
base::span(data + 2, ssl_config.trust_anchor_ids.size())));
ran_callback = true;
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
}
// Tests that SSLClientSocket sends Trust Anchor IDs when configured via
// SSLConfig (similar to ConnectWithTrustAnchorIDs, but more end-to-end as it
// tests that sending a Trust Anchor ID influences the actual certificate that
// the server serves), and properly retrieves the server's Trust Anchor IDs from
// the handshake on error.
TEST_P(SSLClientSocketVersionTest, ConnectToServerWithTrustAnchorIDs) {
SSLServerConfig server_config;
SSLConfig client_config;
server_config.intermediate_trust_anchor_id = {0x01, 0x02, 0x03};
ASSERT_TRUE(StartEmbeddedTestServer(
EmbeddedTestServer::CERT_OK_BY_INTERMEDIATE, server_config));
// If the client doesn't advertise any trust anchor IDs on the connection,
// then the server should provide a full chain (with the intermediate).
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(1u, ssl_info.unverified_cert->intermediate_buffers().size());
// If the client advertises trust anchor IDs that don't correspond to the
// server's intermediate, then the server should provide a full chain (with
// the intermediate).
client_config.trust_anchor_ids = {0x03, 0x01, 0x01, 0x01, 0x02, 0x03, 0x03};
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->GetServerTrustAnchorIDsForRetry().empty());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(1u, ssl_info.unverified_cert->intermediate_buffers().size());
// If the client advertises the trust anchor ID corresponding to the server's
// intermediate, then the server should omit the intermediate from the
// connection.
client_config.trust_anchor_ids = {0x03, 0x01, 0x02, 0x03};
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->GetServerTrustAnchorIDsForRetry().empty());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(0u, ssl_info.unverified_cert->intermediate_buffers().size());
// If the client advertises multiple trust anchor IDs including the one
// corresponding to the server's intermediate, then the server should omit the
// intermediate from the connection.
client_config.trust_anchor_ids = {0x02, 0x01, 0x01, 0x03, 0x01, 0x02, 0x03};
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->GetServerTrustAnchorIDsForRetry().empty());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(0u, ssl_info.unverified_cert->intermediate_buffers().size());
// If the client advertises the trust anchor ID corresponding to the server's
// intermediate but gets an error, it should be able to access the trust
// anchor IDs that the server advertised in the handshake.
cert_verifier_->set_default_result(ERR_CERT_INVALID);
client_config.trust_anchor_ids = {0x03, 0x01, 0x02, 0x03};
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_CERT_INVALID));
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(0u, ssl_info.unverified_cert->intermediate_buffers().size());
EXPECT_EQ(sock_->GetServerTrustAnchorIDsForRetry(),
std::vector<std::vector<uint8_t>>({{0x01, 0x02, 0x03}}));
}
// Tests the method that parses the server's Trust Anchor IDs that it can
// provide in the handshake.
TEST_F(SSLClientSocketTest, ParseServerTrustAnchorIDs) {
struct TestCase {
const std::vector<uint8_t> server_trust_anchor_ids;
const std::vector<std::vector<uint8_t>> expected_parsed_trust_anchor_ids;
};
TestCase test_cases[] = {
// Two Trust Anchor IDs, correctly formed
{{0x03, 0x01, 0x02, 0x03, 0x02, 0x01, 0x01},
{{0x01, 0x02, 0x03}, {0x01, 0x01}}},
// Empty
{{}, {}},
// Malformed
{{0x02, 0x1}, {}},
{{0x00, 0x01, 0x02, 0x03}, {}},
{{0x00}, {}},
};
for (const auto& test : test_cases) {
base::SpanReader<const uint8_t> reader(test.server_trust_anchor_ids);
auto result = SSLClientSocketImpl::ParseServerTrustAnchorIDs(&reader);
EXPECT_EQ(result, test.expected_parsed_trust_anchor_ids);
}
}
// Tests that OCSP stapling is requested, as per Certificate Transparency (RFC
// 6962).
TEST_P(SSLClientSocketVersionTest, ConnectSignedCertTimestampsEnablesOCSP) {
// The test server currently only knows how to generate OCSP responses
// for a freshly minted certificate.
EmbeddedTestServer::ServerCertificateConfig cert_config;
cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
{{bssl::OCSPRevocationStatus::GOOD,
EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
ASSERT_TRUE(StartEmbeddedTestServer(cert_config, GetServerConfig()));
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_EQ(cert_verifier_->GetVerifyParams().size(), 1u);
const auto& params = cert_verifier_->GetVerifyParams().front();
EXPECT_TRUE(params.certificate()->EqualsIncludingChain(
embedded_test_server()->GetCertificate().get()));
EXPECT_EQ(params.hostname(), embedded_test_server()->host_port_pair().host());
EXPECT_FALSE(params.ocsp_response().empty());
}
// Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
TEST_P(SSLClientSocketVersionTest, ReuseStates) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
// The socket was just connected. It should be idle because it is speaking
// HTTP. Although the transport has been used for the handshake, WasEverUsed()
// returns false.
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(sock_->IsConnectedAndIdle());
EXPECT_FALSE(sock_->WasEverUsed());
static constexpr std::string_view request_text = "GET / HTTP/1.0\r\n\r\n";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
TestCompletionCallback callback;
rv = callback.GetResult(sock_->Write(request_buffer.get(),
request_text.size(), callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_EQ(static_cast<int>(request_text.size()), rv);
// The socket has now been used.
EXPECT_TRUE(sock_->WasEverUsed());
// TODO(davidben): Read one byte to ensure the test server has responded and
// then assert IsConnectedAndIdle is false. This currently doesn't work
// because SSLClientSocketImpl doesn't check the implementation's internal
// buffer. Call SSL_pending.
}
// Tests that |is_fatal_cert_error| does not get set for a certificate error,
// on a non-HSTS host.
TEST_P(SSLClientSocketVersionTest, IsFatalErrorNotSetOnNonFatalError) {
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_CHAIN_WRONG_ROOT,
GetServerConfig()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_FALSE(ssl_info.is_fatal_cert_error);
}
// Tests that |is_fatal_cert_error| gets set for a certificate error on an
// HSTS host.
TEST_P(SSLClientSocketVersionTest, IsFatalErrorSetOnFatalError) {
cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
ASSERT_TRUE(StartEmbeddedTestServer(EmbeddedTestServer::CERT_CHAIN_WRONG_ROOT,
GetServerConfig()));
int rv;
const base::Time expiry = base::Time::Now() + base::Seconds(1000);
transport_security_state_->AddHSTS(host_port_pair().host(), expiry, true);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_TRUE(ssl_info.is_fatal_cert_error);
}
// Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
// been flushed completely out of SSLClientSocket's internal buffers. This is a
// regression test for https://crbug.com/466147.
TEST_P(SSLClientSocketVersionTest, ReusableAfterWrite) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
ASSERT_THAT(callback.GetResult(transport->Connect(callback.callback())),
IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
ASSERT_THAT(callback.GetResult(sock->Connect(callback.callback())), IsOk());
// Block any application data from reaching the network.
raw_transport->BlockWrite();
// Write a partial HTTP request.
static constexpr std::string_view request_text = "GET / HTTP/1.0";
auto request_buffer =
base::MakeRefCounted<VectorIOBuffer>(base::as_byte_span(request_text));
// Although transport writes are blocked, SSLClientSocketImpl completes the
// outer Write operation.
EXPECT_EQ(static_cast<int>(request_text.size()),
callback.GetResult(sock->Write(
request_buffer.get(), request_text.size(), callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS)));
// The Write operation is complete, so the socket should be treated as
// reusable, in case the server returns an HTTP response before completely
// consuming the request body. In this case, we assume the server will
// properly drain the request body before trying to read the next request.
EXPECT_TRUE(sock->IsConnectedAndIdle());
}
// Tests that basic session resumption works.
TEST_P(SSLClientSocketVersionTest, SessionResumption) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
// First, perform a full handshake.
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
// The next connection should resume.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
sock_.reset();
// Using a different HostPortPair uses a different session cache key.
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
TestCompletionCallback callback;
ASSERT_THAT(callback.GetResult(transport->Connect(callback.callback())),
IsOk());
std::unique_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
std::move(transport), HostPortPair("example.com", 443), ssl_config);
ASSERT_THAT(callback.GetResult(sock->Connect(callback.callback())), IsOk());
ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
sock.reset();
ssl_client_session_cache_->Flush();
// After clearing the session cache, the next handshake doesn't resume.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
// Pick up the ticket again and confirm resumption works.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
sock_.reset();
// Updating the context-wide configuration should flush the session cache.
SSLContextConfig config;
config.disabled_cipher_suites = {1234};
ssl_config_service_->UpdateSSLConfigAndNotify(config);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
}
namespace {
// FakePeerAddressSocket wraps a |StreamSocket|, forwarding all calls except
// that it provides a given answer for |GetPeerAddress|.
class FakePeerAddressSocket : public WrappedStreamSocket {
public:
FakePeerAddressSocket(std::unique_ptr<StreamSocket> socket,
const IPEndPoint& address)
: WrappedStreamSocket(std::move(socket)), address_(address) {}
~FakePeerAddressSocket() override = default;
int GetPeerAddress(IPEndPoint* address) const override {
*address = address_;
return OK;
}
private:
const IPEndPoint address_;
};
} // namespace
TEST_F(SSLClientSocketTest, SessionResumption_RSA) {
for (bool use_rsa : {false, true}) {
SCOPED_TRACE(use_rsa);
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing =
use_rsa ? kRSACipher : kModernTLS12Cipher;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig ssl_config;
ssl_client_session_cache_->Flush();
for (int i = 0; i < 3; i++) {
SCOPED_TRACE(i);
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
TestCompletionCallback callback;
ASSERT_THAT(callback.GetResult(transport->Connect(callback.callback())),
IsOk());
// The third handshake sees a different destination IP address.
IPEndPoint fake_peer_address(IPAddress(1, 1, 1, i == 2 ? 2 : 1), 443);
auto socket = std::make_unique<FakePeerAddressSocket>(
std::move(transport), fake_peer_address);
std::unique_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
std::move(socket), HostPortPair("example.com", 443), ssl_config);
ASSERT_THAT(callback.GetResult(sock->Connect(callback.callback())),
IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
sock.reset();
switch (i) {
case 0:
// Initial handshake should be a full handshake.
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
break;
case 1:
// Second handshake should resume.
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
break;
case 2:
// Third handshake gets a different IP address and, if the
// session used RSA key exchange, it should not resume.
EXPECT_EQ(
use_rsa ? SSLInfo::HANDSHAKE_FULL : SSLInfo::HANDSHAKE_RESUME,
ssl_info.handshake_type);
break;
default:
NOTREACHED();
}
}
}
}
// Tests that ALPN works with session resumption.
TEST_F(SSLClientSocketTest, SessionResumptionAlpn) {
SSLServerConfig server_config;
server_config.alpn_protos = {NextProto::kProtoHTTP2, NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// First, perform a full handshake.
SSLConfig ssl_config;
ssl_config.alpn_protos.push_back(NextProto::kProtoHTTP2);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_EQ(NextProto::kProtoHTTP2, sock_->GetNegotiatedProtocol());
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
// The next connection should resume; ALPN should be renegotiated.
ssl_config.alpn_protos.clear();
ssl_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_EQ(NextProto::kProtoHTTP11, sock_->GetNegotiatedProtocol());
}
// Tests that the session cache is not sharded by NetworkAnonymizationKey if the
// feature is disabled.
TEST_P(SSLClientSocketVersionTest,
SessionResumptionNetworkIsolationKeyDisabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
features::kPartitionConnectionsByNetworkIsolationKey);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
// First, perform a full handshake.
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up. Do this for
// every connection to avoid problems with TLS 1.3 single-use tickets.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
// The next connection should resume.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// Using a different NetworkAnonymizationKey shares session cache key because
// sharding is disabled.
const SchemefulSite kSiteA(GURL("https://a.test"));
ssl_config.network_anonymization_key =
NetworkAnonymizationKey::CreateSameSite(kSiteA);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
const SchemefulSite kSiteB(GURL("https://a.test"));
ssl_config.network_anonymization_key =
NetworkAnonymizationKey::CreateSameSite(kSiteB);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
}
// Tests that the session cache is sharded by NetworkAnonymizationKey if the
// feature is enabled.
TEST_P(SSLClientSocketVersionTest,
SessionResumptionNetworkIsolationKeyEnabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
features::kPartitionConnectionsByNetworkIsolationKey);
const SchemefulSite kSiteA(GURL("https://a.test"));
const SchemefulSite kSiteB(GURL("https://b.test"));
const auto kNetworkAnonymizationKeyA =
NetworkAnonymizationKey::CreateSameSite(kSiteA);
const auto kNetworkAnonymizationKeyB =
NetworkAnonymizationKey::CreateSameSite(kSiteB);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
// First, perform a full handshake.
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up. Do this for
// every connection to avoid problems with TLS 1.3 single-use tickets.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
// The next connection should resume.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// Using a different NetworkAnonymizationKey uses a different session cache
// key.
ssl_config.network_anonymization_key = kNetworkAnonymizationKeyA;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// We, however, can resume under that newly-established session.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// Repeat with another non-null key.
ssl_config.network_anonymization_key = kNetworkAnonymizationKeyB;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// b.test does not evict a.test's session.
ssl_config.network_anonymization_key = kNetworkAnonymizationKeyA;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
}
// Tests that the session cache is sharded by session usage and proxy chain.
TEST_P(SSLClientSocketVersionTest,
SessionResumptionDifferentSessionUsageAndProxyChain) {
const SchemefulSite kSiteA(GURL("https://a.test"));
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
// First, perform a full handshake.
SSLConfig ssl_config;
ssl_config.session_usage = SessionUsage::kDestination;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up. Do this for
// every connection to avoid problems with TLS 1.3 single-use tickets.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
// The next connection should resume.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// Using a different SessionUsage uses a different session cache
// key.
ssl_config.session_usage = SessionUsage::kProxy;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// We, however, can resume under that newly-established session.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
// Repeat with a different proxy chain
ssl_config.proxy_chain = ProxyChain::FromSchemeHostAndPort(
ProxyServer::SCHEME_HTTPS, "proxy", 8080);
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
sock_.reset();
}
// Tests that connections with certificate errors do not add entries to the
// session cache.
TEST_P(SSLClientSocketVersionTest, CertificateErrorNoResume) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsError(ERR_CERT_COMMON_NAME_INVALID));
cert_verifier_->set_default_result(OK);
// The next connection should perform a full handshake.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
ASSERT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
}
TEST_F(SSLClientSocketTest, RequireECDHE) {
// Run test server without ECDHE.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kRSACipher;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig config;
config.require_ecdhe = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
TEST_F(SSLClientSocketTest, 3DES) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = k3DESCipher;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// 3DES is always disabled.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
TEST_F(SSLClientSocketTest, SHA1) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
// Disable RSA key exchange, to ensure the server does not pick a non-signing
// cipher.
server_config.require_ecdhe = true;
server_config.signature_algorithm_for_testing = SSL_SIGN_RSA_PKCS1_SHA1;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// SHA-1 server signatures are always disabled.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
// False Start requires ALPN, ECDHE, and an AEAD.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_config, client_config, true));
}
// Test that False Start is disabled without ALPN.
TEST_F(SSLClientSocketFalseStartTest, NoAlpn) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
SSLConfig client_config;
client_config.alpn_protos.clear();
ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_config, client_config, false));
}
// Test that False Start is disabled with plain RSA ciphers.
TEST_F(SSLClientSocketFalseStartTest, RSA) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kRSACipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_config, client_config, false));
}
// Test that False Start is disabled without an AEAD.
TEST_F(SSLClientSocketFalseStartTest, NoAEAD) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kCBCCipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_config, client_config, false));
}
// Test that sessions are resumable after receiving the server Finished message.
TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
// Start a server.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
// Let a full handshake complete with False Start.
ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_config, client_config, true));
// Make a second connection.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// It should resume the session.
SSLInfo ssl_info;
EXPECT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Test that the client completes the handshake in the background and installs
// new sessions, even if the socket isn't used. This also avoids a theoretical
// deadlock if NewSessionTicket is sufficiently large that neither it nor the
// client's HTTP/1.1 POST fit in transport windows.
TEST_F(SSLClientSocketFalseStartTest, CompleteHandshakeWithoutRequest) {
// Start a server.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
// Start a handshake up to the server Finished message.
TestCompletionCallback callback;
FakeBlockingStreamSocket* raw_transport = nullptr;
std::unique_ptr<SSLClientSocket> sock;
ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
client_config, &callback, &raw_transport, &sock));
// Wait for the server Finished to arrive, release it, and allow
// SSLClientSocket to process it. This should install a session. It make take
// a few iterations to complete if the server writes in small chunks
while (ssl_client_session_cache_->size() == 0) {
raw_transport->WaitForReadResult();
raw_transport->UnblockReadResult();
base::RunLoop().RunUntilIdle();
raw_transport->BlockReadResult();
}
// Drop the old socket. This is needed because the Python test server can't
// service two sockets in parallel.
sock.reset();
// Make a second connection.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// It should resume the session.
SSLInfo ssl_info;
EXPECT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Test that False Started sessions are not resumable before receiving the
// server Finished message.
TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinished) {
// Start a server.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
// Start a handshake up to the server Finished message.
TestCompletionCallback callback;
FakeBlockingStreamSocket* raw_transport1 = nullptr;
std::unique_ptr<SSLClientSocket> sock1;
ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
client_config, &callback, &raw_transport1, &sock1));
// Although raw_transport1 has the server Finished blocked, the handshake
// still completes.
EXPECT_THAT(callback.WaitForResult(), IsOk());
// Continue to block the client (|sock1|) from processing the Finished
// message, but allow it to arrive on the socket. This ensures that, from the
// server's point of view, it has completed the handshake and added the
// session to its session cache.
//
// The actual read on |sock1| will not complete until the Finished message is
// processed; however, pump the underlying transport so that it is read from
// the socket. NOTE: This may flakily pass if the server's final flight
// doesn't come in one Read.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int rv = sock1->Read(buf.get(), 4096, callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport1->WaitForReadResult();
// Drop the old socket. This is needed because the Python test server can't
// service two sockets in parallel.
sock1.reset();
// Start a second connection.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// No session resumption because the first connection never received a server
// Finished message.
SSLInfo ssl_info;
EXPECT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
}
// Test that False Started sessions are not resumable if the server Finished
// message was bad.
TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBadFinished) {
// Start a server.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = kModernTLS12Cipher;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
// Start a handshake up to the server Finished message.
TestCompletionCallback callback;
FakeBlockingStreamSocket* raw_transport1 = nullptr;
std::unique_ptr<SSLClientSocket> sock1;
ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
client_config, &callback, &raw_transport1, &sock1));
// Although raw_transport1 has the server Finished blocked, the handshake
// still completes.
EXPECT_THAT(callback.WaitForResult(), IsOk());
// Continue to block the client (|sock1|) from processing the Finished
// message, but allow it to arrive on the socket. This ensures that, from the
// server's point of view, it has completed the handshake and added the
// session to its session cache.
//
// The actual read on |sock1| will not complete until the Finished message is
// processed; however, pump the underlying transport so that it is read from
// the socket.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int rv = sock1->Read(buf.get(), 4096, callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport1->WaitForReadResult();
// The server's second leg, or part of it, is now received but not yet sent to
// |sock1|. Before doing so, break the server's second leg.
int bytes_read = raw_transport1->pending_read_result();
ASSERT_LT(0, bytes_read);
raw_transport1->pending_read_buf()->span()[bytes_read - 1]++;
// Unblock the Finished message. |sock1->Read| should now fail.
raw_transport1->UnblockReadResult();
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_SSL_PROTOCOL_ERROR));
// Drop the old socket. This is needed because the Python test server can't
// service two sockets in parallel.
sock1.reset();
// Start a second connection.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// No session resumption because the first connection never received a server
// Finished message.
SSLInfo ssl_info;
EXPECT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
}
// Server preference should win in ALPN.
TEST_F(SSLClientSocketTest, Alpn) {
SSLServerConfig server_config;
server_config.alpn_protos = {NextProto::kProtoHTTP2, NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
client_config.alpn_protos.push_back(NextProto::kProtoHTTP11);
client_config.alpn_protos.push_back(NextProto::kProtoHTTP2);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(NextProto::kProtoHTTP2, sock_->GetNegotiatedProtocol());
}
// If the server supports ALPN but the client does not, then ALPN is not used.
TEST_F(SSLClientSocketTest, AlpnClientDisabled) {
SSLServerConfig server_config;
server_config.alpn_protos = {NextProto::kProtoHTTP2};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(NextProto::kProtoUnknown, sock_->GetNegotiatedProtocol());
}
// Client certificates are disabled on iOS.
#if BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
// Connect to a server requesting client authentication, do not send
// any client certificates. It should refuse the connection.
TEST_P(SSLClientSocketVersionTest, NoCert) {
SSLServerConfig server_config = GetServerConfig();
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server requesting client authentication, and send it
// an empty certificate.
TEST_P(SSLClientSocketVersionTest, SendEmptyCert) {
SSLServerConfig server_config = GetServerConfig();
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_FALSE(ssl_info.client_cert_sent);
}
// Connect to a server requesting client authentication and send a certificate.
TEST_P(SSLClientSocketVersionTest, SendGoodCert) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> client_cert =
ImportCertFromFile(certs_dir, "client_1.pem");
ASSERT_TRUE(client_cert);
// Configure the server to only accept |client_cert|.
MockClientCertVerifier verifier;
verifier.set_default_result(ERR_CERT_INVALID);
verifier.AddResultForCert(client_cert.get(), OK);
SSLServerConfig server_config = GetServerConfig();
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
server_config.client_cert_verifier = &verifier;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
context_->SetClientCertificate(
host_port_pair(), client_cert,
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_TRUE(ssl_info.client_cert_sent);
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
// Shut down the test server before |verifier| goes out of scope.
ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
}
// When client certificate preferences change, the session cache should be
// cleared so the client certificate preferences are applied.
TEST_F(SSLClientSocketTest, ClearSessionCacheOnClientCertChange) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Connecting without a client certificate will fail with
// ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
// Configure a client certificate.
base::FilePath certs_dir = GetTestCertsDirectory();
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
// Now the connection succeeds.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_TRUE(ssl_info.client_cert_sent);
EXPECT_EQ(ssl_info.handshake_type, SSLInfo::HANDSHAKE_FULL);
// Make a second connection. This should resume the session from the previous
// connection.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_TRUE(ssl_info.client_cert_sent);
EXPECT_EQ(ssl_info.handshake_type, SSLInfo::HANDSHAKE_RESUME);
// Clear the client certificate preference.
context_->ClearClientCertificate(host_port_pair());
// Connections return to failing, rather than resume the previous session.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
// Establish a new session with the correct client certificate.
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_TRUE(ssl_info.client_cert_sent);
EXPECT_EQ(ssl_info.handshake_type, SSLInfo::HANDSHAKE_FULL);
// Switch to continuing without a client certificate.
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
// This also clears the session cache and the new preference is applied.
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsError(ERR_BAD_SSL_CLIENT_AUTH_CERT));
}
TEST_F(SSLClientSocketTest, ClearSessionCacheOnClientCertDatabaseChange) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
HostPortPair host_port_pair2("example.com", 42);
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})));
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair2})));
EXPECT_CALL(observer,
OnSSLConfigForServersChanged(base::flat_set<HostPortPair>(
{host_port_pair(), host_port_pair2})));
context_->AddObserver(&observer);
base::FilePath certs_dir = GetTestCertsDirectory();
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
context_->SetClientCertificate(
host_port_pair2, ImportCertFromFile(certs_dir, "client_2.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_2.key")));
EXPECT_EQ(2U, context_->GetClientCertificateCachedServersForTesting().size());
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(1U, context_->ssl_client_session_cache()->size());
CertDatabase::GetInstance()->NotifyObserversClientCertStoreChanged();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0U, context_->GetClientCertificateCachedServersForTesting().size());
EXPECT_EQ(0U, context_->ssl_client_session_cache()->size());
context_->RemoveObserver(&observer);
}
TEST_F(SSLClientSocketTest, DontClearEmptyClientCertCache) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
context_->AddObserver(&observer);
// No cached client certs and no open session.
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
context_->ClearClientCertificateIfNeeded(host_port_pair(), certificate1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_FALSE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest, DontClearMatchingClientCertificates) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})));
context_->AddObserver(&observer);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> private_key1 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
context_->SetClientCertificate(host_port_pair(), certificate1, private_key1);
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
context_->ClearClientCertificateIfNeeded(host_port_pair(), certificate1);
base::RunLoop().RunUntilIdle();
// Cached certificate and session should not have been cleared since the
// certificates were identical.
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().contains(
host_port_pair()));
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_FALSE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest, ClearMismatchingClientCertificates) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})))
.Times(2);
context_->AddObserver(&observer);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> private_key1 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
context_->SetClientCertificate(host_port_pair(), certificate1, private_key1);
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
scoped_refptr<net::X509Certificate> certificate2 =
ImportCertFromFile(certs_dir, "client_2.pem");
context_->ClearClientCertificateIfNeeded(host_port_pair(), certificate2);
base::RunLoop().RunUntilIdle();
// Cached certificate and session should have been cleared since the
// certificates were different.
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_TRUE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest,
ClearMismatchingClientCertificatesWithNullParameter) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})))
.Times(2);
context_->AddObserver(&observer);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> private_key1 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
context_->SetClientCertificate(host_port_pair(), certificate1, private_key1);
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
context_->ClearClientCertificateIfNeeded(host_port_pair(), nullptr);
base::RunLoop().RunUntilIdle();
// Cached certificate and session should have been cleared since the
// certificates were different.
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_TRUE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest,
ClearMismatchingClientCertificatesWithNullCachedCert) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})))
.Times(2);
context_->AddObserver(&observer);
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate2 =
ImportCertFromFile(certs_dir, "client_2.pem");
context_->ClearClientCertificateIfNeeded(host_port_pair(), certificate2);
base::RunLoop().RunUntilIdle();
// Cached certificate and session should have been cleared since the
// certificates were different.
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_TRUE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest, DontClearClientCertificatesWithNullCerts) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})));
context_->AddObserver(&observer);
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
context_->ClearClientCertificateIfNeeded(host_port_pair(), nullptr);
base::RunLoop().RunUntilIdle();
// Cached certificate and session should not have been cleared since the
// certificates were identical.
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().contains(
host_port_pair()));
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
context_->RemoveObserver(&observer);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(GetStringValueFromParams(entries[0], "host"),
host_port_pair().ToString());
EXPECT_FALSE(GetBooleanValueFromParams(entries[0], "is_cleared"));
}
TEST_F(SSLClientSocketTest, ClearMatchingCertDontClearEmptyClientCertCache) {
SSLServerConfig server_config;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// No cached client certs and no open session.
ASSERT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
ASSERT_EQ(context_->ssl_client_session_cache()->size(), 0U);
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
context_->ClearMatchingClientCertificate(certificate1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(context_->GetClientCertificateCachedServersForTesting().empty());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_MATCHING_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
const auto& log_entry = entries[0];
ASSERT_FALSE(log_entry.params.empty());
const base::Value::List* hosts_values =
log_entry.params.FindListByDottedPath("hosts");
ASSERT_TRUE(hosts_values);
ASSERT_TRUE(hosts_values->empty());
const base::Value::List* certificates_values =
log_entry.params.FindListByDottedPath("certificates");
ASSERT_TRUE(certificates_values);
EXPECT_FALSE(certificates_values->empty());
}
TEST_F(SSLClientSocketTest, ClearMatchingCertSingleNotMatching) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Add a client cert decision to the cache.
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> private_key1 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
context_->SetClientCertificate(host_port_pair(), certificate1, private_key1);
ASSERT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
// Create a connection to `host_port_pair()`.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
scoped_refptr<net::X509Certificate> certificate2 =
ImportCertFromFile(certs_dir, "client_2.pem");
context_->ClearMatchingClientCertificate(certificate2);
base::RunLoop().RunUntilIdle();
// Verify that calling with an unused certificate should not invalidate the
// cache, but will still log an event with no hosts.
EXPECT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 1U);
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_MATCHING_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
const auto& log_entry = entries[0];
ASSERT_FALSE(log_entry.params.empty());
const base::Value::List* hosts_values =
log_entry.params.FindListByDottedPath("hosts");
ASSERT_TRUE(hosts_values);
ASSERT_TRUE(hosts_values->empty());
const base::Value::List* certificates_values =
log_entry.params.FindListByDottedPath("certificates");
ASSERT_TRUE(certificates_values);
EXPECT_FALSE(certificates_values->empty());
}
TEST_F(SSLClientSocketTest, ClearMatchingCertSingleMatching) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Add a couple of client cert decision to the cache.
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> certificate1 =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> private_key1 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
context_->SetClientCertificate(host_port_pair(), certificate1, private_key1);
HostPortPair host_port_pair2("example.com", 42);
scoped_refptr<net::X509Certificate> certificate2 =
ImportCertFromFile(certs_dir, "client_2.pem");
scoped_refptr<net::SSLPrivateKey> private_key2 =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_2.key"));
context_->SetClientCertificate(host_port_pair2, certificate2, private_key2);
ASSERT_EQ(context_->GetClientCertificateCachedServersForTesting().size(), 2U);
// Create a connection to `host_port_pair()`.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 1U);
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})));
context_->AddObserver(&observer);
context_->ClearMatchingClientCertificate(certificate1);
base::RunLoop().RunUntilIdle();
context_->RemoveObserver(&observer);
auto cached_servers_with_decision =
context_->GetClientCertificateCachedServersForTesting();
EXPECT_EQ(cached_servers_with_decision.size(), 1U);
EXPECT_TRUE(cached_servers_with_decision.contains(host_port_pair2));
EXPECT_EQ(context_->ssl_client_session_cache()->size(), 0U);
auto entries = log_observer_.GetEntriesWithType(
NetLogEventType::CLEAR_MATCHING_CACHED_CLIENT_CERT);
ASSERT_EQ(1u, entries.size());
const auto& log_entry = entries[0];
ASSERT_FALSE(log_entry.params.empty());
const base::Value::List* hosts_values =
log_entry.params.FindListByDottedPath("hosts");
ASSERT_TRUE(hosts_values);
ASSERT_EQ(hosts_values->size(), 1U);
EXPECT_EQ(hosts_values->front().GetString(), host_port_pair().ToString());
const base::Value::List* certificates_values =
log_entry.params.FindListByDottedPath("certificates");
ASSERT_TRUE(certificates_values);
EXPECT_FALSE(certificates_values->empty());
}
TEST_F(SSLClientSocketTest, DontClearSessionCacheOnServerCertDatabaseChange) {
SSLServerConfig server_config;
// TLS 1.3 reports client certificate errors after the handshake, so test at
// TLS 1.2 for simplicity.
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
HostPortPair host_port_pair2("example.com", 42);
testing::StrictMock<MockSSLClientContextObserver> observer;
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair()})));
EXPECT_CALL(observer, OnSSLConfigForServersChanged(
base::flat_set<HostPortPair>({host_port_pair2})));
EXPECT_CALL(observer,
OnSSLConfigChanged(
SSLClientContext::SSLConfigChangeType::kCertDatabaseChanged));
context_->AddObserver(&observer);
base::FilePath certs_dir = GetTestCertsDirectory();
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
context_->SetClientCertificate(
host_port_pair2, ImportCertFromFile(certs_dir, "client_2.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_2.key")));
EXPECT_EQ(2U, context_->GetClientCertificateCachedServersForTesting().size());
// Connect to `host_port_pair()` using the client cert.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_EQ(1U, context_->ssl_client_session_cache()->size());
CertDatabase::GetInstance()->NotifyObserversTrustStoreChanged();
base::RunLoop().RunUntilIdle();
// The `OnSSLConfigChanged` observer call should be verified by the
// mock observer, but the client auth and client session cache should be
// untouched.
EXPECT_EQ(2U, context_->GetClientCertificateCachedServersForTesting().size());
EXPECT_EQ(1U, context_->ssl_client_session_cache()->size());
context_->RemoveObserver(&observer);
}
// Test client certificate signature algorithm selection.
TEST_F(SSLClientSocketTest, ClientCertSignatureAlgorithm) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> client_cert =
ImportCertFromFile(certs_dir, "client_1.pem");
scoped_refptr<net::SSLPrivateKey> client_key =
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"));
const struct {
const char* name;
uint16_t version;
std::vector<uint16_t> server_prefs;
std::vector<uint16_t> client_prefs;
Error error = OK;
uint16_t expected_signature_algorithm = 0;
} kTests[] = {
{
.name = "TLS 1.2 client preference",
.version = SSL_PROTOCOL_VERSION_TLS1_2,
.server_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA384,
SSL_SIGN_RSA_PSS_RSAE_SHA256},
.client_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA256,
SSL_SIGN_RSA_PSS_RSAE_SHA384},
// The client's preference should be used.
.expected_signature_algorithm = SSL_SIGN_RSA_PSS_RSAE_SHA256,
},
{
.name = "TLS 1.3 client preference",
.version = SSL_PROTOCOL_VERSION_TLS1_3,
.server_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA384,
SSL_SIGN_RSA_PSS_RSAE_SHA256},
.client_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA256,
SSL_SIGN_RSA_PSS_RSAE_SHA384},
// The client's preference should be used.
.expected_signature_algorithm = SSL_SIGN_RSA_PSS_RSAE_SHA256,
},
{
.name = "TLS 1.2 no common algorithms",
.version = SSL_PROTOCOL_VERSION_TLS1_2,
.server_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA384},
.client_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA256},
.error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS,
},
{
.name = "TLS 1.3 no common algorithms",
.version = SSL_PROTOCOL_VERSION_TLS1_3,
.server_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA384},
.client_prefs = {SSL_SIGN_RSA_PSS_RSAE_SHA256},
.error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS,
},
{
.name = "TLS 1.2 PKCS#1",
.version = SSL_PROTOCOL_VERSION_TLS1_2,
.server_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
.client_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
.expected_signature_algorithm = SSL_SIGN_RSA_PKCS1_SHA256,
},
{
.name = "TLS 1.2 no PKCS#1",
.version = SSL_PROTOCOL_VERSION_TLS1_3,
.server_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
.client_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
// The rsa_pkcs1_sha256 codepoint may not be used in TLS 1.3, so the
// TLS library should exclude it.
.error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS,
},
// Test rsa_pkcs1_sha256_legacy. The value is omitted from `client_prefs`
// because SSLPrivateKey implementations are not expected to specify
// `SSL_SIGN_RSA_PKCS1_SHA256_LEGACY`. Instead, SSLClientSocket
// automatically applies support when `SSL_SIGN_RSA_PKCS1_SHA256` is
// available.
{
.name = "TLS 1.2 no legacy PKCS#1",
.version = SSL_PROTOCOL_VERSION_TLS1_2,
.server_prefs = {SSL_SIGN_RSA_PKCS1_SHA256_LEGACY},
.client_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
// The rsa_pkcs1_sha256_legacy codepoint is specifically for
// restoring PKCS#1 to TLS 1.3, so it should not be accepted.
.error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS,
},
{
.name = "TLS 1.3 legacy PKCS#1",
.version = SSL_PROTOCOL_VERSION_TLS1_3,
.server_prefs = {SSL_SIGN_RSA_PKCS1_SHA256_LEGACY},
.client_prefs = {SSL_SIGN_RSA_PKCS1_SHA256},
// The rsa_pkcs1_sha256_legacy codepoint may be used in TLS 1.3.
.expected_signature_algorithm = SSL_SIGN_RSA_PKCS1_SHA256_LEGACY,
},
{
.name = "TLS 1.3 legacy PKCS#1 not preferred",
.version = SSL_PROTOCOL_VERSION_TLS1_3,
.server_prefs = {SSL_SIGN_RSA_PKCS1_SHA256_LEGACY,
SSL_SIGN_RSA_PSS_RSAE_SHA256},
.client_prefs = {SSL_SIGN_RSA_PKCS1_SHA256,
SSL_SIGN_RSA_PSS_RSAE_SHA256},
// The legacy codepoint is only used when no other options are
// available. The key supports PSS, so we will use PSS instead.
.expected_signature_algorithm = SSL_SIGN_RSA_PSS_RSAE_SHA256,
},
};
for (const auto& test : kTests) {
SCOPED_TRACE(test.name);
SSLServerConfig server_config;
server_config.version_min = test.version;
server_config.version_max = test.version;
server_config.client_cert_type = SSLServerConfig::REQUIRE_CLIENT_CERT;
server_config.client_cert_signature_algorithms = test.server_prefs;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Connect with the client certificate.
context_->SetClientCertificate(
host_port_pair(), client_cert,
WrapSSLPrivateKeyWithPreferences(client_key, test.client_prefs));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
if (test.error != OK) {
EXPECT_THAT(rv, IsError(test.error));
continue;
}
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
// Capture the SSLInfo from the server to get the client's chosen signature
// algorithm.
EXPECT_THAT(MakeHTTPRequest(sock_.get(), "/ssl-info"), IsOk());
std::optional<SSLInfo> server_ssl_info = LastSSLInfoFromServer();
ASSERT_TRUE(server_ssl_info);
EXPECT_EQ(server_ssl_info->peer_signature_algorithm,
test.expected_signature_algorithm);
}
}
#endif // BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
HashValueVector MakeHashValueVector(uint8_t value) {
HashValueVector out;
HashValue hash(HASH_VALUE_SHA256);
std::ranges::fill(hash.span(), value);
out.push_back(hash);
return out;
}
// Test that |ssl_info.pkp_bypassed| is set when a local trust anchor causes
// pinning to be bypassed.
TEST_P(SSLClientSocketVersionTest, PKPBypassedSet) {
base::test::ScopedFeatureList scoped_feature_list_;
scoped_feature_list_.InitAndEnableFeature(
net::features::kStaticKeyPinningEnforcement);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// The certificate needs to be trusted, but chain to a local root with
// different public key hashes than specified in the pin.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = false;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kBadHashValueVectorInput);
cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK);
transport_security_state_->EnableStaticPinsForTesting();
transport_security_state_->SetPinningListAlwaysTimelyForTesting(true);
ScopedTransportSecurityStateSource scoped_security_state_source;
SSLConfig ssl_config;
int rv;
HostPortPair new_host_port_pair("example.test", host_port_pair().port());
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(ssl_config,
new_host_port_pair, &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(ssl_info.pkp_bypassed);
EXPECT_FALSE(ssl_info.cert_status & CERT_STATUS_PINNED_KEY_MISSING);
}
TEST_P(SSLClientSocketVersionTest, PKPEnforced) {
base::test::ScopedFeatureList scoped_feature_list_;
scoped_feature_list_.InitAndEnableFeature(
net::features::kStaticKeyPinningEnforcement);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// Certificate is trusted, but chains to a public root that doesn't match the
// pin hashes.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = true;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kBadHashValueVectorInput);
cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK);
transport_security_state_->EnableStaticPinsForTesting();
transport_security_state_->SetPinningListAlwaysTimelyForTesting(true);
ScopedTransportSecurityStateSource scoped_security_state_source;
SSLConfig ssl_config;
int rv;
HostPortPair new_host_port_pair("example.test", host_port_pair().port());
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(ssl_config,
new_host_port_pair, &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_THAT(rv, IsError(ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN));
EXPECT_TRUE(ssl_info.cert_status & CERT_STATUS_PINNED_KEY_MISSING);
EXPECT_FALSE(sock_->IsConnected());
EXPECT_FALSE(ssl_info.pkp_bypassed);
}
namespace {
// TLS_RSA_WITH_AES_128_GCM_SHA256's key exchange involves encrypting to the
// server long-term key.
const uint16_t kEncryptingCipher = kRSACipher;
// TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256's key exchange involves a signature by
// the server long-term key.
const uint16_t kSigningCipher = kModernTLS12Cipher;
} // namespace
struct KeyUsageTest {
EmbeddedTestServer::ServerCertificate server_cert;
uint16_t cipher_suite;
bool match;
};
class SSLClientSocketKeyUsageTest
: public SSLClientSocketTest,
public ::testing::WithParamInterface<
std::tuple<KeyUsageTest, bool /*known_root*/>> {};
const KeyUsageTest kKeyUsageTests[] = {
// keyUsage matches cipher suite.
{EmbeddedTestServer::CERT_KEY_USAGE_RSA_DIGITAL_SIGNATURE, kSigningCipher,
true},
{EmbeddedTestServer::CERT_KEY_USAGE_RSA_ENCIPHERMENT, kEncryptingCipher,
true},
// keyUsage does not match cipher suite.
{EmbeddedTestServer::CERT_KEY_USAGE_RSA_ENCIPHERMENT, kSigningCipher,
false},
{EmbeddedTestServer::CERT_KEY_USAGE_RSA_DIGITAL_SIGNATURE,
kEncryptingCipher, false},
};
TEST_P(SSLClientSocketKeyUsageTest, RSAKeyUsage) {
const auto& [test, known_root] = GetParam();
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.cipher_suite_for_testing = test.cipher_suite;
ASSERT_TRUE(StartEmbeddedTestServer(test.server_cert, server_config));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// Certificate is trusted.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = known_root;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kGoodHashValueVectorInput);
cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK);
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
if (test.match) {
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(sock_->IsConnected());
} else {
EXPECT_THAT(rv, IsError(ERR_SSL_KEY_USAGE_INCOMPATIBLE));
EXPECT_FALSE(sock_->IsConnected());
}
}
INSTANTIATE_TEST_SUITE_P(RSAKeyUsageInstantiation,
SSLClientSocketKeyUsageTest,
Combine(ValuesIn(kKeyUsageTests), Bool()));
// Test that when CT is required, setting ignore_certificate_errors
// ignores errors in CT.
TEST_P(SSLClientSocketVersionTest, IgnoreCertificateErrorsBypassesRequiredCT) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// Certificate is trusted and chains to a public root.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = true;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kGoodHashValueVectorInput);
verify_result.policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
verify_result.cert_status = CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED;
cert_verifier_->AddResultForCert(server_cert.get(), verify_result,
ERR_CERTIFICATE_TRANSPARENCY_REQUIRED);
SSLConfig ssl_config;
ssl_config.ignore_certificate_errors = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(ssl_info.cert_status &
CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED);
EXPECT_TRUE(sock_->IsConnected());
}
// When both PKP and CT are required for a host, and both fail, the more
// serious error is that the pin validation failed.
TEST_P(SSLClientSocketVersionTest, PKPMoreImportantThanCT) {
base::test::ScopedFeatureList scoped_feature_list_;
scoped_feature_list_.InitAndEnableFeature(
net::features::kStaticKeyPinningEnforcement);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// Certificate is trusted, but chains to a public root that doesn't match the
// pin hashes.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = true;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kBadHashValueVectorInput);
verify_result.policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
verify_result.cert_status = CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED;
cert_verifier_->AddResultForCert(server_cert.get(), verify_result,
ERR_CERTIFICATE_TRANSPARENCY_REQUIRED);
transport_security_state_->EnableStaticPinsForTesting();
transport_security_state_->SetPinningListAlwaysTimelyForTesting(true);
ScopedTransportSecurityStateSource scoped_security_state_source;
const char kCTHost[] = "hsts-hpkp-preloaded.test";
SSLConfig ssl_config;
int rv;
HostPortPair ct_host_port_pair(kCTHost, host_port_pair().port());
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(ssl_config,
ct_host_port_pair, &rv));
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_THAT(rv, IsError(ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN));
EXPECT_TRUE(ssl_info.cert_status & CERT_STATUS_PINNED_KEY_MISSING);
EXPECT_TRUE(ssl_info.cert_status &
CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED);
EXPECT_FALSE(sock_->IsConnected());
}
// Tests that the SCTAuditingDelegate is called to enqueue SCT reports.
TEST_P(SSLClientSocketVersionTest, SCTAuditingReportCollected) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, GetServerConfig()));
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
// Certificate is trusted and chains to a public root.
CertVerifyResult verify_result;
verify_result.is_issued_by_known_root = true;
verify_result.verified_cert = server_cert;
verify_result.public_key_hashes =
MakeHashValueVector(kGoodHashValueVectorInput);
verify_result.policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK);
MockSCTAuditingDelegate sct_auditing_delegate;
context_ = std::make_unique<SSLClientContext>(
ssl_config_service_.get(), cert_verifier_.get(),
transport_security_state_.get(), ssl_client_session_cache_.get(),
&sct_auditing_delegate);
EXPECT_CALL(sct_auditing_delegate, IsSCTAuditingEnabled())
.WillRepeatedly(Return(true));
EXPECT_CALL(sct_auditing_delegate,
MaybeEnqueueReport(host_port_pair(), server_cert.get(), _))
.Times(1);
SSLConfig ssl_config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_THAT(rv, 0);
EXPECT_TRUE(sock_->IsConnected());
}
// Test that handshake_failure alerts at the ServerHello are mapped to
// ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
TEST_F(SSLClientSocketTest, HandshakeFailureServerHello) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(40 /* AlertDescription.handshake_failure */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
// Test that handshake_failure alerts after the ServerHello but without a
// CertificateRequest are mapped to ERR_SSL_PROTOCOL_ERROR.
TEST_F(SSLClientSocketTest, HandshakeFailureNoClientCerts) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write its second flight.
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// Wait for the server's final flight.
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(40 /* AlertDescription.handshake_failure */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
}
// Test that handshake_failure alerts after the ServerHello map to
// ERR_BAD_SSL_CLIENT_AUTH_CERT if a client certificate was requested but not
// supplied. TLS does not have an alert for this case, so handshake_failure is
// common. See https://crbug.com/646567.
TEST_F(SSLClientSocketTest, LateHandshakeFailureMissingClientCerts) {
// Request a client certificate.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
// Send no client certificate.
context_->SetClientCertificate(host_port_pair(), nullptr, nullptr);
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write its second flight.
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// Wait for the server's final flight.
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(40 /* AlertDescription.handshake_failure */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_BAD_SSL_CLIENT_AUTH_CERT));
}
// Test that handshake_failure alerts after the ServerHello map to
// ERR_SSL_PROTOCOL_ERROR if received after sending a client certificate. It is
// assumed servers will send a more appropriate alert in this case.
TEST_F(SSLClientSocketTest, LateHandshakeFailureSendClientCerts) {
// Request a client certificate.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
// Send a client certificate.
base::FilePath certs_dir = GetTestCertsDirectory();
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write its second flight.
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// Wait for the server's final flight.
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(40 /* AlertDescription.handshake_failure */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
}
// Test that access_denied alerts are mapped to ERR_SSL_PROTOCOL_ERROR if
// received on a connection not requesting client certificates. This is an
// incorrect use of the alert but is common. See https://crbug.com/630883.
TEST_F(SSLClientSocketTest, AccessDeniedNoClientCerts) {
// Request a client certificate.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write its second flight.
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// Wait for the server's final flight.
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(49 /* AlertDescription.access_denied */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
}
// Test that access_denied alerts are mapped to ERR_BAD_SSL_CLIENT_AUTH_CERT if
// received on a connection requesting client certificates.
TEST_F(SSLClientSocketTest, AccessDeniedClientCerts) {
// Request a client certificate.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
server_config.client_cert_type = SSLServerConfig::OPTIONAL_CLIENT_CERT;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
TestCompletionCallback callback;
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
int rv = callback.GetResult(transport->Connect(callback.callback()));
ASSERT_THAT(rv, IsOk());
// Send a client certificate.
base::FilePath certs_dir = GetTestCertsDirectory();
context_->SetClientCertificate(
host_port_pair(), ImportCertFromFile(certs_dir, "client_1.pem"),
key_util::LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key")));
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(transport), host_port_pair(), SSLConfig()));
// Connect. Stop before the client processes ServerHello.
raw_transport->BlockReadResult();
rv = sock->Connect(callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
raw_transport->WaitForReadResult();
// Release the ServerHello and wait for the client to write its second flight.
raw_transport->BlockWrite();
raw_transport->UnblockReadResult();
raw_transport->WaitForWrite();
// Wait for the server's final flight.
raw_transport->BlockReadResult();
raw_transport->UnblockWrite();
raw_transport->WaitForReadResult();
// Replace it with an alert.
raw_transport->ReplaceReadResult(
FormatTLS12Alert(49 /* AlertDescription.access_denied */));
raw_transport->UnblockReadResult();
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsError(ERR_BAD_SSL_CLIENT_AUTH_CERT));
}
// Test the client can send application data before the ServerHello comes in.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTEarlyDataBeforeServerHello) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() and Write() complete even though the
// ServerHello is blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
// Release the ServerHello. Now reads complete.
socket->UnblockReadResult();
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('1', buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Test that the client sends 1-RTT data if the ServerHello happens to come in
// before Write() is called. See https://crbug.com/950706.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTEarlyDataAfterServerHello) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() completes even though the ServerHello is
// blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
// Wait for the ServerHello to come in and for SSLClientSocket to process it.
socket->WaitForReadResult();
socket->UnblockReadResult();
base::RunLoop().RunUntilIdle();
// Now write to the socket.
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
// Although the socket was created in early data state and the client never
// explicitly called ReaD() or ConfirmHandshake(), SSLClientSocketImpl
// internally consumed the ServerHello and switch keys. The server then
// responds with '0'.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('0', buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Check that 0RTT is confirmed after a Write and Read.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTConfirmedAfterRead) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() and Write() complete even though the
// ServerHello is blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
socket->UnblockReadResult();
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('1', buf->span()[size - 1]);
// After the handshake is confirmed, ConfirmHandshake should return
// synchronously.
TestCompletionCallback callback;
ASSERT_THAT(ssl_socket()->ConfirmHandshake(callback.callback()), IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Test that writes wait for the ServerHello once it has reached the early data
// limit.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTEarlyDataLimit) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() completes even though the ServerHello is
// blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
// EmbeddedTestServer uses BoringSSL's hard-coded early data limit, which is
// below 16k.
constexpr size_t kRequestSize = 16 * 1024;
std::string request = "GET /zerortt HTTP/1.0\r\n";
while (request.size() < kRequestSize) {
request += "The-Answer-To-Life-The-Universe-And-Everything: 42\r\n";
}
request += "\r\n";
// Writing the large input should not succeed. It is blocked on the
// ServerHello.
TestCompletionCallback write_callback;
auto write_buf = base::MakeRefCounted<StringIOBuffer>(request);
int write_rv = ssl_socket()->Write(write_buf.get(), request.size(),
write_callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_THAT(write_rv, IsError(ERR_IO_PENDING));
// The Write should have issued a read for the ServerHello, so
// WaitForReadResult has something to wait for.
socket->WaitForReadResult();
EXPECT_TRUE(socket->pending_read_result());
// Queue a read. It should be blocked on the ServerHello.
TestCompletionCallback read_callback;
auto read_buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int read_rv =
ssl_socket()->Read(read_buf.get(), 4096, read_callback.callback());
ASSERT_THAT(read_rv, IsError(ERR_IO_PENDING));
// Also queue a ConfirmHandshake. It should also be blocked on ServerHello.
TestCompletionCallback confirm_callback;
int confirm_rv = ssl_socket()->ConfirmHandshake(confirm_callback.callback());
ASSERT_THAT(confirm_rv, IsError(ERR_IO_PENDING));
// Double-check the write was not accidentally blocked on the network.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(write_callback.have_result());
// At this point, the maximum possible number of events are all blocked on the
// same thing. Release the ServerHello. All three should complete.
socket->UnblockReadResult();
EXPECT_EQ(static_cast<int>(request.size()),
write_callback.GetResult(write_rv));
EXPECT_THAT(confirm_callback.GetResult(confirm_rv), IsOk());
int size = read_callback.GetResult(read_rv);
ASSERT_GT(size, 0);
EXPECT_EQ('1', read_buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// When a client socket reaches the 0-RTT early data limit, both Write() and
// ConfirmHandshake() become blocked on a transport read. Test that
// CancelReadIfReady() does not interrupt those.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTEarlyDataLimitCancelReadIfReady) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() completes even though the ServerHello is
// blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
// EmbeddedTestServer uses BoringSSL's hard-coded early data limit, which is
// below 16k.
constexpr size_t kRequestSize = 16 * 1024;
std::string request = "GET /zerortt HTTP/1.0\r\n";
while (request.size() < kRequestSize) {
request += "The-Answer-To-Life-The-Universe-And-Everything: 42\r\n";
}
request += "\r\n";
// Writing the large input should not succeed. It is blocked on the
// ServerHello.
TestCompletionCallback write_callback;
auto write_buf = base::MakeRefCounted<StringIOBuffer>(request);
int write_rv = ssl_socket()->Write(write_buf.get(), request.size(),
write_callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_THAT(write_rv, IsError(ERR_IO_PENDING));
// The Write should have issued a read for the ServerHello, so
// WaitForReadResult has something to wait for.
socket->WaitForReadResult();
EXPECT_TRUE(socket->pending_read_result());
// Attempt a ReadIfReady(). It should be blocked on the ServerHello.
TestCompletionCallback read_callback;
auto read_buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int read_rv =
ssl_socket()->ReadIfReady(read_buf.get(), 4096, read_callback.callback());
ASSERT_THAT(read_rv, IsError(ERR_IO_PENDING));
// Also queue a ConfirmHandshake. It should also be blocked on ServerHello.
TestCompletionCallback confirm_callback;
int confirm_rv = ssl_socket()->ConfirmHandshake(confirm_callback.callback());
ASSERT_THAT(confirm_rv, IsError(ERR_IO_PENDING));
// Cancel the ReadIfReady() and release the ServerHello. The remaining
// operations should complete.
ASSERT_THAT(ssl_socket()->CancelReadIfReady(), IsOk());
socket->UnblockReadResult();
EXPECT_EQ(static_cast<int>(request.size()),
write_callback.GetResult(write_rv));
EXPECT_THAT(confirm_callback.GetResult(confirm_rv), IsOk());
// ReadIfReady() should not complete.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(read_callback.have_result());
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
// After a canceled read, future reads are still possible.
TestCompletionCallback read_callback2;
read_rv = read_callback2.GetResult(
ssl_socket()->Read(read_buf.get(), 4096, read_callback2.callback()));
ASSERT_GT(read_rv, 0);
}
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTReject) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
SSLServerConfig server_config;
server_config.early_data_enabled = false;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
SetServerConfig(server_config);
// 0-RTT Connection
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
socket->UnblockReadResult();
// Expect early data to be rejected.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int rv = ReadAndWait(buf.get(), 4096);
EXPECT_EQ(ERR_EARLY_DATA_REJECTED, rv);
rv = WriteAndWait(kRequest);
EXPECT_EQ(ERR_EARLY_DATA_REJECTED, rv);
// Run the event loop so the rejection has reached the TLS session cache.
base::RunLoop().RunUntilIdle();
// Now that the session cache has been updated, retrying the connection
// should succeed.
socket = MakeClient(true);
ASSERT_THAT(Connect(), IsOk());
ASSERT_THAT(MakeHTTPRequest(ssl_socket()), IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
}
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTWrongVersion) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
SetServerConfig(server_config);
// 0-RTT Connection
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
socket->UnblockReadResult();
// Expect early data to be rejected because the TLS version was incorrect.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int rv = ReadAndWait(buf.get(), 4096);
EXPECT_EQ(ERR_WRONG_VERSION_ON_EARLY_DATA, rv);
rv = WriteAndWait(kRequest);
EXPECT_EQ(ERR_WRONG_VERSION_ON_EARLY_DATA, rv);
// Run the event loop so the rejection has reached the TLS session cache.
base::RunLoop().RunUntilIdle();
// Now that the session cache has been updated, retrying the connection
// should succeed.
socket = MakeClient(true);
ASSERT_THAT(Connect(), IsOk());
ASSERT_THAT(MakeHTTPRequest(ssl_socket()), IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
}
// Test that the ConfirmHandshake successfully completes the handshake and that
// it blocks until the server's leg has been received.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTConfirmHandshake) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// 0-RTT Connection
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
// The ServerHello is blocked, so ConfirmHandshake should not complete.
TestCompletionCallback callback;
ASSERT_EQ(ERR_IO_PENDING,
ssl_socket()->ConfirmHandshake(callback.callback()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
// Release the ServerHello. ConfirmHandshake now completes.
socket->UnblockReadResult();
ASSERT_THAT(callback.GetResult(ERR_IO_PENDING), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('0', buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
// Test that an early read does not break during zero RTT.
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTReadBeforeWrite) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// Make a 0-RTT Connection. Connect() completes even though the ServerHello is
// blocked.
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
// Read() does not make progress.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
TestCompletionCallback read_callback;
ASSERT_EQ(ERR_IO_PENDING,
ssl_socket()->Read(buf.get(), 4096, read_callback.callback()));
// Write() completes, even though reads are blocked.
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
// Release the ServerHello, etc. The Read() now completes.
socket->UnblockReadResult();
int size = read_callback.GetResult(ERR_IO_PENDING);
EXPECT_GT(size, 0);
EXPECT_EQ('1', buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTDoubleConfirmHandshake) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// 0-RTT Connection
MakeClient(true);
ASSERT_THAT(Connect(), IsOk());
TestCompletionCallback callback;
ASSERT_THAT(
callback.GetResult(ssl_socket()->ConfirmHandshake(callback.callback())),
IsOk());
// After the handshake is confirmed, ConfirmHandshake should return
// synchronously.
ASSERT_THAT(ssl_socket()->ConfirmHandshake(callback.callback()), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('0', buf->span()[size - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
TEST_F(SSLClientSocketZeroRTTTest, ZeroRTTParallelReadConfirm) {
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// 0-RTT Connection
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
// The ServerHello is blocked, so ConfirmHandshake should not complete.
TestCompletionCallback callback;
ASSERT_EQ(ERR_IO_PENDING,
ssl_socket()->ConfirmHandshake(callback.callback()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback.have_result());
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
TestCompletionCallback read_callback;
ASSERT_EQ(ERR_IO_PENDING,
ssl_socket()->Read(buf.get(), 4096, read_callback.callback()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(read_callback.have_result());
// Release the ServerHello. ConfirmHandshake now completes.
socket->UnblockReadResult();
ASSERT_THAT(callback.WaitForResult(), IsOk());
int result = read_callback.WaitForResult();
EXPECT_GT(result, 0);
EXPECT_EQ('1', buf->span()[result - 1]);
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
}
TEST_P(SSLClientSocketReadTest, IdleAfterRead) {
// Set up a TCP server.
TCPServerSocket server_listener(nullptr, NetLogSource());
ASSERT_THAT(server_listener.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0),
1, /*ipv6_only=*/std::nullopt),
IsOk());
IPEndPoint server_address;
ASSERT_THAT(server_listener.GetLocalAddress(&server_address), IsOk());
// Connect a TCP client and server socket.
TestCompletionCallback server_callback;
std::unique_ptr<StreamSocket> server_transport;
int server_rv =
server_listener.Accept(&server_transport, server_callback.callback());
TestCompletionCallback client_callback;
auto client_transport = std::make_unique<TCPClientSocket>(
AddressList(server_address), nullptr, nullptr, nullptr, NetLogSource());
int client_rv = client_transport->Connect(client_callback.callback());
EXPECT_THAT(server_callback.GetResult(server_rv), IsOk());
EXPECT_THAT(client_callback.GetResult(client_rv), IsOk());
// Set up an SSL server.
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> cert =
ImportCertFromFile(certs_dir, "ok_cert.pem");
ASSERT_TRUE(cert);
bssl::UniquePtr<EVP_PKEY> pkey =
key_util::LoadEVP_PKEYFromPEM(certs_dir.AppendASCII("ok_cert.pem"));
ASSERT_TRUE(pkey);
std::unique_ptr<crypto::RSAPrivateKey> key =
crypto::RSAPrivateKey::CreateFromKey(pkey.get());
ASSERT_TRUE(key);
std::unique_ptr<SSLServerContext> server_context =
CreateSSLServerContext(cert.get(), *key.get(), GetServerConfig());
// Complete the SSL handshake on both sides.
std::unique_ptr<SSLClientSocket> client(CreateSSLClientSocket(
std::move(client_transport), HostPortPair::FromIPEndPoint(server_address),
SSLConfig()));
std::unique_ptr<SSLServerSocket> server(
server_context->CreateSSLServerSocket(std::move(server_transport)));
server_rv = server->Handshake(server_callback.callback());
client_rv = client->Connect(client_callback.callback());
EXPECT_THAT(server_callback.GetResult(server_rv), IsOk());
EXPECT_THAT(client_callback.GetResult(client_rv), IsOk());
// Write a single record on the server.
auto write_buf = base::MakeRefCounted<StringIOBuffer>("a");
server_rv = server->Write(write_buf.get(), 1, server_callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS);
// Read that record on the server, but with a much larger buffer than
// necessary.
auto read_buf = base::MakeRefCounted<IOBufferWithSize>(1024);
client_rv =
Read(client.get(), read_buf.get(), 1024, client_callback.callback());
EXPECT_EQ(1, server_callback.GetResult(server_rv));
EXPECT_EQ(1, WaitForReadCompletion(client.get(), read_buf.get(), 1024,
&client_callback, client_rv));
// At this point the client socket should be idle.
EXPECT_TRUE(client->IsConnectedAndIdle());
}
// Test that certificate errors are properly reported when the underlying
// transport is itself a TLS connection, such as when tunneling over an HTTPS
// proxy. See https://crbug.com/959305.
TEST_F(SSLClientSocketTest, SSLOverSSLBadCertificate) {
// Load a pair of certificates.
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<net::X509Certificate> ok_cert =
ImportCertFromFile(certs_dir, "ok_cert.pem");
ASSERT_TRUE(ok_cert);
bssl::UniquePtr<EVP_PKEY> ok_pkey =
key_util::LoadEVP_PKEYFromPEM(certs_dir.AppendASCII("ok_cert.pem"));
ASSERT_TRUE(ok_pkey);
scoped_refptr<net::X509Certificate> expired_cert =
ImportCertFromFile(certs_dir, "expired_cert.pem");
ASSERT_TRUE(expired_cert);
bssl::UniquePtr<EVP_PKEY> expired_pkey =
key_util::LoadEVP_PKEYFromPEM(certs_dir.AppendASCII("expired_cert.pem"));
ASSERT_TRUE(expired_pkey);
CertVerifyResult expired_result;
expired_result.verified_cert = expired_cert;
expired_result.cert_status = CERT_STATUS_DATE_INVALID;
cert_verifier_->AddResultForCert(expired_cert, expired_result,
ERR_CERT_DATE_INVALID);
// Set up a TCP server.
TCPServerSocket server_listener(nullptr, NetLogSource());
ASSERT_THAT(server_listener.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0),
1, /*ipv6_only=*/std::nullopt),
IsOk());
IPEndPoint server_address;
ASSERT_THAT(server_listener.GetLocalAddress(&server_address), IsOk());
// Connect a TCP client and server socket.
TestCompletionCallback server_callback;
std::unique_ptr<StreamSocket> server_transport;
int server_rv =
server_listener.Accept(&server_transport, server_callback.callback());
TestCompletionCallback client_callback;
auto client_transport = std::make_unique<TCPClientSocket>(
AddressList(server_address), nullptr, nullptr, nullptr, NetLogSource());
int client_rv = client_transport->Connect(client_callback.callback());
ASSERT_THAT(server_callback.GetResult(server_rv), IsOk());
ASSERT_THAT(client_callback.GetResult(client_rv), IsOk());
// Set up a pair of SSL servers.
std::unique_ptr<crypto::RSAPrivateKey> ok_key =
crypto::RSAPrivateKey::CreateFromKey(ok_pkey.get());
ASSERT_TRUE(ok_key);
std::unique_ptr<SSLServerContext> ok_server_context =
CreateSSLServerContext(ok_cert.get(), *ok_key.get(), SSLServerConfig());
std::unique_ptr<crypto::RSAPrivateKey> expired_key =
crypto::RSAPrivateKey::CreateFromKey(expired_pkey.get());
ASSERT_TRUE(expired_key);
std::unique_ptr<SSLServerContext> expired_server_context =
CreateSSLServerContext(expired_cert.get(), *expired_key.get(),
SSLServerConfig());
// Complete the proxy SSL handshake with ok_cert.pem. This should succeed.
std::unique_ptr<SSLClientSocket> client =
CreateSSLClientSocket(std::move(client_transport),
HostPortPair("proxy.test", 443), SSLConfig());
std::unique_ptr<SSLServerSocket> server =
ok_server_context->CreateSSLServerSocket(std::move(server_transport));
client_rv = client->Connect(client_callback.callback());
server_rv = server->Handshake(server_callback.callback());
ASSERT_THAT(client_callback.GetResult(client_rv), IsOk());
ASSERT_THAT(server_callback.GetResult(server_rv), IsOk());
// Run the tunneled SSL handshake on with expired_cert.pem. This should fail.
client = CreateSSLClientSocket(std::move(client),
HostPortPair("server.test", 443), SSLConfig());
server = expired_server_context->CreateSSLServerSocket(std::move(server));
client_rv = client->Connect(client_callback.callback());
server_rv = server->Handshake(server_callback.callback());
// The client should observe the bad certificate error.
EXPECT_THAT(client_callback.GetResult(client_rv),
IsError(ERR_CERT_DATE_INVALID));
SSLInfo ssl_info;
ASSERT_TRUE(client->GetSSLInfo(&ssl_info));
EXPECT_EQ(ssl_info.cert_status, expired_result.cert_status);
// TODO(crbug.com/41430308): The server sees
// ERR_BAD_SSL_CLIENT_AUTH_CERT because its peer (the client) alerts it with
// bad_certificate. The alert-mapping code assumes it is running on a client,
// so it translates bad_certificate to ERR_BAD_SSL_CLIENT_AUTH_CERT, which
// shouldn't be the error for a bad server certificate.
EXPECT_THAT(server_callback.GetResult(server_rv),
IsError(ERR_BAD_SSL_CLIENT_AUTH_CERT));
}
TEST_F(SSLClientSocketTest, Tag) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
auto transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, NetLog::Get(), NetLogSource());
auto tagging_sock =
std::make_unique<MockTaggingStreamSocket>(std::move(transport));
auto* tagging_sock_ptr = tagging_sock.get();
// |sock| takes ownership of |tagging_sock|, but keep a
// non-owning pointer to it.
std::unique_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
std::move(tagging_sock), host_port_pair(), SSLConfig()));
EXPECT_EQ(tagging_sock_ptr->tag(), SocketTag());
#if BUILDFLAG(IS_ANDROID)
SocketTag tag(0x12345678, 0x87654321);
sock->ApplySocketTag(tag);
EXPECT_EQ(tagging_sock_ptr->tag(), tag);
#endif // BUILDFLAG(IS_ANDROID)
}
TEST_F(SSLClientSocketTest, ECH) {
SSLServerConfig server_config;
SSLConfig client_config;
server_config.ech_keys = MakeTestEchKeys(
"public.example", /*max_name_len=*/64, &client_config.ech_config_list);
ASSERT_TRUE(server_config.ech_keys);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Connecting with the client should use ECH.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
SSLInfo ssl_info;
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
EXPECT_TRUE(ssl_info.encrypted_client_hello);
// TLS 1.3 causes the ticket to arrive later. Use the socket to ensure we have
// a ticket. This also populates the SSLInfo from the server.
EXPECT_THAT(MakeHTTPRequest(sock_.get(), "/ssl-info"), IsOk());
std::optional<SSLInfo> server_ssl_info = LastSSLInfoFromServer();
ASSERT_TRUE(server_ssl_info);
EXPECT_TRUE(server_ssl_info->encrypted_client_hello);
// Reconnect. ECH should not interfere with resumption.
sock_.reset();
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
EXPECT_TRUE(ssl_info.encrypted_client_hello);
// Check SSLInfo from the server.
EXPECT_THAT(MakeHTTPRequest(sock_.get(), "/ssl-info"), IsOk());
server_ssl_info = LastSSLInfoFromServer();
ASSERT_TRUE(server_ssl_info);
EXPECT_TRUE(server_ssl_info->encrypted_client_hello);
// Connecting without ECH should not report ECH was used.
client_config.ech_config_list.clear();
sock_.reset();
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
EXPECT_FALSE(ssl_info.encrypted_client_hello);
// Check SSLInfo from the server.
EXPECT_THAT(MakeHTTPRequest(sock_.get(), "/ssl-info"), IsOk());
server_ssl_info = LastSSLInfoFromServer();
ASSERT_TRUE(server_ssl_info);
EXPECT_FALSE(server_ssl_info->encrypted_client_hello);
}
// Test that, on key mismatch, the public name can be used to authenticate
// replacement keys.
TEST_F(SSLClientSocketTest, ECHWrongKeys) {
static const char kPublicName[] = "public.example";
std::vector<uint8_t> ech_config_list1, ech_config_list2;
bssl::UniquePtr<SSL_ECH_KEYS> keys1 =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list1);
ASSERT_TRUE(keys1);
bssl::UniquePtr<SSL_ECH_KEYS> keys2 =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list2);
ASSERT_TRUE(keys2);
// Configure the client and server with different keys.
SSLServerConfig server_config;
server_config.ech_keys = std::move(keys1);
SSLConfig client_config;
client_config.ech_config_list = std::move(ech_config_list2);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Verify the fallback handshake verifies the certificate against the public
// name.
cert_verifier_->set_default_result(ERR_CERT_INVALID);
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
CertVerifyResult verify_result;
verify_result.verified_cert = server_cert;
cert_verifier_->AddResultForCertAndHost(server_cert, kPublicName,
verify_result, OK);
// Connecting with the client should report ECH was not negotiated.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_ECH_NOT_NEGOTIATED));
// The server's keys are available as retry keys.
EXPECT_EQ(ech_config_list1, sock_->GetECHRetryConfigs());
}
// Test that, if the server does not support ECH, it can securely report this
// via the public name. This allows recovery if the server needed to
// rollback ECH support.
TEST_F(SSLClientSocketTest, ECHSecurelyDisabled) {
static const char kPublicName[] = "public.example";
std::vector<uint8_t> ech_config_list;
bssl::UniquePtr<SSL_ECH_KEYS> keys =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list);
ASSERT_TRUE(keys);
// The server does not have keys configured.
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
// However it can authenticate for kPublicName.
cert_verifier_->set_default_result(ERR_CERT_INVALID);
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
CertVerifyResult verify_result;
verify_result.verified_cert = server_cert;
cert_verifier_->AddResultForCertAndHost(server_cert, kPublicName,
verify_result, OK);
// Connecting with the client should report ECH was not negotiated.
SSLConfig client_config;
client_config.ech_config_list = std::move(ech_config_list);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_ECH_NOT_NEGOTIATED));
// The retry config is empty, meaning the server has securely reported that
// ECH is disabled
EXPECT_TRUE(sock_->GetECHRetryConfigs().empty());
}
// The same as the above, but testing that it also works in TLS 1.2, which
// otherwise does not support ECH.
TEST_F(SSLClientSocketTest, ECHSecurelyDisabledTLS12) {
static const char kPublicName[] = "public.example";
std::vector<uint8_t> ech_config_list;
bssl::UniquePtr<SSL_ECH_KEYS> keys =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list);
ASSERT_TRUE(keys);
// The server does not have keys configured.
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// However it can authenticate for kPublicName.
cert_verifier_->set_default_result(ERR_CERT_INVALID);
scoped_refptr<X509Certificate> server_cert =
embedded_test_server()->GetCertificate();
CertVerifyResult verify_result;
verify_result.verified_cert = server_cert;
cert_verifier_->AddResultForCertAndHost(server_cert, kPublicName,
verify_result, OK);
// Connecting with the client should report ECH was not negotiated.
SSLConfig client_config;
client_config.ech_config_list = std::move(ech_config_list);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_ECH_NOT_NEGOTIATED));
// The retry config is empty, meaning the server has securely reported that
// ECH is disabled
EXPECT_TRUE(sock_->GetECHRetryConfigs().empty());
}
// Test that the ECH fallback handshake rejects bad certificates.
TEST_F(SSLClientSocketTest, ECHFallbackBadCert) {
static const char kPublicName[] = "public.example";
std::vector<uint8_t> ech_config_list1, ech_config_list2;
bssl::UniquePtr<SSL_ECH_KEYS> keys1 =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list1);
ASSERT_TRUE(keys1);
bssl::UniquePtr<SSL_ECH_KEYS> keys2 =
MakeTestEchKeys(kPublicName, /*max_name_len=*/64, &ech_config_list2);
ASSERT_TRUE(keys2);
// Configure the client and server with different keys.
SSLServerConfig server_config;
server_config.ech_keys = std::move(keys1);
SSLConfig client_config;
client_config.ech_config_list = std::move(ech_config_list2);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Configure the client to reject the certificate for the public name (or any
// other name).
cert_verifier_->set_default_result(ERR_CERT_INVALID);
// Connecting with the client will fail with a fatal error.
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_ECH_FALLBACK_CERTIFICATE_INVALID));
}
TEST_F(SSLClientSocketTest, InvalidECHConfigList) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
// If the ECHConfigList cannot be parsed at all, report an error to the
// caller.
SSLConfig client_config;
client_config.ech_config_list = {0x00};
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsError(ERR_INVALID_ECH_CONFIG_LIST));
}
// Test that, if no ECHConfigList is available, the client sends ECH GREASE.
TEST_F(SSLClientSocketTest, ECHGreaseEnabled) {
// Configure the server to expect an ECH extension.
bool ran_callback = false;
SSLServerConfig server_config;
server_config.client_hello_callback_for_testing =
base::BindLambdaForTesting([&](const SSL_CLIENT_HELLO* client_hello) {
const uint8_t* data;
size_t len;
EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_encrypted_client_hello, &data, &len));
ran_callback = true;
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
}
// Test that, if ECH is disabled, the client does not send ECH GREASE.
TEST_F(SSLClientSocketTest, ECHGreaseDisabled) {
SSLContextConfig context_config;
context_config.ech_enabled = false;
ssl_config_service_->UpdateSSLConfigAndNotify(context_config);
// Configure the server not to expect an ECH extension.
bool ran_callback = false;
SSLServerConfig server_config;
server_config.client_hello_callback_for_testing =
base::BindLambdaForTesting([&](const SSL_CLIENT_HELLO* client_hello) {
const uint8_t* data;
size_t len;
EXPECT_FALSE(SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_encrypted_client_hello, &data, &len));
ran_callback = true;
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
}
struct SSLHandshakeDetailsParams {
bool alpn;
bool early_data;
uint16_t version;
SSLHandshakeDetails expected_initial;
SSLHandshakeDetails expected_resume;
};
const SSLHandshakeDetailsParams kSSLHandshakeDetailsParams[] = {
// TLS 1.2 does False Start if ALPN is enabled.
{false /* no ALPN */, false /* no early data */,
SSL_PROTOCOL_VERSION_TLS1_2, SSLHandshakeDetails::kTLS12Full,
SSLHandshakeDetails::kTLS12Resume},
{true /* ALPN */, false /* no early data */, SSL_PROTOCOL_VERSION_TLS1_2,
SSLHandshakeDetails::kTLS12FalseStart, SSLHandshakeDetails::kTLS12Resume},
// TLS 1.3 supports full handshakes, resumption, and 0-RTT.
{false /* no ALPN */, false /* no early data */,
SSL_PROTOCOL_VERSION_TLS1_3, SSLHandshakeDetails::kTLS13Full,
SSLHandshakeDetails::kTLS13Resume},
{false /* no ALPN */, true /* early data */, SSL_PROTOCOL_VERSION_TLS1_3,
SSLHandshakeDetails::kTLS13Full, SSLHandshakeDetails::kTLS13Early},
};
class SSLHandshakeDetailsTest
: public SSLClientSocketTest,
public ::testing::WithParamInterface<SSLHandshakeDetailsParams> {};
INSTANTIATE_TEST_SUITE_P(All,
SSLHandshakeDetailsTest,
ValuesIn(kSSLHandshakeDetailsParams));
TEST_P(SSLHandshakeDetailsTest, Metrics) {
// Enable all test features in the server.
SSLServerConfig server_config;
server_config.early_data_enabled = true;
server_config.alpn_protos = {NextProto::kProtoHTTP11};
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLContextConfig client_context_config;
client_context_config.version_min = GetParam().version;
client_context_config.version_max = GetParam().version;
ssl_config_service_->UpdateSSLConfigAndNotify(client_context_config);
SSLConfig client_config;
client_config.version_min_override = GetParam().version;
client_config.version_max_override = GetParam().version;
client_config.early_data_enabled = GetParam().early_data;
if (GetParam().alpn) {
client_config.alpn_protos = {NextProto::kProtoHTTP11};
}
SSLVersion version;
switch (GetParam().version) {
case SSL_PROTOCOL_VERSION_TLS1_2:
version = SSL_CONNECTION_VERSION_TLS1_2;
break;
case SSL_PROTOCOL_VERSION_TLS1_3:
version = SSL_CONNECTION_VERSION_TLS1_3;
break;
default:
FAIL() << GetParam().version;
}
// Make the initial connection.
{
base::HistogramTester histograms;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// Sanity-check the socket matches the test parameters.
SSLInfo info;
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(version, SSLConnectionStatusToVersion(info.connection_status));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, info.handshake_type);
histograms.ExpectUniqueSample("Net.SSLHandshakeDetails",
GetParam().expected_initial, 1);
// TLS 1.2 with False Start and TLS 1.3 cause the ticket to arrive later, so
// use the socket to ensure the session ticket has been picked up.
EXPECT_THAT(MakeHTTPRequest(sock_.get()), IsOk());
}
// Make a resumption connection.
{
base::HistogramTester histograms;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
// Sanity-check the socket matches the test parameters.
SSLInfo info;
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(version, SSLConnectionStatusToVersion(info.connection_status));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, info.handshake_type);
histograms.ExpectUniqueSample("Net.SSLHandshakeDetails",
GetParam().expected_resume, 1);
}
}
TEST_F(SSLClientSocketZeroRTTTest, EarlyDataReasonNewSession) {
const char kReasonHistogram[] = "Net.SSLHandshakeEarlyDataReason";
ASSERT_TRUE(StartServer());
base::HistogramTester histograms;
ASSERT_TRUE(RunInitialConnection());
histograms.ExpectUniqueSample(kReasonHistogram,
ssl_early_data_no_session_offered, 1);
}
// Test 0-RTT logging when the server declines to resume a connection.
TEST_F(SSLClientSocketZeroRTTTest, EarlyDataReasonNoResume) {
const char kReasonHistogram[] = "Net.SSLHandshakeEarlyDataReason";
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
SSLServerConfig server_config;
server_config.early_data_enabled = false;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
SetServerConfig(server_config);
base::HistogramTester histograms;
// 0-RTT Connection
FakeBlockingStreamSocket* socket = MakeClient(true);
socket->BlockReadResult();
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
socket->UnblockReadResult();
// Expect early data to be rejected.
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int rv = ReadAndWait(buf.get(), 4096);
EXPECT_EQ(ERR_EARLY_DATA_REJECTED, rv);
// The histogram may be record asynchronously.
base::RunLoop().RunUntilIdle();
histograms.ExpectUniqueSample(kReasonHistogram,
ssl_early_data_session_not_resumed, 1);
}
// Test 0-RTT logging in the standard ConfirmHandshake-after-acceptance case.
TEST_F(SSLClientSocketZeroRTTTest, EarlyDataReasonZeroRTT) {
const char kReasonHistogram[] = "Net.SSLHandshakeEarlyDataReason";
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// 0-RTT Connection
base::HistogramTester histograms;
MakeClient(true);
ASSERT_THAT(Connect(), IsOk());
TestCompletionCallback callback;
ASSERT_THAT(
callback.GetResult(ssl_socket()->ConfirmHandshake(callback.callback())),
IsOk());
base::RunLoop().RunUntilIdle();
histograms.ExpectUniqueSample(kReasonHistogram, ssl_early_data_accepted, 1);
}
// Check that we're correctly logging 0-rtt success when the handshake
// concludes during a Read.
TEST_F(SSLClientSocketZeroRTTTest, EarlyDataReasonReadServerHello) {
const char kReasonHistogram[] = "Net.SSLHandshakeEarlyDataReason";
ASSERT_TRUE(StartServer());
ASSERT_TRUE(RunInitialConnection());
// 0-RTT Connection
base::HistogramTester histograms;
MakeClient(true);
ASSERT_THAT(Connect(), IsOk());
constexpr std::string_view kRequest = "GET /zerortt HTTP/1.0\r\n\r\n";
EXPECT_EQ(static_cast<int>(kRequest.size()), WriteAndWait(kRequest));
auto buf = base::MakeRefCounted<IOBufferWithSize>(4096);
int size = ReadAndWait(buf.get(), 4096);
EXPECT_GT(size, 0);
EXPECT_EQ('1', buf->span()[size - 1]);
// 0-RTT metrics are logged on a PostTask, so if Read returns synchronously,
// it is possible the metrics haven't been picked up yet.
base::RunLoop().RunUntilIdle();
SSLInfo ssl_info;
ASSERT_TRUE(GetSSLInfo(&ssl_info));
EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
histograms.ExpectUniqueSample(kReasonHistogram, ssl_early_data_accepted, 1);
}
TEST_F(SSLClientSocketTest, VersionMaxOverride) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Connecting normally uses the global configuration.
SSLConfig config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsOk());
SSLInfo info;
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
SSLConnectionStatusToVersion(info.connection_status));
// Individual sockets may override the maximum version.
config.version_max_override = SSL_PROTOCOL_VERSION_TLS1_2;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsOk());
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
SSLConnectionStatusToVersion(info.connection_status));
}
TEST_F(SSLClientSocketTest, VersionMinOverride) {
SSLServerConfig server_config;
server_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2;
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// Connecting normally uses the global configuration.
SSLConfig config;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsOk());
SSLInfo info;
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
SSLConnectionStatusToVersion(info.connection_status));
// Individual sockets may also override the minimum version.
config.version_min_override = SSL_PROTOCOL_VERSION_TLS1_3;
config.version_max_override = SSL_PROTOCOL_VERSION_TLS1_3;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(config, &rv));
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
// Basic test of CancelReadIfReady works.
TEST_F(SSLClientSocketTest, CancelReadIfReady) {
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, SSLServerConfig()));
// Connect with a FakeBlockingStreamSocket.
auto real_transport = std::make_unique<TCPClientSocket>(
addr(), nullptr, nullptr, nullptr, NetLogSource());
auto transport =
std::make_unique<FakeBlockingStreamSocket>(std::move(real_transport));
FakeBlockingStreamSocket* raw_transport = transport.get();
TestCompletionCallback callback;
ASSERT_THAT(callback.GetResult(transport->Connect(callback.callback())),
IsOk());
// Complete the handshake. Disable the post-handshake peek so that, after the
// handshake, there are no pending reads on the transport.
SSLConfig config;
config.disable_post_handshake_peek_for_testing = true;
auto sock =
CreateSSLClientSocket(std::move(transport), host_port_pair(), config);
ASSERT_THAT(callback.GetResult(sock->Connect(callback.callback())), IsOk());
// Block the socket and wait for some data to arrive from the server.
raw_transport->BlockReadResult();
auto write_buf =
base::MakeRefCounted<StringIOBuffer>("GET / HTTP/1.0\r\n\r\n");
ASSERT_EQ(callback.GetResult(sock->Write(write_buf.get(), write_buf->size(),
callback.callback(),
TRAFFIC_ANNOTATION_FOR_TESTS)),
write_buf->size());
// ReadIfReady() should not read anything because the socket is blocked.
bool callback_called = false;
auto read_buf = base::MakeRefCounted<IOBufferWithSize>(100);
int rv = sock->ReadIfReady(
read_buf.get(), 100,
base::BindLambdaForTesting([&](int rv) { callback_called = true; }));
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Cancel ReadIfReady() and unblock the socket.
ASSERT_THAT(sock->CancelReadIfReady(), IsOk());
raw_transport->WaitForReadResult();
raw_transport->UnblockReadResult();
base::RunLoop().RunUntilIdle();
// Although data is now available, the callback should not have been called.
EXPECT_FALSE(callback_called);
// Future reads on the socket should still work. The data should be
// synchronously available.
EXPECT_GT(
callback.GetResult(sock->Read(read_buf.get(), 100, callback.callback())),
0);
}
// Test that the server_name extension (SNI) is sent on DNS names, and not IP
// literals.
TEST_F(SSLClientSocketTest, ServerName) {
std::optional<std::string> got_server_name;
bool ran_callback = false;
auto reset_callback_state = [&] {
got_server_name = std::nullopt;
ran_callback = false;
};
// Start a server which records the server name.
SSLServerConfig server_config;
server_config.client_hello_callback_for_testing =
base::BindLambdaForTesting([&](const SSL_CLIENT_HELLO* client_hello) {
const char* server_name =
SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name);
if (server_name) {
got_server_name = server_name;
} else {
got_server_name = std::nullopt;
}
ran_callback = true;
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
// The client should send the server_name extension for DNS names.
uint16_t port = host_port_pair().port();
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(
SSLConfig(), HostPortPair("example.com", port), &rv));
ASSERT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
EXPECT_EQ(got_server_name, "example.com");
// The client should not send the server_name extension for IPv4 and IPv6
// literals. See https://crbug.com/500981.
reset_callback_state();
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(
SSLConfig(), HostPortPair("1.2.3.4", port), &rv));
ASSERT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
EXPECT_EQ(got_server_name, std::nullopt);
reset_callback_state();
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(
SSLConfig(), HostPortPair("::1", port), &rv));
ASSERT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
EXPECT_EQ(got_server_name, std::nullopt);
reset_callback_state();
ASSERT_TRUE(CreateAndConnectSSLClientSocketWithHost(
SSLConfig(), HostPortPair("2001:db8::42", port), &rv));
ASSERT_THAT(rv, IsOk());
EXPECT_TRUE(ran_callback);
EXPECT_EQ(got_server_name, std::nullopt);
}
TEST_F(SSLClientSocketTest, PostQuantumKeyExchange) {
SSLServerConfig server_config;
server_config.curves_for_testing.push_back(NID_X25519MLKEM768);
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
for (bool enabled : {false, true}) {
SCOPED_TRACE(enabled);
SSLContextConfig config;
config.post_quantum_key_agreement_enabled = enabled;
ssl_config_service_->UpdateSSLConfigAndNotify(config);
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
if (enabled) {
EXPECT_THAT(rv, IsOk());
} else {
EXPECT_THAT(rv, IsError(ERR_SSL_VERSION_OR_CIPHER_MISMATCH));
}
}
}
class SSLClientSocketAlpsTest
: public SSLClientSocketTest,
public ::testing::WithParamInterface<std::tuple<bool, bool, bool>> {
public:
SSLClientSocketAlpsTest() {
if (client_use_new_alps()) {
feature_list_.InitAndEnableFeature(features::kUseNewAlpsCodepointHttp2);
} else {
feature_list_.InitAndDisableFeature(features::kUseNewAlpsCodepointHttp2);
}
}
bool client_alps_enabled() const { return std::get<0>(GetParam()); }
bool server_alps_enabled() const { return std::get<1>(GetParam()); }
bool client_use_new_alps() const { return std::get<2>(GetParam()); }
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
SSLClientSocketAlpsTest,
Combine(Bool(), Bool(), Bool()));
TEST_P(SSLClientSocketAlpsTest, Alps) {
const std::string server_data = "server sends some test data";
const std::string client_data = "client also sends some data";
SSLServerConfig server_config;
server_config.alpn_protos = {NextProto::kProtoHTTP2};
if (server_alps_enabled()) {
server_config.application_settings[NextProto::kProtoHTTP2] =
std::vector<uint8_t>(server_data.begin(), server_data.end());
}
// Configure the server to support whichever ALPS codepoint the client sent.
server_config.client_hello_callback_for_testing =
base::BindRepeating([](const SSL_CLIENT_HELLO* client_hello) {
const uint8_t* unused_extension_bytes;
size_t unused_extension_len;
int use_alps_new_codepoint = SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_application_settings,
&unused_extension_bytes, &unused_extension_len);
SSL_set_alps_use_new_codepoint(client_hello->ssl,
use_alps_new_codepoint);
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
SSLConfig client_config;
client_config.alpn_protos = {NextProto::kProtoHTTP2};
if (client_alps_enabled()) {
client_config.application_settings[NextProto::kProtoHTTP2] =
std::vector<uint8_t>(client_data.begin(), client_data.end());
}
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
SSLInfo info;
ASSERT_TRUE(sock_->GetSSLInfo(&info));
EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
SSLConnectionStatusToVersion(info.connection_status));
EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, info.handshake_type);
EXPECT_EQ(NextProto::kProtoHTTP2, sock_->GetNegotiatedProtocol());
// ALPS is negotiated only if ALPS is enabled both on client and server.
const auto alps_data_received_by_client = sock_->GetPeerApplicationSettings();
if (client_alps_enabled() && server_alps_enabled()) {
ASSERT_TRUE(alps_data_received_by_client.has_value());
EXPECT_EQ(server_data, alps_data_received_by_client.value());
} else {
EXPECT_FALSE(alps_data_received_by_client.has_value());
}
}
// Test that unused protocols in `application_settings` are ignored.
TEST_P(SSLClientSocketAlpsTest, UnusedProtocols) {
if (!client_alps_enabled() || !server_alps_enabled()) {
return;
}
SSLConfig client_config;
client_config.alpn_protos = {NextProto::kProtoHTTP2};
client_config.application_settings[NextProto::kProtoHTTP2] = {};
client_config.application_settings[NextProto::kProtoHTTP11] = {};
// Configure the server to check the ClientHello is as we expected.
SSLServerConfig server_config;
server_config.client_hello_callback_for_testing =
base::BindLambdaForTesting([&](const SSL_CLIENT_HELLO* client_hello) {
const uint8_t* data;
size_t len;
if (!SSL_early_callback_ctx_extension_get(
client_hello,
client_use_new_alps() ? TLSEXT_TYPE_application_settings
: TLSEXT_TYPE_application_settings_old,
&data, &len)) {
return false;
}
// The client should only have sent "h2" in the extension. Note there
// are two length prefixes. A two-byte length prefix (0x0003) followed
// by a one-byte length prefix (0x02). See
// https://www.ietf.org/archive/id/draft-vvv-tls-alps-01.html#section-4
static constexpr auto expected =
std::to_array<uint8_t>({0x00, 0x03, 0x02, 'h', '2'});
EXPECT_EQ(
// SAFETY:
// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_early_callback_ctx_extension_get
// The comment of `SSL_early_callback_ctx_extension_get` says that
// `data` is set to extension contents, and `len` is the
// length of the extension contents.
UNSAFE_BUFFERS(base::span(data, data + len)), base::span(expected));
return true;
});
ASSERT_TRUE(
StartEmbeddedTestServer(EmbeddedTestServer::CERT_OK, server_config));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(client_config, &rv));
EXPECT_THAT(rv, IsOk());
}
} // namespace net
|