1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464
|
// 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.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include <array>
#include <memory>
#include <string_view>
#include <utility>
#include "base/base64.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/strings/escape.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.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_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/default_clock.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/interstitials/security_interstitial_idn_test.h"
#include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ssl/cert_verifier_browser_test.h"
#include "chrome/browser/ssl/chrome_security_blocking_page_factory.h"
#include "chrome/browser/ssl/https_upgrades_util.h"
#include "chrome/browser/ssl/ssl_browsertest_util.h"
#include "chrome/browser/ssl/ssl_error_controller_client.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/web_applications/test/os_integration_test_override_impl.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/safe_browsing_private.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
#include "components/content_settings/common/content_settings_agent.mojom.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/embedder_support/switches.h"
#include "components/error_page/content/browser/net_error_auto_reloader.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/network_time/network_time_test_utils.h"
#include "components/network_time/network_time_tracker.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/testing_pref_service.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/security_interstitials/content/bad_clock_blocking_page.h"
#include "components/security_interstitials/content/captive_portal_blocking_page.h"
#include "components/security_interstitials/content/common_name_mismatch_handler.h"
#include "components/security_interstitials/content/insecure_form_blocking_page.h"
#include "components/security_interstitials/content/insecure_form_navigation_throttle.h"
#include "components/security_interstitials/content/mitm_software_blocking_page.h"
#include "components/security_interstitials/content/security_interstitial_controller_client.h"
#include "components/security_interstitials/content/security_interstitial_page.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/security_interstitials/content/ssl_blocking_page.h"
#include "components/security_interstitials/content/ssl_error_assistant.h"
#include "components/security_interstitials/content/ssl_error_assistant.pb.h"
#include "components/security_interstitials/content/ssl_error_handler.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/security_interstitials/core/controller_client.h"
#include "components/security_interstitials/core/https_only_mode_metrics.h"
#include "components/security_interstitials/core/metrics_helper.h"
#include "components/security_interstitials/core/pref_names.h"
#include "components/security_state/content/security_state_tab_helper.h"
#include "components/security_state/core/security_state.h"
#include "components/strings/grit/components_strings.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_entry_restore_context.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/network_service_util.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/restore_type.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_mock_cert_verifier.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "crypto/hash.h"
#include "extensions/browser/event_router.h"
#include "google_apis/gaia/gaia_id.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/sync_call_restrictions.h"
#include "net/base/features.h"
#include "net/base/host_port_pair.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_database.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/http/transport_security_state_test_util.h"
#include "net/ssl/client_cert_identity_test_util.h"
#include "net/ssl/client_cert_store.h"
#include "net/ssl/ssl_config.h"
#include "net/ssl/ssl_info.h"
#include "net/ssl/ssl_server_config.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/controllable_http_response.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/embedded_test_server/request_handler_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/test_certificate_data.h"
#include "net/test/test_data_directory.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/chrome_debug_urls.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/page_state/page_state.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/mojom/window_features/window_features.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/scoped_test_mv2_enabler.h"
#include "extensions/browser/background_script_executor.h"
#include "extensions/common/extension.h"
#include "extensions/test/test_extension_dir.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#if BUILDFLAG(USE_NSS_CERTS)
#include "chrome/browser/net/nss_service.h"
#include "chrome/browser/net/nss_service_factory.h"
#include "crypto/scoped_test_nss_db.h"
#include "net/cert/nss_cert_database.h"
#include "net/cert/x509_util_nss.h"
#endif // BUILDFLAG(USE_NSS_CERTS)
#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_switches.h"
#include "base/path_service.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector_builder.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#endif // BUILDFLAG(IS_CHROMEOS)
using content::WebContents;
namespace AuthState = ssl_test_util::AuthState;
namespace CertError = ssl_test_util::CertError;
namespace {
const int kLargeVersionId = 0xFFFFFF;
const char kHstsTestHostName[] = "hsts-example.test";
enum ProceedDecision {
SSL_INTERSTITIAL_PROCEED,
SSL_INTERSTITIAL_DO_NOT_PROCEED
};
// A WebContentsObserver that allows observing when the page has set a
// particular SSL content status flag. Assumes that the flag is not set when the
// observer is created.
class SSLContentStatusObserver : public content::WebContentsObserver {
public:
explicit SSLContentStatusObserver(content::WebContents* web_contents,
content::SSLStatus::ContentStatusFlags flag)
: content::WebContentsObserver(web_contents), flag_(flag) {
content::NavigationEntry* entry =
web_contents->GetController().GetVisibleEntry();
if (entry) {
DCHECK(!(entry->GetSSL().content_status & flag_));
}
}
SSLContentStatusObserver(const SSLContentStatusObserver&) = delete;
SSLContentStatusObserver& operator=(const SSLContentStatusObserver&) = delete;
~SSLContentStatusObserver() override = default;
void DidChangeVisibleSecurityState() override {
content::NavigationEntry* entry =
web_contents()->GetController().GetVisibleEntry();
if (entry && (entry->GetSSL().content_status & flag_)) {
run_loop_.Quit();
}
}
void WaitForSSLContentStatusFlag() { run_loop_.Run(); }
private:
// The content status flag of interest
content::SSLStatus::ContentStatusFlags flag_;
base::RunLoop run_loop_;
};
// This observer waits for the SSLErrorHandler to start an interstitial timer
// for the given web contents.
class SSLInterstitialTimerObserver {
public:
explicit SSLInterstitialTimerObserver(WebContents* web_contents)
: web_contents_(web_contents), message_loop_runner_(new base::RunLoop) {
callback_ = base::BindRepeating(
&SSLInterstitialTimerObserver::OnTimerStarted, base::Unretained(this));
SSLErrorHandler::SetInterstitialTimerStartedCallbackForTesting(&callback_);
}
SSLInterstitialTimerObserver(const SSLInterstitialTimerObserver&) = delete;
SSLInterstitialTimerObserver& operator=(const SSLInterstitialTimerObserver&) =
delete;
~SSLInterstitialTimerObserver() {
SSLErrorHandler::SetInterstitialTimerStartedCallbackForTesting(nullptr);
}
// Waits until the interstitial delay timer in SSLErrorHandler is started.
void WaitForTimerStarted() { message_loop_runner_->Run(); }
// Returns true if the interstitial delay timer has been started.
bool timer_started() const { return timer_started_; }
private:
void OnTimerStarted(WebContents* web_contents) {
timer_started_ = true;
if (web_contents_ == web_contents)
message_loop_runner_->Quit();
}
bool timer_started_ = false;
raw_ptr<const WebContents> web_contents_;
SSLErrorHandler::TimerStartedCallback callback_;
std::unique_ptr<base::RunLoop> message_loop_runner_;
};
class ChromeContentBrowserClientForMixedContentTest
: public ChromeContentBrowserClient {
public:
ChromeContentBrowserClientForMixedContentTest() = default;
ChromeContentBrowserClientForMixedContentTest(
const ChromeContentBrowserClientForMixedContentTest&) = delete;
ChromeContentBrowserClientForMixedContentTest& operator=(
const ChromeContentBrowserClientForMixedContentTest&) = delete;
void OverrideWebPreferences(
content::WebContents* web_contents,
content::SiteInstance& main_frame_site,
blink::web_pref::WebPreferences* web_prefs) override {
web_prefs->allow_running_insecure_content = allow_running_insecure_content_;
web_prefs->strict_mixed_content_checking = strict_mixed_content_checking_;
web_prefs->strictly_block_blockable_mixed_content =
strictly_block_blockable_mixed_content_;
}
void SetMixedContentSettings(bool allow_running_insecure_content,
bool strict_mixed_content_checking,
bool strictly_block_blockable_mixed_content) {
allow_running_insecure_content_ = allow_running_insecure_content;
strict_mixed_content_checking_ = strict_mixed_content_checking;
strictly_block_blockable_mixed_content_ =
strictly_block_blockable_mixed_content;
}
private:
bool allow_running_insecure_content_ = false;
bool strict_mixed_content_checking_ = false;
bool strictly_block_blockable_mixed_content_ = false;
};
std::string EncodeQuery(const std::string& query) {
url::RawCanonOutputT<char> buffer;
url::EncodeURIComponent(query, &buffer);
return std::string(buffer.view());
}
// Returns the Sha256 hash of the SPKI of |cert|.
std::array<uint8_t, crypto::hash::kSha256Size> GetSPKIHash(
const CRYPTO_BUFFER* cert) {
std::string_view spki_bytes;
EXPECT_TRUE(net::asn1::ExtractSPKIFromDERCert(
net::x509_util::CryptoBufferAsStringPiece(cert), &spki_bytes));
return crypto::hash::Sha256(base::as_byte_span(spki_bytes));
}
// Compares two SSLStatuses to check if they match up before and after an
// interstitial. To match up, they should have the same connection information
// properties, such as certificate, connection status, connection security,
// etc. Content status and user data are not compared. Returns true if the
// statuses match and false otherwise.
bool ComparePreAndPostInterstitialSSLStatuses(const content::SSLStatus& one,
const content::SSLStatus& two) {
// TODO(mattm): It feels like this should use
// certificate->EqualsIncludingChain, but that fails on some platforms. Find
// out why and document or fix.
return one.initialized == two.initialized &&
!!one.certificate == !!two.certificate &&
(one.certificate
? one.certificate->EqualsExcludingChain(two.certificate.get())
: true) &&
one.cert_status == two.cert_status &&
one.key_exchange_group == two.key_exchange_group &&
// Skip comparing the peer_signature_algorithm, because it is not
// filled in by the time of an interstitial.
one.connection_status == two.connection_status &&
one.pkp_bypassed == two.pkp_bypassed;
}
void ExpectInterstitialElementHidden(WebContents* tab,
const std::string& element_id,
bool expect_hidden) {
content::RenderFrameHost* frame = tab->GetPrimaryMainFrame();
// Send CMD_TEXT_FOUND to indicate that the 'hidden' class is found, and
// CMD_TEXT_NOT_FOUND if not.
std::string command = base::StringPrintf(
"document.querySelector('#%s')"
" .classList.contains('hidden')"
" ? %d : %d;",
element_id.c_str(), security_interstitials::CMD_TEXT_FOUND,
security_interstitials::CMD_TEXT_NOT_FOUND);
int result = content::EvalJs(frame, command).ExtractInt();
EXPECT_EQ(expect_hidden ? security_interstitials::CMD_TEXT_FOUND
: security_interstitials::CMD_TEXT_NOT_FOUND,
result);
}
} // namespace
class SSLUITestBase : public InProcessBrowserTest,
public network::mojom::SSLConfigClient {
public:
SSLUITestBase()
: https_server_(net::EmbeddedTestServer::TYPE_HTTPS),
https_server_expired_(net::EmbeddedTestServer::TYPE_HTTPS),
https_server_mismatched_(net::EmbeddedTestServer::TYPE_HTTPS),
https_server_sha1_(net::EmbeddedTestServer::TYPE_HTTPS),
https_server_common_name_only_(net::EmbeddedTestServer::TYPE_HTTPS),
wss_server_expired_(net::SpawnedTestServer::TYPE_WSS,
SSLOptions(SSLOptions::CERT_EXPIRED),
net::GetWebSocketTestDataDirectory()),
wss_server_mismatched_(net::SpawnedTestServer::TYPE_WSS,
SSLOptions(SSLOptions::CERT_MISMATCHED_NAME),
net::GetWebSocketTestDataDirectory()) {
https_server_.AddDefaultHandlers(GetChromeTestDataDir());
https_server_expired_.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
https_server_expired_.AddDefaultHandlers(GetChromeTestDataDir());
https_server_mismatched_.SetSSLConfig(
net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
https_server_mismatched_.AddDefaultHandlers(GetChromeTestDataDir());
https_server_sha1_.SetSSLConfig(net::EmbeddedTestServer::CERT_SHA1_LEAF);
https_server_sha1_.AddDefaultHandlers(GetChromeTestDataDir());
https_server_common_name_only_.SetSSLConfig(
net::EmbeddedTestServer::CERT_COMMON_NAME_ONLY);
https_server_common_name_only_.AddDefaultHandlers(GetChromeTestDataDir());
}
SSLUITestBase(const SSLUITestBase&) = delete;
SSLUITestBase& operator=(const SSLUITestBase&) = delete;
void SetUp() override {
policy_provider_.SetDefaultReturns(
/*is_initialization_complete_return=*/true,
/*is_first_policy_load_complete_return=*/true);
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
&policy_provider_);
InProcessBrowserTest::SetUp();
SSLErrorHandler::ResetConfigForTesting();
}
void TearDown() override {
SSLErrorHandler::ResetConfigForTesting();
InProcessBrowserTest::TearDown();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Browser will both run and display insecure content.
command_line->AppendSwitch(switches::kAllowRunningInsecureContent);
// Use process-per-site so that navigating to a same-site page in a
// new tab will use the same process.
command_line->AppendSwitch(switches::kProcessPerSite);
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
network::mojom::NetworkContextParamsPtr context_params =
CreateDefaultNetworkContextParams();
last_ssl_config_ = *context_params->initial_ssl_config;
receiver_.Bind(std::move(context_params->ssl_config_client_receiver));
}
void TearDownOnMainThread() override { receiver_.reset(); }
void ProceedThroughInterstitial(WebContents* tab) {
content::TestNavigationObserver nav_observer(tab, 1);
SendInterstitialCommand(tab, security_interstitials::CMD_PROCEED);
nav_observer.Wait();
}
virtual void DontProceedThroughInterstitial(WebContents* tab) {
SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED);
}
void SendInterstitialCommand(
WebContents* tab,
security_interstitials::SecurityInterstitialCommand command) {
std::string javascript;
switch (command) {
case security_interstitials::CMD_DONT_PROCEED: {
javascript = "window.certificateErrorPageController.dontProceed();";
break;
}
case security_interstitials::CMD_PROCEED: {
javascript = "window.certificateErrorPageController.proceed();";
break;
}
case security_interstitials::CMD_SHOW_MORE_SECTION: {
javascript = "window.certificateErrorPageController.showMoreSection();";
break;
}
case security_interstitials::CMD_OPEN_HELP_CENTER: {
javascript = "window.certificateErrorPageController.openHelpCenter();";
break;
}
case security_interstitials::CMD_OPEN_DIAGNOSTIC: {
javascript = "window.certificateErrorPageController.openDiagnostic();";
break;
}
case security_interstitials::CMD_RELOAD: {
javascript = "window.certificateErrorPageController.reload();";
break;
}
case security_interstitials::CMD_OPEN_DATE_SETTINGS: {
javascript =
"window.certificateErrorPageController.openDateSettings();";
break;
}
case security_interstitials::CMD_OPEN_LOGIN: {
javascript = "window.certificateErrorPageController.openLogin();";
break;
}
case security_interstitials::CMD_DO_REPORT: {
javascript = "window.certificateErrorPageController.doReport();";
break;
}
case security_interstitials::CMD_DONT_REPORT: {
javascript = "window.certificateErrorPageController.dontReport();";
break;
}
case security_interstitials::CMD_OPEN_REPORTING_PRIVACY: {
javascript =
"window.certificateErrorPageController.openReportingPrivacy();";
break;
}
case security_interstitials::CMD_OPEN_WHITEPAPER: {
javascript = "window.certificateErrorPageController.openWhitepaper();";
break;
}
case security_interstitials::CMD_REPORT_PHISHING_ERROR: {
javascript =
"window.certificateErrorPageController.reportPhishingError();";
break;
}
default: {
// Other values in the enum are not used by these tests, and don't
// have a Javascript equivalent that can be called here.
NOTREACHED();
}
}
ASSERT_TRUE(content::ExecJs(tab, javascript));
return;
}
network::mojom::NetworkContextParamsPtr CreateDefaultNetworkContextParams() {
return g_browser_process->system_network_context_manager()
->CreateDefaultNetworkContextParams();
}
static std::string GetFilePathWithHostAndPortReplacement(
const std::string& original_file_path,
const net::HostPortPair& host_port_pair) {
base::StringPairs replacement_text;
replacement_text.push_back(
make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
return net::test_server::GetFilePathWithReplacements(original_file_path,
replacement_text);
}
static std::string GetTopFramePath(
const net::EmbeddedTestServer& http_server,
const net::EmbeddedTestServer& good_https_server,
const net::EmbeddedTestServer& bad_https_server) {
// The "frame_left.html" page contained in the top_frame.html page contains
// <a href>'s to three different servers. This sets up all of the
// replacement text to work with test servers which listen on ephemeral
// ports.
GURL http_url = http_server.GetURL("/ssl/google.html");
GURL good_https_url = good_https_server.GetURL("/ssl/google.html");
GURL bad_https_url = bad_https_server.GetURL("/ssl/bad_iframe.html");
base::StringPairs replacement_text_frame_left;
replacement_text_frame_left.push_back(
make_pair("REPLACE_WITH_HTTP_PORT", http_url.port()));
replacement_text_frame_left.push_back(
make_pair("REPLACE_WITH_GOOD_HTTPS_PAGE", good_https_url.spec()));
replacement_text_frame_left.push_back(
make_pair("REPLACE_WITH_BAD_HTTPS_PAGE", bad_https_url.spec()));
std::string frame_left_path = net::test_server::GetFilePathWithReplacements(
"frame_left.html", replacement_text_frame_left);
// Substitute the generated frame_left URL into the top_frame page.
base::StringPairs replacement_text_top_frame;
replacement_text_top_frame.push_back(
make_pair("REPLACE_WITH_FRAME_LEFT_PATH", frame_left_path));
return net::test_server::GetFilePathWithReplacements(
"/ssl/top_frame.html", replacement_text_top_frame);
}
security_interstitials::SecurityInterstitialPage* GetInterstitialPage(
WebContents* tab) {
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
if (!helper)
return nullptr;
return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting();
}
// Helper function for TestInterstitialLinksOpenInNewTab. Implemented as a
// test fixture method because the whole test fixture class is friended by
// SSLBlockingPage.
security_interstitials::SecurityInterstitialControllerClient*
GetControllerClientFromSSLBlockingPage(SSLBlockingPage* ssl_interstitial) {
return ssl_interstitial->controller();
}
// Helper function that checks that after proceeding through an interstitial,
// the app window is closed, a new tab with the app URL is opened, and there
// is no interstitial.
void ProceedThroughInterstitialInAppAndCheckNewTabOpened(
Browser* app_browser,
const GURL& app_url) {
Profile* profile = browser()->profile();
size_t num_browsers = chrome::GetBrowserCount(profile);
EXPECT_EQ(app_browser, chrome::FindLastActive());
int num_tabs = browser()->tab_strip_model()->count();
ProceedThroughInterstitial(
app_browser->tab_strip_model()->GetActiveWebContents());
EXPECT_EQ(--num_browsers, chrome::GetBrowserCount(profile));
EXPECT_EQ(browser(), chrome::FindLastActive());
EXPECT_EQ(++num_tabs, browser()->tab_strip_model()->count());
WebContents* new_tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(new_tab));
ssl_test_util::CheckAuthenticationBrokenState(
new_tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
EXPECT_EQ(app_url, new_tab->GetVisibleURL());
}
// network::mojom::SSLConfigClient implementation.
void OnSSLConfigUpdated(network::mojom::SSLConfigPtr ssl_config) override {
last_ssl_config_ = *ssl_config;
}
protected:
typedef net::SpawnedTestServer::SSLOptions SSLOptions;
// Navigates to an interstitial and clicks through the certificate
// error; then navigates to a page at |path| that loads unsafe content.
void SetUpUnsafeContentsWithUserException(const std::string& path) {
ASSERT_TRUE(https_server_.Start());
// Note that it is necessary to user https_server_mismatched_ here over the
// other invalid cert servers. This is because the test relies on the two
// servers having different hosts since SSL exceptions are per-host, not per
// origin, and https_server_mismatched_ uses 'localhost' rather than
// '127.0.0.1'.
ASSERT_TRUE(https_server_mismatched_.Start());
// Navigate to an unsafe site. Proceed with interstitial page to indicate
// the user approves the bad certificate.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/blank_page.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID,
AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
path, https_server_mismatched_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
}
void UpdateChromePolicy(const policy::PolicyMap& policies) {
policy_provider_.UpdateChromePolicy(policies);
ASSERT_TRUE(base::CurrentThread::Get());
base::RunLoop().RunUntilIdle();
content::FlushNetworkServiceInstanceForTesting();
}
void RunOnIOThreadBlocking(base::OnceClosure task) {
base::RunLoop run_loop;
content::GetIOThreadTaskRunner({})->PostTaskAndReply(
FROM_HERE, std::move(task), run_loop.QuitClosure());
run_loop.Run();
}
net::EmbeddedTestServer https_server_;
net::EmbeddedTestServer https_server_expired_;
net::EmbeddedTestServer https_server_mismatched_;
net::EmbeddedTestServer https_server_sha1_;
net::EmbeddedTestServer https_server_common_name_only_;
net::SpawnedTestServer wss_server_expired_;
net::SpawnedTestServer wss_server_mismatched_;
testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
network::mojom::SSLConfig last_ssl_config_;
mojo::Receiver<network::mojom::SSLConfigClient> receiver_{this};
};
class SSLUITest : public SSLUITestBase {
public:
SSLUITest() : SSLUITestBase() {
scoped_feature_list_.InitWithFeatures(
/* enabled_features */ {},
/* disabled_features */ {blink::features::kMixedContentAutoupgrade});
}
SSLUITest(const SSLUITest&) = delete;
SSLUITest& operator=(const SSLUITest&) = delete;
protected:
void DontProceedThroughInterstitial(WebContents* tab) override {
content::TestNavigationObserver nav_observer(tab, 1);
SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED);
nav_observer.Wait();
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
class SSLUITestBlock : public SSLUITest {
public:
SSLUITestBlock() : SSLUITest() {}
// Browser will not run insecure content.
void SetUpCommandLine(base::CommandLine* command_line) override {
// By overriding SSLUITest, we won't apply the flag that allows running
// insecure content.
}
};
class SSLUITestIgnoreCertErrors : public SSLUITest {
public:
SSLUITestIgnoreCertErrors() : SSLUITest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
SSLUITest::SetUpCommandLine(command_line);
// Browser will ignore certificate errors.
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
}
};
static std::string MakeCertSPKIFingerprint(net::X509Certificate* cert) {
return base::Base64Encode(GetSPKIHash(cert->cert_buffer()));
}
class SSLUITestIgnoreCertErrorsBySPKIHTTPS : public SSLUITest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
SSLUITest::SetUpCommandLine(command_line);
std::string whitelist_flag = MakeCertSPKIFingerprint(
https_server_mismatched_.GetCertificate().get());
// Browser will ignore certificate errors for chains matching one of the
// public keys from the list.
command_line->AppendSwitchASCII(
network::switches::kIgnoreCertificateErrorsSPKIList, whitelist_flag);
}
};
class SSLUITestIgnoreCertErrorsBySPKIWSS : public SSLUITest {
public:
SSLUITestIgnoreCertErrorsBySPKIWSS() : SSLUITest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
SSLUITest::SetUpCommandLine(command_line);
std::string whitelist_flag =
MakeCertSPKIFingerprint(wss_server_expired_.GetCertificate().get());
// Browser will ignore certificate errors for chains matching one of the
// public keys from the list.
command_line->AppendSwitchASCII(
network::switches::kIgnoreCertificateErrorsSPKIList, whitelist_flag);
}
};
class SSLUITestIgnoreLocalhostCertErrors : public SSLUITest {
public:
SSLUITestIgnoreLocalhostCertErrors() : SSLUITest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
SSLUITest::SetUpCommandLine(command_line);
// Browser will ignore certificate errors on localhost.
command_line->AppendSwitch(switches::kAllowInsecureLocalhost);
}
};
class SSLUITestHSTS : public SSLUITest {
public:
void SetUpOnMainThread() override {
SSLUITest::SetUpOnMainThread();
ssl_test_util::SetHSTSForHostName(browser()->profile(), kHstsTestHostName);
}
};
class SSLUITestReduceSubresourceNotifications : public SSLUITestBase {
public:
SSLUITestReduceSubresourceNotifications() {
scoped_feature_list_.InitWithFeatures(
/* enabled_features */ {features::kReduceSubresourceResponseStartedIPC},
/* disabled_features */ {blink::features::kMixedContentAutoupgrade});
}
SSLUITestReduceSubresourceNotifications(
const SSLUITestReduceSubresourceNotifications&) = delete;
SSLUITestReduceSubresourceNotifications& operator=(
const SSLUITestReduceSubresourceNotifications&) = delete;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Visits a regular page over http.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTP) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Visits a page over http which includes broken https resources (status should
// be OK).
// TODO(jcampan): test that bad HTTPS content is blocked (otherwise we'll give
// the secure cookies away!).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPWithBrokenHTTPSResource) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_contents.html",
https_server_expired_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(replacement_path)));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Tests that after loading mixed content and then making a same-document
// navigation, the mixed content security indicator remains. See
// https://crbug.com/959571.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestMixedContentWithSamePageNavigation) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to a secure page (no mixed content).
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Add a mixed form after a same-document navigation.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html#foo")));
ssl_test_util::SecurityStateWebContentsObserver observer(tab);
ASSERT_NE(false, content::EvalJs(tab,
"var f = document.createElement('form');"
"f.action = 'http://foo.test';"
"document.body.appendChild(f)"));
observer.WaitForDidChangeVisibleSecurityState();
// Since mixed forms trigger their own warning, we display the lock icon on
// otherwise secure sites with an insecure form.
security_state::SecurityLevel expected_level = security_state::SECURE;
ssl_test_util::CheckSecurityState(
tab, CertError::NONE, expected_level,
AuthState::DISPLAYED_FORM_WITH_INSECURE_ACTION);
// Go back (which should also be a same-document navigation) and test that the
// security indicator is still downgraded because of the mixed form.
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckSecurityState(
tab, CertError::NONE, expected_level,
AuthState::DISPLAYED_FORM_WITH_INSECURE_ACTION);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSWithInsecureContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_content.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Tests that the NavigationEntry gets marked as active mixed content,
// even if there is a certificate error. Regression test for
// https://crbug.com/593950.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSWithActiveInsecureContent) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
// Navigate to a page with a certificate error and click through the
// interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
// Load an insecure (http://) script. When it is loaded, check that the page
// is marked as having run insecure content.
SSLContentStatusObserver observer(tab,
content::SSLStatus::RAN_INSECURE_CONTENT);
ASSERT_NE(false,
content::EvalJs(tab,
"var s = document.createElement('script');"
"s.src = 'http://does-not-exist.test/foo.js';"
"document.body.appendChild(s)"));
observer.WaitForSSLContentStatusFlag();
// Now check that the page is marked as both having a cert error and having
// run insecure content.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::RAN_INSECURE_CONTENT);
}
// Tests that when a subframe commits a main resource with a certificate error,
// the navigation entry is marked as insecure.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrors, SubframeHasCertError) {
ASSERT_TRUE(https_server_mismatched_.Start());
// Load a page with a data: favicon URL to suppress a favicon request. A
// favicon request can cause the navigation entry to get marked as having run
// insecure content (favicons are treated as active content), which would
// interfere with the test expectation below.
GURL main_frame_url =
https_server_mismatched_.GetURL("a.test", "/data_favicon.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
EXPECT_FALSE(
tab->GetController().GetLastCommittedEntry()->GetSSL().content_status &
content::SSLStatus::RAN_CONTENT_WITH_CERT_ERRORS);
GURL subframe_url =
https_server_mismatched_.GetURL("b.test", "/data_favicon.html");
content::TestNavigationObserver iframe_observer(tab);
EXPECT_TRUE(content::ExecJs(
tab, content::JsReplace("var i = document.createElement('iframe');"
"i.src = $1;"
"document.body.appendChild(i);",
subframe_url.spec())));
iframe_observer.Wait();
EXPECT_TRUE(
tab->GetController().GetLastCommittedEntry()->GetSSL().content_status &
content::SSLStatus::RAN_CONTENT_WITH_CERT_ERRORS);
}
namespace {
// A WebContentsObserver that allows the user to wait for a same-document
// navigation. Tests using this observer will fail if a non-same-document
// navigation completes after calling WaitForSameDocumentNavigation.
class SameDocumentNavigationObserver : public content::WebContentsObserver {
public:
explicit SameDocumentNavigationObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
~SameDocumentNavigationObserver() override = default;
void WaitForSameDocumentNavigation() { run_loop_.Run(); }
// WebContentsObserver:
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override {
ASSERT_TRUE(navigation_handle->IsSameDocument());
run_loop_.Quit();
}
private:
base::RunLoop run_loop_;
};
} // namespace
// Tests that the mixed content flags are reset when going back to an existing
// navigation entry that had mixed content. Regression test for
// https://crbug.com/750649.
IN_PROC_BROWSER_TEST_F(SSLUITest, GoBackToMixedContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
// Navigate to a URL and dynamically load mixed content.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
ssl_test_util::SecurityStateWebContentsObserver observer(tab);
ASSERT_TRUE(content::ExecJs(tab,
"var i = document.createElement('img');"
"i.src = 'http://example.test';"
"document.body.appendChild(i);"));
observer.WaitForDidChangeVisibleSecurityState();
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
// Now navigate somewhere else, and then back to the page that dynamically
// loaded mixed content.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
EXPECT_TRUE(content::WaitForLoadStop(tab));
// After going back, the mixed content indicator should no longer be present.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Tests that the mixed content flags are not reset for an in-page navigation.
IN_PROC_BROWSER_TEST_F(SSLUITest, MixedContentWithSameDocumentNavigation) {
ASSERT_TRUE(https_server_.Start());
// Navigate to a URL and dynamically load mixed content.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
ssl_test_util::SecurityStateWebContentsObserver security_state_observer(tab);
ASSERT_TRUE(content::ExecJs(tab,
"var i = document.createElement('img');"
"i.src = 'http://example.test';"
"document.body.appendChild(i);"));
security_state_observer.WaitForDidChangeVisibleSecurityState();
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
// Initiate a same-document navigation and check that the page is still
// marked as having displayed mixed content.
SameDocumentNavigationObserver navigation_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html#foo")));
navigation_observer.WaitForSameDocumentNavigation();
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Tests that the WebContents's flag for displaying content with cert
// errors get cleared upon navigation.
IN_PROC_BROWSER_TEST_F(SSLUITest,
DisplayedContentWithCertErrorsClearedOnNavigation) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
// Navigate to a page with a certificate error and click through the
// interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
// Add a subresource with a certificate error and check that it's recorded
// correctly. We wait specifically for the DidDisplayContentWithCertErrors
// event (rather than a DidChangeVisibleSecurityState event) because the
// page's favicon is loaded as active content and the notification about that
// can interfere with the visible security state change that we're observing
// here.
SSLContentStatusObserver observer(
tab, content::SSLStatus::DISPLAYED_CONTENT_WITH_CERT_ERRORS);
ASSERT_NE(false, content::EvalJs(tab,
"var i = document.createElement('img');"
"i.src = 'ssl/google_files/logo.gif';"
"document.body.appendChild(i)"));
observer.WaitForSSLContentStatusFlag();
// Navigate away to a different page, and check that the flag gets cleared.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
content::NavigationEntry* entry = tab->GetController().GetVisibleEntry();
ASSERT_TRUE(entry);
EXPECT_FALSE(entry->GetSSL().content_status &
content::SSLStatus::DISPLAYED_CONTENT_WITH_CERT_ERRORS);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSMetricsReporting_Proceed) {
ASSERT_TRUE(https_server_expired_.Start());
base::HistogramTester histograms;
const std::string decision_histogram =
"interstitial.ssl_overridable.decision";
const std::string interaction_histogram =
"interstitial.ssl_overridable.interaction";
// Histograms should start off empty.
histograms.ExpectTotalCount(decision_histogram, 0);
histograms.ExpectTotalCount(interaction_histogram, 0);
// After navigating to the page, the totals should be set.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(
browser()->tab_strip_model()->GetActiveWebContents()));
histograms.ExpectTotalCount(decision_histogram, 1);
histograms.ExpectBucketCount(decision_histogram,
security_interstitials::MetricsHelper::SHOW, 1);
histograms.ExpectTotalCount(interaction_histogram, 2);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::TOTAL_VISITS, 1);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::SHOW_ENHANCED_PROTECTION, 1);
// Decision should be recorded.
SendInterstitialCommand(browser()->tab_strip_model()->GetActiveWebContents(),
security_interstitials::CMD_PROCEED);
histograms.ExpectTotalCount(decision_histogram, 2);
histograms.ExpectBucketCount(
decision_histogram, security_interstitials::MetricsHelper::PROCEED, 1);
histograms.ExpectTotalCount(interaction_histogram, 2);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::TOTAL_VISITS, 1);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSMetricsReporting_DontProceed) {
ASSERT_TRUE(https_server_expired_.Start());
base::HistogramTester histograms;
const std::string decision_histogram =
"interstitial.ssl_overridable.decision";
const std::string interaction_histogram =
"interstitial.ssl_overridable.interaction";
// Histograms should start off empty.
histograms.ExpectTotalCount(decision_histogram, 0);
histograms.ExpectTotalCount(interaction_histogram, 0);
// After navigating to the page, the totals should be set.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(
browser()->tab_strip_model()->GetActiveWebContents()));
histograms.ExpectTotalCount(decision_histogram, 1);
histograms.ExpectBucketCount(decision_histogram,
security_interstitials::MetricsHelper::SHOW, 1);
histograms.ExpectTotalCount(interaction_histogram, 2);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::TOTAL_VISITS, 1);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::SHOW_ENHANCED_PROTECTION, 1);
// Decision should be recorded.
SendInterstitialCommand(browser()->tab_strip_model()->GetActiveWebContents(),
security_interstitials::CMD_DONT_PROCEED);
histograms.ExpectTotalCount(decision_histogram, 2);
histograms.ExpectBucketCount(
decision_histogram, security_interstitials::MetricsHelper::DONT_PROCEED,
1);
histograms.ExpectTotalCount(interaction_histogram, 2);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::TOTAL_VISITS, 1);
}
// Visits a page over OK https:
IN_PROC_BROWSER_TEST_F(SSLUITest, TestOKHTTPS) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Visits a page with https error and proceed:
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndProceed) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
EXPECT_EQ(https_server_expired_.GetURL("/ssl/google.html"),
tab->GetVisibleURL());
}
// Visits a page with https error and checks favicon is not displayed:
IN_PROC_BROWSER_TEST_F(SSLUITest, TestNoFaviconOnInterstitial) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
EXPECT_FALSE(
browser()->tab_strip_model()->delegate()->ShouldDisplayFavicon(tab));
}
class SSLUITestWithWebApps : public SSLUITest {
public:
Browser* InstallAndOpenTestWebApp(const GURL& start_url) {
auto web_app_info =
web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(start_url);
web_app_info->scope = start_url.GetWithoutFilename();
web_app_info->title = u"Test app";
web_app_info->description = u"Test description";
Profile* profile = browser()->profile();
webapps::AppId app_id =
web_app::test::InstallWebApp(profile, std::move(web_app_info));
Browser* app_browser = web_app::LaunchWebAppBrowserAndWait(profile, app_id);
return app_browser;
}
private:
web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
};
// Visits a page in an app window with https error and proceed:
// Disabled due to flaky failures; see https://crbug.com/1156046.
IN_PROC_BROWSER_TEST_F(SSLUITestWithWebApps,
DISABLED_InAppTestHTTPSExpiredCertAndProceed) {
ASSERT_TRUE(https_server_expired_.Start());
const GURL app_url = https_server_expired_.GetURL("/ssl/google.html");
Browser* app_browser = InstallAndOpenTestWebApp(app_url);
WebContents* app_tab = app_browser->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(app_tab));
ssl_test_util::CheckAuthenticationBrokenState(
app_tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitialInAppAndCheckNewTabOpened(app_browser, app_url);
}
// Visits a page with https error and proceed. Then open the app and proceed.
IN_PROC_BROWSER_TEST_F(SSLUITestWithWebApps,
InAppTestHTTPSExpiredCertAndPreviouslyProceeded) {
ASSERT_TRUE(https_server_expired_.Start());
const GURL app_url = https_server_expired_.GetURL("/ssl/google.html");
// Go through the interstitial in a regular browser tab.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), app_url));
WebContents* initial_tab =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(initial_tab));
ssl_test_util::CheckAuthenticationBrokenState(
initial_tab, net::CERT_STATUS_DATE_INVALID,
AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(initial_tab);
ssl_test_util::CheckAuthenticationBrokenState(
initial_tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
Browser* app_browser = InstallAndOpenTestWebApp(app_url);
// Apps are not allowed to have SSL errors, so the interstitial should be
// showing even though the user proceeded through it in a regular tab.
WebContents* app_tab = app_browser->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(app_tab));
// TODO(crbug.com/40735115): Apps are not setting the right security state in
// this case, so we only check the presence of the interstitial (inside Wait
// ForInterstitial) and the behavior after clicking through.
// After the bug is fixed, add a call to CheckAuthenticationBrokenState
// with net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL
// parameters.
ProceedThroughInterstitialInAppAndCheckNewTabOpened(app_browser, app_url);
}
// Visits a page with https error and don't proceed (and ensure we can still
// navigate at that point):
IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialCrossSiteNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_mismatched_.Start());
// First navigate to an OK page.
GURL initial_url = https_server_.GetURL("/ssl/google.html");
ASSERT_EQ("127.0.0.1", initial_url.host());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Navigate from 127.0.0.1 to localhost so it triggers a
// cross-site navigation to make sure http://crbug.com/5800 is gone.
GURL cross_site_url = https_server_mismatched_.GetURL("/ssl/google.html");
ASSERT_EQ("localhost", cross_site_url.host());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), cross_site_url));
// An SSL interstitial should be showing.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID,
AuthState::SHOWING_INTERSTITIAL);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
// Simulate user clicking "Take me back".
DontProceedThroughInterstitial(tab);
// We should be back to the original good page.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Navigate to a new page to make sure bug 5800 is fixed.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
}
// Test that localhost pages don't show an interstitial.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreLocalhostCertErrors,
TestNoInterstitialOnLocalhost) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to a localhost page.
GURL url = https_server_.GetURL("/ssl/page_with_subresource.html");
GURL::Replacements replacements;
std::string new_host("localhost");
replacements.SetHostStr(new_host);
url = url.ReplaceComponents(replacements);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
// We should see no interstitial, but we should have an error
// (red-crossed-out-https) in the URL bar.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
// We should see that the script tag in the page loaded and ran (and
// wasn't blocked by the certificate error).
std::u16string title;
std::u16string expected_title = u"This script has loaded";
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(title, expected_title);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorCausedByClockUsingBuildTime) {
ASSERT_TRUE(https_server_expired_.Start());
// Set up the build and current clock times to be more than a year apart.
std::unique_ptr<base::SimpleTestClock> mock_clock(
new base::SimpleTestClock());
mock_clock->SetNow(base::Time::NowFromSystemTime());
mock_clock->Advance(base::Days(367));
SSLErrorHandler::SetClockForTesting(mock_clock.get());
ssl_errors::SetBuildTimeForTesting(base::Time::NowFromSystemTime());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
WebContents* clock_tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(
chrome_browser_interstitials::IsShowingBadClockInterstitial(clock_tab));
ssl_test_util::CheckSecurityState(clock_tab, net::CERT_STATUS_DATE_INVALID,
security_state::DANGEROUS,
AuthState::SHOWING_INTERSTITIAL);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorCausedByClockUsingNetwork) {
ASSERT_TRUE(https_server_expired_.Start());
// Set network forward ten minutes, which is sufficient to trigger
// the interstitial.
g_browser_process->network_time_tracker()->UpdateNetworkTime(
base::Time::Now() + base::Minutes(10),
base::Milliseconds(1), /* resolution */
base::Milliseconds(500), /* latency */
base::TimeTicks::Now() /* posting time of this update */);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
WebContents* clock_tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(
chrome_browser_interstitials::IsShowingBadClockInterstitial(clock_tab));
ssl_test_util::CheckSecurityState(clock_tab, net::CERT_STATUS_DATE_INVALID,
security_state::DANGEROUS,
AuthState::SHOWING_INTERSTITIAL);
}
// Visits a page with https error and then goes back using Browser::GoBack.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndGoBackViaButton) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
// First navigate to an HTTP page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Now go to a bad HTTPS page that shows an interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Simulate user clicking on back button (crbug.com/39248).
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
EXPECT_TRUE(content::WaitForLoadStop(tab));
// We should be back at the original good page.
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
}
// Visits a page with https error and then goes back using GoToOffset.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndGoBackViaMenu) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
// First navigate to an HTTP page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Now go to a bad HTTPS page that shows an interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Simulate user clicking and holding on back button (crbug.com/37215). With
// committed interstitials enabled, this triggers a navigation.
content::TestNavigationObserver nav_observer(tab);
tab->GetController().GoToOffset(-1);
nav_observer.Wait();
// We should be back at the original good page.
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
}
// Visits a page with https error and then goes back using the DONT_PROCEED
// interstitial command.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertGoBackUsingCommand) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
// First navigate to an HTTP page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Now go to a bad HTTPS page that shows an interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
content::LoadStopObserver observer(tab);
SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED);
observer.Wait();
// We should be back at the original good page.
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
}
// Visits a page that uses a SHA-1 leaf certificate, which should be rejected
// by default.
IN_PROC_BROWSER_TEST_F(SSLUITest, SHA1IsDefaultDisabled) {
EXPECT_FALSE(last_ssl_config_.sha1_local_anchors_enabled);
EXPECT_FALSE(CreateDefaultNetworkContextParams()
->initial_ssl_config->sha1_local_anchors_enabled);
ASSERT_TRUE(https_server_sha1_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_sha1_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
browser()->tab_strip_model()->GetActiveWebContents(),
net::CERT_STATUS_WEAK_SIGNATURE_ALGORITHM,
AuthState::SHOWING_INTERSTITIAL);
}
// Visit a HTTP page which request WSS connection to a server providing invalid
// certificate. Close the page while WSS connection waits for SSLManager's
// response from UI thread.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestWSSInvalidCertAndClose) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(wss_server_expired_.Start());
// Setup page title observer.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TitleWatcher watcher(tab, u"PASS");
watcher.AlsoWaitForTitle(u"FAIL");
// Create GURLs to test pages.
std::string wss_close_url_path = base::StringPrintf(
"%s?%d",
embedded_test_server()->GetURL("/ssl/wss_close.html").spec().c_str(),
wss_server_expired_.host_port_pair().port());
GURL wss_close_url(wss_close_url_path);
std::string wss_loop_url_path = base::StringPrintf(
"%s?%d",
embedded_test_server()->GetURL("/ssl/wss_close_loop.html").spec().c_str(),
wss_server_expired_.host_port_pair().port());
GURL wss_loop_url(wss_loop_url_path);
// Create tabs and visit pages which keep on creating wss connections.
std::array<WebContents*, 16> tabs;
for (int i = 0; i < 16; ++i) {
tabs[i] = chrome::AddSelectedTabWithURL(browser(), wss_loop_url,
ui::PAGE_TRANSITION_LINK);
}
chrome::SelectNextTab(browser());
// Visit a page which waits for one TLS handshake failure.
// The title will be changed to 'PASS'.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), wss_close_url));
const std::u16string result = watcher.WaitAndGetTitle();
EXPECT_TRUE(base::EqualsCaseInsensitiveASCII(result, "pass"));
// Close tabs which contains the test page.
for (int i = 0; i < 16; ++i)
chrome::CloseWebContents(browser(), tabs[i], false);
chrome::CloseWebContents(browser(), tab, false);
}
// Visit a HTTPS page and proceeds despite an invalid certificate. The page
// requests WSS connection to the same origin host to check if WSS connection
// share certificates policy with HTTPS correcly.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestWSSInvalidCert) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(wss_server_expired_.Start());
// Setup page title observer.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TitleWatcher watcher(tab, u"PASS");
watcher.AlsoWaitForTitle(u"FAIL");
// Visit bad HTTPS page.
GURL::Replacements replacements;
replacements.SetSchemeStr("https");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), wss_server_expired_.GetURL("connect_check.html")
.ReplaceComponents(replacements)));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Proceed anyway.
ProceedThroughInterstitial(tab);
// Test page run a WebSocket wss connection test. The result will be shown
// as page title.
const std::u16string result = watcher.WaitAndGetTitle();
EXPECT_TRUE(base::EqualsCaseInsensitiveASCII(result, "pass"));
}
// Data URLs should always be marked as non-secure.
IN_PROC_BROWSER_TEST_F(SSLUITest, MarkDataAsNonSecure) {
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
SecurityStateTabHelper* helper =
SecurityStateTabHelper::FromWebContents(contents);
ASSERT_TRUE(helper);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("data:text/plain,hello")));
EXPECT_EQ(security_state::WARNING, helper->GetSecurityLevel());
}
#if BUILDFLAG(USE_NSS_CERTS)
class SSLUITestWithClientCert : public SSLUITestBase {
public:
SSLUITestWithClientCert() : cert_db_(nullptr) {}
void SetUpOnMainThread() override {
SSLUITestBase::SetUpOnMainThread();
base::RunLoop loop;
NssServiceFactory::GetForContext(browser()->profile())
->UnsafelyGetNSSCertDatabaseForTesting(
base::BindOnce(&SSLUITestWithClientCert::DidGetCertDatabase,
base::Unretained(this), &loop));
loop.Run();
}
protected:
void DidGetCertDatabase(base::RunLoop* loop, net::NSSCertDatabase* cert_db) {
cert_db_ = cert_db;
loop->Quit();
}
raw_ptr<net::NSSCertDatabase> cert_db_;
};
// SSL client certificate tests are only enabled when using NSS for private key
// storage, as only NSS can avoid modifying global machine state when testing.
// See http://crbug.com/51132
// Visit a HTTPS page which requires client cert authentication. The client
// cert will be selected automatically, then a test which uses WebSocket runs.
//
// TODO(crbug.com/40811167): disabled because of race in when certs
// are incorporated.
IN_PROC_BROWSER_TEST_F(SSLUITestWithClientCert, DISABLED_TestWSSClientCert) {
// Import a client cert for test.
crypto::ScopedPK11Slot public_slot = cert_db_->GetPublicSlot();
std::string pkcs12_data;
base::FilePath cert_path = net::GetTestCertsDirectory().Append(
FILE_PATH_LITERAL("websocket_client_cert.p12"));
{
base::ScopedAllowBlockingForTesting allow_blocking;
EXPECT_TRUE(base::ReadFileToString(cert_path, &pkcs12_data));
}
EXPECT_EQ(net::OK,
cert_db_->ImportFromPKCS12(public_slot.get(), pkcs12_data,
std::u16string(), true, nullptr));
// Start WebSocket test server with TLS and client cert authentication.
net::SpawnedTestServer::SSLOptions options(
net::SpawnedTestServer::SSLOptions::CERT_OK);
options.request_client_certificate = true;
base::FilePath ca_path = net::GetTestCertsDirectory().Append(
FILE_PATH_LITERAL("websocket_cacert.pem"));
options.client_authorities.push_back(ca_path);
net::SpawnedTestServer wss_server(net::SpawnedTestServer::TYPE_WSS, options,
net::GetWebSocketTestDataDirectory());
ASSERT_TRUE(wss_server.Start());
GURL::Replacements replacements;
replacements.SetSchemeStr("https");
GURL url =
wss_server.GetURL("connect_check.html").ReplaceComponents(replacements);
// Setup page title observer.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TitleWatcher watcher(tab, u"PASS");
watcher.AlsoWaitForTitle(u"FAIL");
// Add an entry into AutoSelectCertificateForUrls policy for automatic client
// cert selection.
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
base::Value::Dict filter;
filter.SetByDottedPath("ISSUER.CN", "pywebsocket");
base::Value::List filters;
filters.Append(std::move(filter));
base::Value::Dict setting;
setting.Set("filters", std::move(filters));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(std::move(setting)));
// Visit a HTTPS page which requires client certs.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Test page runs a WebSocket wss connection test. The result will be shown
// as page title.
const std::u16string result = watcher.WaitAndGetTitle();
EXPECT_TRUE(base::EqualsCaseInsensitiveASCII(result, "pass"));
}
#endif // BUILDFLAG(USE_NSS_CERTS)
// A stub ClientCertStore that returns a FakeClientCertIdentity.
class ClientCertStoreStub : public net::ClientCertStore {
public:
explicit ClientCertStoreStub(net::ClientCertIdentityList list)
: list_(std::move(list)) {}
~ClientCertStoreStub() override = default;
// net::ClientCertStore:
void GetClientCerts(
scoped_refptr<const net::SSLCertRequestInfo> cert_request_info,
ClientCertListCallback callback) override {
std::move(callback).Run(std::move(list_));
}
private:
net::ClientCertIdentityList list_;
};
std::unique_ptr<net::ClientCertStore> CreateCertStore() {
base::FilePath certs_dir = net::GetTestCertsDirectory();
net::ClientCertIdentityList cert_identity_list;
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::unique_ptr<net::FakeClientCertIdentity> cert_identity =
net::FakeClientCertIdentity::CreateFromCertAndKeyFiles(
certs_dir, "client_1.pem", "client_1.pk8");
EXPECT_TRUE(cert_identity.get());
if (cert_identity)
cert_identity_list.push_back(std::move(cert_identity));
}
return std::unique_ptr<net::ClientCertStore>(
new ClientCertStoreStub(std::move(cert_identity_list)));
}
std::unique_ptr<net::ClientCertStore> CreateFailSigningCertStore() {
base::FilePath certs_dir = net::GetTestCertsDirectory();
net::ClientCertIdentityList cert_identity_list;
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::unique_ptr<net::FakeClientCertIdentity> cert_identity =
net::FakeClientCertIdentity::CreateFromCertAndFailSigning(
certs_dir, "client_1.pem");
EXPECT_TRUE(cert_identity.get());
if (cert_identity)
cert_identity_list.push_back(std::move(cert_identity));
}
return std::unique_ptr<net::ClientCertStore>(
new ClientCertStoreStub(std::move(cert_identity_list)));
}
std::unique_ptr<net::ClientCertStore> CreateEmptyCertStore() {
return std::unique_ptr<net::ClientCertStore>(new ClientCertStoreStub({}));
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrowserUseClientCertStore) {
// Make the browser use the ClientCertStoreStub instead of the regular one.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateCertStore));
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
GURL https_url =
https_server.GetURL("/ssl/browser_use_client_cert_store.html");
// Add an entry into AutoSelectCertificateForUrls policy for automatic client
// cert selection.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
base::Value::List filters;
filters.Append(base::Value::Dict());
base::Value::Dict setting;
setting.Set("filters", std::move(filters));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
https_url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(std::move(setting)));
// Visit a HTTPS page which requires client certs.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
EXPECT_EQ("pass", tab->GetLastCommittedURL().ref());
}
// Tests that requests from service workers can also use certificates
// auto-selected by policy.
// https://crbug.com/1417601.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestServiceWorkerRequestsUseClientCertStore) {
// Make the browser use the ClientCertStoreStub instead of the regular one.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateCertStore));
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
{
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES,
ssl_config);
}
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
// We set up a page that installs a service worker to perform a fetch to
// a separate, cross-origin resource. We need this to be a cross-origin
// because visiting the first site (to install the service worker) requires
// a cert to be present, so subsequent fetches to that site will succeed
// without a separate certificate prompt.
// Note: These domain names need to match those in
// //net/data/ssl/certificates/test_names.pem.
GURL requestor_url =
https_server.GetURL("a.test", "/ssl/service_worker_fetch/page.html");
GURL target_url =
https_server.GetURL("b.test", "/ssl/service_worker_fetch/target.txt");
// Add an entry into AutoSelectCertificateForUrls policy for automatic client
// cert selection for both the requestor and target URLs.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
base::Value::List filters;
filters.Append(base::Value::Dict());
base::Value::Dict setting;
setting.Set("filters", std::move(filters));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
requestor_url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(setting.Clone()));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
target_url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(std::move(setting)));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), requestor_url));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Check the navigation succeeded. The title check verifies we didn't e.g.
// get a privacy error.
EXPECT_EQ(requestor_url, web_contents->GetLastCommittedURL());
EXPECT_EQ(u"My Title", web_contents->GetTitle());
// Perform a fetch from a worker and validate that it succeeds.
EXPECT_EQ(
"text content\n",
content::EvalJs(web_contents,
content::JsReplace("doFetchInWorker($1);", target_url)));
}
// Tests that if an extension service worker requests a resource where a
// client cert is optional (not required) and there are no client certs, the
// request will continue without a certificate (as opposed to abort).
#if BUILDFLAG(ENABLE_EXTENSIONS) && !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(
SSLUITest,
TestExtensionServiceWorkerCanContinueWithoutACertificate) {
// TODO(https://crbug.com/40804030): Remove this when updated to use MV3.
extensions::ScopedTestMV2Enabler mv2_enabler;
// Make the browser use the ClientCertStoreStub instead of the regular one.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateEmptyCertStore));
// Set up an HTTPS server with optional client certs.
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
{
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES,
ssl_config);
}
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
// Load a test extension that will try to fetch the cross-origin resource.
static constexpr char kManifest[] =
R"({
"name": "Fetching Extension",
"manifest_version": 2,
"version": "0.1",
"background": {"service_worker": "background.js"}
})";
static constexpr char kBackgroundJs[] =
R"(async function doFetchAndReply(url) {
try {
let response = await fetch(url);
result = await response.text();
} catch (e) {
result = `Fetch error: ${e.toString()}`;
}
chrome.test.sendScriptResult(result);
})";
extensions::TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
Profile* const profile = browser()->profile();
extensions::ChromeTestExtensionLoader extension_loader(profile);
scoped_refptr<const extensions::Extension> extension =
extension_loader.LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
// Path to the cross-origin resource to fetch.
// Note: This domain name matches one in
// //net/data/ssl/certificates/test_names.pem.
GURL target_url =
https_server.GetURL("b.test", "/ssl/service_worker_fetch/target.txt");
// Try to fetch the resource from the extension. We have no client certs
// (we're using an empty cert store), so no certificates will be selected.
// Even so, the fetch should succeed. It continues without a certificate, and
// the certificate is optional.
base::Value fetch_result =
extensions::BackgroundScriptExecutor::ExecuteScript(
profile, extension->id(),
base::StringPrintf("doFetchAndReply('%s');",
target_url.spec().c_str()),
extensions::BackgroundScriptExecutor::ResultCapture::
kSendScriptResult);
EXPECT_EQ(fetch_result, "text content\n");
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
IN_PROC_BROWSER_TEST_F(SSLUITest, TestClientAuthSigningFails) {
// Make the browser use the ClientCertStoreStub instead of the regular one.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateFailSigningCertStore));
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
GURL https_url =
https_server.GetURL("/ssl/browser_use_client_cert_store.html");
// Add an entry into AutoSelectCertificateForUrls policy for automatic client
// cert selection.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
base::Value::List filters;
filters.Append(base::Value::Dict());
base::Value::Dict setting;
setting.Set("filters", std::move(filters));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
https_url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(std::move(setting)));
// Visit a HTTPS page which requires client certs.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
// Page should not load successfully.
EXPECT_EQ("", tab->GetLastCommittedURL().ref());
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestClientAuthContinueWithoutCert) {
// Make the browser use a ClientCertStoreStub that returns no certs.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateEmptyCertStore));
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
GURL https_url =
https_server.GetURL("/ssl/browser_use_client_cert_store.html");
// Visit a HTTPS page which requires client certs.
// The browser should automatically continue to the site without a client
// cert, since the ClientCertStore returns no certs.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Page should not load successfully.
EXPECT_EQ("", tab->GetLastCommittedURL().ref());
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestCertDBChangedFlushesClientAuthCache) {
// Make the browser use the ClientCertStoreStub instead of the regular one.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateCertStore));
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
https_server.ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(https_server.Start());
GURL https_url =
https_server.GetURL("/ssl/browser_use_client_cert_store.html");
// Add an entry into AutoSelectCertificateForUrls policy for automatic client
// cert selection.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
base::Value::List filters;
filters.Append(base::Value::Dict());
base::Value::Dict setting;
setting.Set("filters", std::move(filters));
HostContentSettingsMapFactory::GetForProfile(profile)
->SetWebsiteSettingDefaultScope(
https_url, GURL(), ContentSettingsType::AUTO_SELECT_CERTIFICATE,
base::Value(std::move(setting)));
// Visit a HTTPS page which requires client certs.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
EXPECT_EQ("pass", tab->GetLastCommittedURL().ref());
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), GURL("about:blank"), 1);
EXPECT_EQ("", tab->GetLastCommittedURL().ref());
// Now use a ClientCertStoreStub that always returns an empty list.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(
base::BindRepeating(&CreateEmptyCertStore));
// Visiting the page which requires client certs should still work (either
// due to the socket still being open, or due to the SSL client auth cache).
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
EXPECT_EQ("pass", tab->GetLastCommittedURL().ref());
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), GURL("about:blank"), 1);
EXPECT_EQ("", tab->GetLastCommittedURL().ref());
// Send an OnClientCertStoreChanged notification.
net::CertDatabase::GetInstance()->NotifyObserversClientCertStoreChanged();
content::FlushNetworkServiceInstanceForTesting();
// Visiting the page which requires client certs should fail, as the socket
// pool has been flushed and SSL client auth cache has been cleared due to
// the CertDBChanged observer.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
https_url, 1);
EXPECT_EQ("", tab->GetLastCommittedURL().ref());
}
// Open a page with a HTTPS error in a tab with no prior navigation (through a
// link with a blank target). This is to test that the lack of navigation entry
// does not cause any problems (it was causing a crasher, see
// http://crbug.com/19941).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorWithNoNavEntry) {
ASSERT_TRUE(https_server_expired_.Start());
const GURL url = https_server_expired_.GetURL("/ssl/google.htm");
WebContents* tab2 =
chrome::AddSelectedTabWithURL(browser(), url, ui::PAGE_TRANSITION_TYPED);
content::WaitForLoadStop(tab2);
// Verify our assumption that there was no prior navigation.
EXPECT_FALSE(chrome::CanGoBack(browser()));
// We should have an interstitial page showing.
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab2));
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBadHTTPSDownload) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
GURL url_non_dangerous = embedded_test_server()->GetURL("/title1.html");
GURL url_dangerous =
https_server_expired_.GetURL("/downloads/dangerous/dangerous.exe");
// Visit a non-dangerous page.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_non_dangerous));
// Now, start a transition to dangerous download.
{
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::LoadStopObserver observer(tab);
NavigateParams navigate_params(browser(), url_dangerous,
ui::PAGE_TRANSITION_TYPED);
Navigate(&navigate_params);
observer.Wait();
}
// Proceed through the SSL interstitial. This doesn't use
// ProceedThroughInterstitial() since no page load will commit.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
{
// Wait for the download to complete after proceeding with the download.
// This serves to verify the download was initiated, and to let the
// test successfully shut down and cleanup. Exiting the browser with a
// download still in-progress can lead to test failues.
content::DownloadTestObserverTerminal dangerous_download_observer(
browser()->profile()->GetDownloadManager(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT);
SendInterstitialCommand(tab, security_interstitials::CMD_PROCEED);
dangerous_download_observer.WaitForFinished();
}
// There should still be an interstitial at this point. Press the
// back button on the browser. Note that this doesn't wait for a
// NAV_ENTRY_COMMITTED notification because going back with an
// active interstitial simply hides the interstitial.
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(chrome::CanGoBack(browser()));
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
}
//
// Insecure content
//
// Visits a page that displays insecure content.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_content.html",
embedded_test_server()->host_port_pair());
// Load a page that displays insecure content.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
ssl_test_util::CheckSecurityState(
browser()->tab_strip_model()->GetActiveWebContents(), CertError::NONE,
security_state::WARNING, AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Visits a page that displays an insecure form.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureForm) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
// Since mixed forms trigger their own warning, we display the lock icon on
// otherwise secure sites with an insecure form.
security_state::SecurityLevel expected_level = security_state::SECURE;
ssl_test_util::CheckSecurityState(
browser()->tab_strip_model()->GetActiveWebContents(), CertError::NONE,
expected_level, AuthState::DISPLAYED_FORM_WITH_INSECURE_ACTION);
}
// Verifies that an SSL interstitial generates SafeBrowsing extension api
// events.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestExtensionEvents) {
class ExtensionEventObserver : public extensions::EventRouter::TestObserver {
public:
ExtensionEventObserver() = default;
ExtensionEventObserver(const ExtensionEventObserver&) = delete;
ExtensionEventObserver& operator=(const ExtensionEventObserver&) = delete;
~ExtensionEventObserver() override = default;
// extensions::EventRouter::TestObserver:
void OnWillDispatchEvent(const extensions::Event& event) override {
event_names_.push_back(event.event_name);
}
void OnDidDispatchEventToProcess(const extensions::Event& event,
int process_id) override {}
const std::vector<std::string>& event_names() const { return event_names_; }
private:
std::vector<std::string> event_names_;
};
ExtensionEventObserver observer;
extensions::EventRouter::Get(browser()->profile())
->AddObserverForTesting(&observer);
ASSERT_TRUE(https_server_expired_.Start());
GURL request_url = https_server_expired_.GetURL("/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), request_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab != nullptr);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Verifies that security interstitial shown event is observed.
EXPECT_TRUE(base::Contains(observer.event_names(),
extensions::api::safe_browsing_private::
OnSecurityInterstitialShown::kEventName));
ProceedThroughInterstitial(tab);
// Verifies that security interstitial proceeded event is observed.
EXPECT_TRUE(base::Contains(observer.event_names(),
extensions::api::safe_browsing_private::
OnSecurityInterstitialProceeded::kEventName));
extensions::EventRouter::Get(browser()->profile())
->RemoveObserverForTesting(&observer);
}
// Visits a page that runs insecure content and tries to suppress the insecure
// content warnings by randomizing location.hash.
// Based on http://crbug.com/8706
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRunsInsecuredContentRandomizeHash) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/page_runs_insecure_content.html")));
ssl_test_util::CheckAuthenticationBrokenState(
browser()->tab_strip_model()->GetActiveWebContents(), CertError::NONE,
AuthState::RAN_INSECURE_CONTENT);
}
// Visits an SSL page twice, once with subresources served over good SSL and
// once over bad SSL.
// - For the good SSL case, the iframe and images should be properly displayed.
// - For the bad SSL case, the iframe contents shouldn't be displayed and images
// and scripts should be filtered out entirely.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeContents) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
// Enable popups without user gesture.
HostContentSettingsMapFactory::GetForProfile(browser()->profile())
->SetDefaultContentSetting(ContentSettingsType::POPUPS,
CONTENT_SETTING_ALLOW);
{
// First visit the page with its iframe and subresources served over good
// SSL. This is a sanity check to make sure these resources aren't already
// broken in the good case.
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_contents.html", https_server_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// The state is expected to be authenticated.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// The iframe should be able to open a popup.
EXPECT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
// In order to check that the image was loaded, check its width.
// The actual image (Google logo) is 276 pixels wide.
EXPECT_EQ(276, content::EvalJs(tab, "ImageWidth();"));
// Check that variable |foo| is set.
EXPECT_EQ(true, content::EvalJs(tab, "IsFooSet();"));
}
{
// Now visit the page with its iframe and subresources served over bad
// SSL. Iframes, images, and scripts should all be blocked.
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_contents.html",
https_server_expired_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// When the bad content is filtered, the state is expected to be
// authenticated.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// The iframe attempts to open a popup window, but it shouldn't be able to.
// Previous popup is still open.
EXPECT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
// The broken image width is zero.
EXPECT_EQ(16, content::EvalJs(tab, "ImageWidth();"));
// Check that variable |foo| is not set.
EXPECT_EQ(false, content::EvalJs(tab, "IsFooSet();"));
}
}
// Visits a page with insecure content loaded by JS (after the initial page
// load).
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// flaky http://crbug.com/396462
#define MAYBE_TestDisplaysInsecureContentLoadedFromJS \
DISABLED_TestDisplaysInsecureContentLoadedFromJS
#else
#define MAYBE_TestDisplaysInsecureContentLoadedFromJS \
TestDisplaysInsecureContentLoadedFromJS
#endif
IN_PROC_BROWSER_TEST_F(SSLUITest,
MAYBE_TestDisplaysInsecureContentLoadedFromJS) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
net::HostPortPair replacement_pair = embedded_test_server()->host_port_pair();
replacement_pair.set_host("example.test");
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_dynamic_insecure_content.html", replacement_pair);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Load the insecure image.
EXPECT_EQ(true, content::EvalJs(tab, "loadBadImage();"));
// We should now have insecure content.
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Visits two pages from the same origin: one that displays insecure content and
// one that doesn't. The test checks that we do not propagate the insecure
// content state from one to the other.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureContentTwoTabs) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/blank_page.html")));
WebContents* tab1 = browser()->tab_strip_model()->GetActiveWebContents();
// This tab should be fine.
ssl_test_util::CheckAuthenticatedState(tab1, AuthState::NONE);
// Create a new tab.
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_content.html",
embedded_test_server()->host_port_pair());
GURL url = https_server_.GetURL(replacement_path);
NavigateParams params(browser(), url, ui::PAGE_TRANSITION_TYPED);
params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
params.tabstrip_index = 0;
params.source_contents = tab1;
Navigate(¶ms);
WebContents* tab2 = params.navigated_or_inserted_contents;
EXPECT_TRUE(content::WaitForLoadStop(tab2));
// The new tab has insecure content.
ssl_test_util::CheckSecurityState(tab2, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
// The original tab should not be contaminated.
ssl_test_util::CheckAuthenticatedState(tab1, AuthState::NONE);
}
// Visits two pages from the same origin: one that runs insecure content and one
// that doesn't. The test checks that we propagate the insecure content state
// from one to the other.
// TODO(crbug.com/40709634): Flaky
IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_TestRunsInsecureContentTwoTabs) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/blank_page.html")));
WebContents* tab1 = browser()->tab_strip_model()->GetActiveWebContents();
// This tab should be fine.
ssl_test_util::CheckAuthenticatedState(tab1, AuthState::NONE);
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_runs_insecure_content.html",
embedded_test_server()->host_port_pair());
// Create a new tab in the same process. Using a NEW_FOREGROUND_TAB
// disposition won't usually stay in the same process, but this works
// because we are using process-per-site in SetUpCommandLine.
GURL url = https_server_.GetURL(replacement_path);
NavigateParams params(browser(), url, ui::PAGE_TRANSITION_TYPED);
params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
params.source_contents = tab1;
Navigate(¶ms);
WebContents* tab2 = params.navigated_or_inserted_contents;
EXPECT_TRUE(content::WaitForLoadStop(tab2));
// Both tabs should have the same process.
EXPECT_EQ(tab1->GetPrimaryMainFrame()->GetProcess(),
tab2->GetPrimaryMainFrame()->GetProcess());
// The new tab has insecure content.
ssl_test_util::CheckAuthenticationBrokenState(
tab2, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
// Which means the origin for the first tab has also been contaminated with
// insecure content.
ssl_test_util::CheckAuthenticationBrokenState(
tab1, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
}
// Visits a page with an image over http. Visits another page over https
// referencing that same image over http (hoping it is coming from the webcore
// memory cache).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysCachedInsecureContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_content.html",
embedded_test_server()->host_port_pair());
// Load original page over HTTP.
const GURL url_http = embedded_test_server()->GetURL(replacement_path);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_http));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// Load again but over SSL. It should be marked as displaying insecure
// content (even though the image comes from the WebCore memory cache).
const GURL url_https = https_server_.GetURL(replacement_path);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_https));
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Visits a page with script over http. Visits another page over https
// referencing that same script over http (hoping it is coming from the webcore
// memory cache).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRunsCachedInsecureContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_runs_insecure_content.html",
embedded_test_server()->host_port_pair());
// Load original page over HTTP.
const GURL url_http = embedded_test_server()->GetURL(replacement_path);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_http));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// Load again but over SSL. It should be marked as displaying insecure
// content (even though the image comes from the WebCore memory cache).
const GURL url_https = https_server_.GetURL(replacement_path);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_https));
ssl_test_util::CheckAuthenticationBrokenState(
tab, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
}
// This test ensures the CN invalid status does not 'stick' to a certificate
// (see bug #1044942) and that it depends on the host-name.
// Test if disabled due to flakiness http://crbug.com/368280 .
IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_TestCNInvalidStickiness) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_mismatched_.Start());
// First we hit the server with hostname, this generates an invalid policy
// error.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/google.html")));
// We get an interstitial page as a result.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID,
AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
// Now we try again with the right host name this time.
GURL url(https_server_.GetURL("/ssl/google.html"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
// Security state should be OK.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Now try again the broken one to make sure it is still broken.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/google.html")));
// Since we OKed the interstitial last time, we get right to the page.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
}
// Test that navigating to a #ref does not change a bad security state.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRefNavigation) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/page_with_refs.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
// Now navigate to a ref in the page, the security state should not have
// changed.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/page_with_refs.html#jp")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
}
// Tests that closing a page that opened a pop-up with an interstitial does not
// crash the browser (crbug.com/1966).
// TODO(crbug.com/1119359, crbug.com/1338068): Test is flaky on Linux and Chrome
// OS.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_TestCloseTabWithUnsafePopup DISABLED_TestCloseTabWithUnsafePopup
#else
#define MAYBE_TestCloseTabWithUnsafePopup TestCloseTabWithUnsafePopup
#endif
IN_PROC_BROWSER_TEST_F(SSLUITest, MAYBE_TestCloseTabWithUnsafePopup) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
// Enable popups without user gesture.
HostContentSettingsMapFactory::GetForProfile(browser()->profile())
->SetDefaultContentSetting(ContentSettingsType::POPUPS,
CONTENT_SETTING_ALLOW);
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_popup.html",
https_server_expired_.host_port_pair());
WebContents* tab1 = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(
https_server_expired_.GetURL("/ssl/bad_iframe.html"));
nav_observer.StartWatchingNewWebContents();
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(replacement_path)));
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
// Last activated browser should be the popup.
Browser* popup_browser = chrome::FindBrowserWithProfile(browser()->profile());
WebContents* popup = popup_browser->tab_strip_model()->GetActiveWebContents();
EXPECT_NE(popup, tab1);
nav_observer.Wait();
ASSERT_TRUE(popup->GetController().GetVisibleEntry());
EXPECT_EQ(https_server_expired_.GetURL("/ssl/bad_iframe.html"),
popup->GetController().GetVisibleEntry()->GetURL());
// The interstitial showing is posted to the message loop and this happens
// after the navigation, so we need to additionally wait for that to be
// processed.
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(popup));
// Add another tab to make sure the browser does not exit when we close
// the first tab.
GURL url = embedded_test_server()->GetURL("/ssl/google.html");
auto* contents =
chrome::AddSelectedTabWithURL(browser(), url, ui::PAGE_TRANSITION_TYPED);
EXPECT_TRUE(content::WaitForLoadStop(contents));
// Close the first tab.
chrome::CloseWebContents(browser(), tab1, false);
}
// Visit a page over bad https that is a redirect to a page with good https.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectBadToGoodHTTPS) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
GURL url1 = https_server_expired_.GetURL("/server-redirect?");
GURL url2 = https_server_.GetURL("/ssl/google.html");
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL(url1.spec() + url2.spec())));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
// We have been redirected to the good page.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Visit a page over good https that is a redirect to a page with bad https.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectGoodToBadHTTPS) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
GURL url1 = https_server_.GetURL("/server-redirect?");
GURL url2 = https_server_expired_.GetURL("/ssl/google.html");
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL(url1.spec() + url2.spec())));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
}
// Visit a page over http that is a redirect to a page with good HTTPS.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPToGoodHTTPS) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// HTTP redirects to good HTTPS.
GURL http_url = embedded_test_server()->GetURL("/server-redirect?");
GURL good_https_url = https_server_.GetURL("/ssl/google.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL(http_url.spec() + good_https_url.spec())));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Visit a page over http that is a redirect to a page with bad HTTPS.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPToBadHTTPS) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
const GURL http_url = embedded_test_server()->GetURL("/server-redirect?");
const GURL bad_https_url = https_server_expired_.GetURL("/ssl/google.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL(http_url.spec() + bad_https_url.spec())));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
}
// Visit a page over https that is a redirect to a page with http (to make sure
// we don't keep the secure state).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPSToHTTP) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
GURL https_url = https_server_.GetURL("/server-redirect?");
GURL http_url = embedded_test_server()->GetURL("/ssl/google.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL(https_url.spec() + http_url.spec())));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Visit a page over https that is a redirect to a non-existent page with http
// (to make sure we don't keep the secure state when redirecting to an error).
// Regression test for crbug.com/1154754.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPSToInvalidHTTP) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
GURL https_url = https_server_.GetURL("/server-redirect?");
// Test runners might have servers listening in localhost, and the test
// constructor routes all URLs to localhost, so use close-socket to make
// sure we always get an error page.
GURL invalid_url = embedded_test_server()->GetURL("/close-socket");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL(https_url.spec() + invalid_url.spec())));
auto* helper = SecurityStateTabHelper::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents());
// Check we don't keep the previous certificate state around.
EXPECT_FALSE(helper->GetVisibleSecurityState()->certificate);
EXPECT_EQ(helper->GetSecurityLevel(), security_state::SecurityLevel::NONE);
}
class SSLUITestWaitForDOMNotification : public SSLUITestIgnoreCertErrors,
public content::WebContentsObserver {
public:
SSLUITestWaitForDOMNotification()
: SSLUITestIgnoreCertErrors(), run_loop_(nullptr) {}
SSLUITestWaitForDOMNotification(const SSLUITestWaitForDOMNotification&) =
delete;
SSLUITestWaitForDOMNotification& operator=(
const SSLUITestWaitForDOMNotification&) = delete;
~SSLUITestWaitForDOMNotification() override = default;
void SetUpOnMainThread() override {
SSLUITestIgnoreCertErrors::SetUpOnMainThread();
}
void set_expected_notification(const std::string& expected_notification) {
expected_notification_ = expected_notification;
}
void set_run_loop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
void observe(content::WebContents* web_contents) {
content::WebContentsObserver::Observe(web_contents);
}
// content::WebContentsObserver
void DomOperationResponse(content::RenderFrameHost* render_frame_host,
const std::string& json_string) override {
DCHECK(run_loop_);
if (json_string == expected_notification_) {
run_loop_->Quit();
}
}
private:
std::string expected_notification_;
raw_ptr<base::RunLoop> run_loop_;
};
// Tests that a mixed resource which includes HTTP in the redirect chain
// is marked as mixed content, even if the end result is HTTPS.
IN_PROC_BROWSER_TEST_F(SSLUITestWaitForDOMNotification,
TestMixedContentWithHTTPInRedirectChain) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/blank_page.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Construct a URL which will be dynamically added to the page as an
// image. The URL redirects through HTTP, though it ends up at an
// HTTPS resource.
GURL http_url = embedded_test_server()->GetURL("/server-redirect?");
GURL::Replacements http_url_replacements;
// Be sure to use a non-localhost name for the mixed content request,
// since local hostnames are not considered mixed content.
http_url_replacements.SetHostStr("example.test");
std::string http_url_query =
EncodeQuery(https_server_.GetURL("/ssl/google_files/logo.gif").spec());
http_url_replacements.SetQueryStr(http_url_query);
http_url = http_url.ReplaceComponents(http_url_replacements);
GURL https_url = https_server_.GetURL("/server-redirect?");
GURL::Replacements https_url_replacements;
std::string https_url_query = EncodeQuery(http_url.spec());
https_url_replacements.SetQueryStr(https_url_query);
https_url = https_url.ReplaceComponents(https_url_replacements);
base::RunLoop run_loop;
// Load the image. It starts at |https_server_|, which redirects to an
// embedded_test_server() HTTP URL, which redirects back to
// |https_server_| for the final HTTPS image. Because the redirect
// chain passes through HTTP, the page should be marked as mixed
// content.
set_expected_notification("\"mixed-image-loaded\"");
observe(tab);
set_run_loop(&run_loop);
ASSERT_TRUE(content::ExecJs(
tab,
"var loaded = function () {"
" window.domAutomationController.send('mixed-image-loaded');"
"};"
"var img = document.createElement('img');"
"img.onload = loaded;"
"img.src = '" +
https_url.spec() +
"';"
"document.body.appendChild(img);"));
run_loop.Run();
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Visits a page to which we could not connect (bad port) over http and https
// and make sure the security style is correct.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestConnectToBadPort) {
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("http://localhost:17")));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(),
AuthState::SHOWING_ERROR);
// Same thing over HTTPS.
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("https://localhost:17")));
ssl_test_util::CheckUnauthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(),
AuthState::SHOWING_ERROR);
}
//
// Frame navigation
//
// From a good HTTPS top frame:
// - navigate to an OK HTTPS frame
// - navigate to a bad HTTPS (expect unsafe content and filtered frame), then
// back
// - navigate to HTTP (expect insecure content), then back
IN_PROC_BROWSER_TEST_F(SSLUITest, TestGoodFrameNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
// SetUpOnMainThread adds this hostname to the resolver so that it's not
// blocked (browser_test_base.cc has a resolver that blocks all non-local
// hostnames by default to ensure tests don't hit the network). This is
// critical to do because the request would otherwise get cancelled in the
// browser before the renderer sees it.
std::string top_frame_path = GetTopFramePath(
*embedded_test_server(), https_server_, https_server_expired_);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(top_frame_path)));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Now navigate inside the frame.
{
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('goodHTTPSLink');"));
observer.Wait();
}
// We should still be fine.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Now let's hit a bad page.
{
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('badHTTPSLink');"));
observer.Wait();
}
// The security style should still be secure.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// And the frame should be blocked.
content::RenderFrameHost* content_frame = content::FrameMatchingPredicate(
tab->GetPrimaryPage(),
base::BindRepeating(&content::FrameMatchesName, "contentFrame"));
std::string is_evil_js("document.getElementById('evilDiv') != null;");
EXPECT_EQ(false, content::EvalJs(content_frame, is_evil_js));
// Now go back, our state should still be OK.
{
content::LoadStopObserver observer(tab);
tab->GetController().GoBack();
observer.Wait();
}
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// Navigate to a page served over HTTP.
{
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('HTTPLink');"));
observer.Wait();
}
// Our state should be unauthenticated (in the ran mixed script sense). Note
// this also displays images from the http page (google.com).
ssl_test_util::CheckAuthenticationBrokenState(
tab, CertError::NONE,
AuthState::RAN_INSECURE_CONTENT | AuthState::DISPLAYED_INSECURE_CONTENT |
AuthState::DISPLAYED_FORM_WITH_INSECURE_ACTION);
// Go back, our state should be unchanged.
{
content::LoadStopObserver observer(tab);
tab->GetController().GoBack();
observer.Wait();
}
ssl_test_util::CheckAuthenticationBrokenState(
tab, CertError::NONE,
AuthState::RAN_INSECURE_CONTENT | AuthState::DISPLAYED_INSECURE_CONTENT |
AuthState::DISPLAYED_FORM_WITH_INSECURE_ACTION);
}
// From a bad HTTPS top frame:
// - navigate to an OK HTTPS frame (expected to be still authentication broken).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestBadFrameNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
std::string top_frame_path = GetTopFramePath(
*embedded_test_server(), https_server_, https_server_expired_);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL(top_frame_path)));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
// Navigate to a good frame.
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('goodHTTPSLink');"));
observer.Wait();
// We should still be authentication broken.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
}
// From an HTTP top frame, navigate to good and bad HTTPS (security state should
// stay unauthenticated).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnauthenticatedFrameNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
std::string top_frame_path = GetTopFramePath(
*embedded_test_server(), https_server_, https_server_expired_);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(top_frame_path)));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// Now navigate inside the frame to a secure HTTPS frame.
{
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('goodHTTPSLink');"));
observer.Wait();
}
// We should still be unauthenticated.
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// Now navigate to a bad HTTPS frame.
{
content::LoadStopObserver observer(tab);
ASSERT_EQ(true, content::EvalJs(tab, "clickLink('badHTTPSLink');"));
observer.Wait();
}
// State should not have changed.
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// And the frame should have been blocked (see bug #2316).
content::RenderFrameHost* content_frame = content::FrameMatchingPredicate(
tab->GetPrimaryPage(),
base::BindRepeating(&content::FrameMatchesName, "contentFrame"));
std::string is_evil_js("document.getElementById('evilDiv') != null;");
EXPECT_EQ(false, content::EvalJs(content_frame, is_evil_js));
}
enum class OffMainThreadFetchMode { kEnabled, kDisabled };
enum class SSLUIWorkerFetchTestType { kUseFetch, kUseImportScripts };
class SSLUIWorkerFetchTest
: public testing::WithParamInterface<SSLUIWorkerFetchTestType>,
public SSLUITestBase {
public:
SSLUIWorkerFetchTest() { EXPECT_TRUE(tmp_dir_.CreateUniqueTempDir()); }
SSLUIWorkerFetchTest(const SSLUIWorkerFetchTest&) = delete;
SSLUIWorkerFetchTest& operator=(const SSLUIWorkerFetchTest&) = delete;
~SSLUIWorkerFetchTest() override = default;
void SetUpOnMainThread() override { SSLUITestBase::SetUpOnMainThread(); }
void SetUpCommandLine(base::CommandLine* command_line) override {
SSLUITestBase::SetUpCommandLine(command_line);
scoped_feature_list_.InitAndDisableFeature(
blink::features::kMixedContentAutoupgrade);
}
protected:
void WriteFile(const base::FilePath::StringType& filename,
std::string_view contents) {
base::ScopedAllowBlockingForTesting allow_blocking;
EXPECT_TRUE(base::WriteFile(tmp_dir_.GetPath().Append(filename), contents));
}
void WriteTestFiles(const net::EmbeddedTestServer& remote_server,
const std::string& hostname) {
WriteFile(FILE_PATH_LITERAL("worker_test.html"),
"<script>"
"var worker = new Worker('worker.js');"
"worker.addEventListener("
" 'message',"
" event => { document.title = event.data; });"
"</script>");
switch (GetParam()) {
case SSLUIWorkerFetchTestType::kUseFetch:
WriteFile(FILE_PATH_LITERAL("worker_test_data.txt.mock-http-headers"),
"HTTP/1.1 200 OK\n"
"Content-Type: text/plain\n"
"Access-Control-Allow-Origin: *");
WriteFile(FILE_PATH_LITERAL("worker_test_data.txt"), "LOADED");
WriteFile(FILE_PATH_LITERAL("worker.js"),
base::StringPrintf(
"fetch('%s')"
" .then(res => res.text())"
" .then(text => postMessage(text))"
" .catch(_ => postMessage('FAILED'))",
remote_server.GetURL(hostname, "/worker_test_data.txt")
.spec()
.c_str()));
break;
case SSLUIWorkerFetchTestType::kUseImportScripts: {
WriteFile(FILE_PATH_LITERAL("imported.js"), "data = 'LOADED';");
WriteFile(
FILE_PATH_LITERAL("worker.js"),
base::StringPrintf(
"var data = 'FAILED';"
"try {"
" importScripts('%s')"
"} catch(e) {}"
"postMessage(data);",
remote_server.GetURL(hostname, "/imported.js").spec().c_str()));
} break;
}
}
void RunMixedContentSettingsTest(
ChromeContentBrowserClientForMixedContentTest* browser_client,
bool allow_running_insecure_content,
bool strict_mixed_content_checking,
bool strictly_block_blockable_mixed_content,
bool expected_load,
bool expected_show_blocked,
bool expected_show_dangerous,
bool expected_load_after_allow,
bool expected_show_blocked_after_allow,
bool expected_show_dangerous_after_allow) {
SCOPED_TRACE(
::testing::Message()
<< "RunMixedContentSettingsTest :"
<< "allow_running_insecure_content="
<< (allow_running_insecure_content ? "true " : "false ")
<< "strict_mixed_content_checking="
<< (strict_mixed_content_checking ? "true " : "false ")
<< "strictly_block_blockable_mixed_content="
<< (strictly_block_blockable_mixed_content ? "true " : "false "));
// Run the tests in a new tab. This forces each call of
// RunMixedContentSettingsTest in a single test case to use different tabs
// and thus different processes, bypassing a subtle race condition where
// processes can get re-used under Site Isolation and retain their mixed
// content status (see crbug.com/890372). This ensures all error state is
// cleared.
chrome::NewTab(browser());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(tab));
CheckErrorStateIsCleared();
browser_client->SetMixedContentSettings(
allow_running_insecure_content, strict_mixed_content_checking,
strictly_block_blockable_mixed_content);
tab->OnWebPreferencesChanged();
CheckMixedContentSettings(allow_running_insecure_content,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content);
const std::u16string loaded_title = u"LOADED";
const std::u16string failed_title = u"FAILED";
{
// First load.
content::TitleWatcher watcher(tab, loaded_title);
watcher.AlsoWaitForTitle(failed_title);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/worker_test.html")));
EXPECT_EQ(expected_load ? loaded_title : failed_title,
watcher.WaitAndGetTitle());
}
EXPECT_EQ(expected_show_blocked,
content_settings::PageSpecificContentSettings::GetForFrame(
tab->GetPrimaryMainFrame())
->IsContentBlocked(ContentSettingsType::MIXEDSCRIPT));
ssl_test_util::CheckSecurityState(
tab, CertError::NONE,
expected_show_dangerous ? security_state::DANGEROUS
: security_state::SECURE,
expected_show_dangerous ? AuthState::RAN_INSECURE_CONTENT
: AuthState::NONE);
// Clears title.
ASSERT_TRUE(
content::ExecJs(tab->GetPrimaryMainFrame(), "document.title = \"\";"));
{
// SetAllowRunningInsecureContent will reload the page.
content::TitleWatcher watcher(tab, loaded_title);
watcher.AlsoWaitForTitle(failed_title);
SetAllowRunningInsecureContent();
tab->OnWebPreferencesChanged();
EXPECT_EQ(expected_load_after_allow ? loaded_title : failed_title,
watcher.WaitAndGetTitle());
}
EXPECT_EQ(expected_show_blocked_after_allow,
content_settings::PageSpecificContentSettings::GetForFrame(
tab->GetPrimaryMainFrame())
->IsContentBlocked(ContentSettingsType::MIXEDSCRIPT));
ssl_test_util::CheckSecurityState(
tab, CertError::NONE,
expected_show_dangerous_after_allow ? security_state::DANGEROUS
: security_state::SECURE,
expected_show_dangerous_after_allow ? AuthState::RAN_INSECURE_CONTENT
: AuthState::NONE);
chrome::CloseTab(browser());
}
base::ScopedTempDir tmp_dir_;
private:
void SetAllowRunningInsecureContent() {
content::RenderFrameHost* render_frame_host = browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
mojo::AssociatedRemote<content_settings::mojom::ContentSettingsAgent> agent;
render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&agent);
agent->SetAllowRunningInsecureContent();
}
void CheckErrorStateIsCleared() {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_FALSE(content_settings::PageSpecificContentSettings::GetForFrame(
tab->GetPrimaryMainFrame())
->IsContentBlocked(ContentSettingsType::MIXEDSCRIPT));
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::NONE, AuthState::NONE);
EXPECT_FALSE(SecurityStateTabHelper::FromWebContents(tab)
->GetVisibleSecurityState()
->ran_mixed_content);
}
void CheckMixedContentSettings(bool allow_running_insecure_content,
bool strict_mixed_content_checking,
bool strictly_block_blockable_mixed_content) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
const blink::web_pref::WebPreferences& prefs =
tab->GetOrCreateWebPreferences();
ASSERT_EQ(prefs.strictly_block_blockable_mixed_content,
strictly_block_blockable_mixed_content);
ASSERT_EQ(prefs.allow_running_insecure_content,
allow_running_insecure_content);
ASSERT_EQ(prefs.strict_mixed_content_checking,
strict_mixed_content_checking);
}
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_P(SSLUIWorkerFetchTest,
TestUnsafeContentsInWorkerFiltered) {
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
https_server_expired_.ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
WriteTestFiles(https_server_expired_, "localhost");
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
const std::u16string loaded_title = u"LOADED";
const std::u16string failed_title = u"FAILED";
content::TitleWatcher watcher(tab, loaded_title);
watcher.AlsoWaitForTitle(failed_title);
// This page will spawn a Worker which will try to load content from
// BadCertServer.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/worker_test.html")));
// Expect Worker not to load insecure content.
EXPECT_EQ(failed_title, watcher.WaitAndGetTitle());
// The bad content is filtered, expect the state to be authenticated.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// This test, and the related test TestUnsafeContentsWithUserException, verify
// that if unsafe content is loaded but the host of that unsafe content has a
// user exception, the content runs and the security style is downgraded.
// TODO(crbug.com/40707016): Disabled due to flakiness.
IN_PROC_BROWSER_TEST_P(SSLUIWorkerFetchTest,
DISABLED_TestUnsafeContentsInWorkerWithUserException) {
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
https_server_mismatched_.ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
// Note that it is necessary to user https_server_mismatched_ here over the
// other invalid cert servers. This is because the test relies on the two
// servers having different hosts since SSL exceptions are per-host, not per
// origin, and https_server_mismatched_ uses 'localhost' rather than
// '127.0.0.1'.
ASSERT_TRUE(https_server_mismatched_.Start());
WriteTestFiles(https_server_mismatched_, "localhost");
// Navigate to an unsafe site. Proceed with interstitial page to indicate
// the user approves the bad certificate.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/blank_page.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID,
AuthState::SHOWING_INTERSTITIAL);
content::TestNavigationObserver nav_observer(tab, 1);
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->CommandReceived(
base::NumberToString(security_interstitials::CMD_PROCEED));
nav_observer.Wait();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
SecurityStateTabHelper* tab_helper =
SecurityStateTabHelper::FromWebContents(tab);
ASSERT_TRUE(tab_helper);
std::unique_ptr<security_state::VisibleSecurityState> visible_security_state =
tab_helper->GetVisibleSecurityState();
EXPECT_FALSE(visible_security_state->ran_mixed_content);
EXPECT_FALSE(visible_security_state->displayed_mixed_content);
EXPECT_FALSE(visible_security_state->ran_content_with_cert_errors);
EXPECT_FALSE(visible_security_state->displayed_content_with_cert_errors);
const std::u16string loaded_title = u"LOADED";
const std::u16string failed_title = u"FAILED";
content::TitleWatcher watcher(tab, loaded_title);
watcher.AlsoWaitForTitle(failed_title);
// Navigate to safe page that has Worker loading unsafe content.
// Expect content to load but be marked as auth broken due to running insecure
// content.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/worker_test.html")));
// Worker loads insecure content
EXPECT_EQ(loaded_title, watcher.WaitAndGetTitle());
ssl_test_util::CheckAuthenticationBrokenState(tab, CertError::NONE,
AuthState::NONE);
visible_security_state = tab_helper->GetVisibleSecurityState();
EXPECT_FALSE(visible_security_state->ran_mixed_content);
EXPECT_FALSE(visible_security_state->displayed_mixed_content);
EXPECT_TRUE(visible_security_state->ran_content_with_cert_errors);
EXPECT_FALSE(visible_security_state->displayed_content_with_cert_errors);
}
// This test checks the behavior of mixed content blocking for the requests
// from a dedicated worker by changing the settings in WebPreferences
// with allow_running_insecure_content = true.
// Flaky. See https://crbug.com/1145674.
IN_PROC_BROWSER_TEST_P(
SSLUIWorkerFetchTest,
DISABLED_MixedContentSettings_AllowRunningInsecureContent) {
ChromeContentBrowserClientForMixedContentTest browser_client;
content::ScopedContentBrowserClientSetting setting(&browser_client);
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
embedded_test_server()->ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(embedded_test_server()->Start());
WriteTestFiles(*embedded_test_server(), "example.com");
for (bool strict_mixed_content_checking : {true, false}) {
for (bool strictly_block_blockable_mixed_content : {true, false}) {
if (strict_mixed_content_checking) {
RunMixedContentSettingsTest(
&browser_client, true /* allow_running_insecure_content */,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, false /* expected_load */,
false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
} else {
RunMixedContentSettingsTest(
&browser_client, true /* allow_running_insecure_content */,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, true /* expected_load */,
false /* expected_show_blocked */,
true /* expected_show_dangerous */,
true /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
true /* expected_show_dangerous_after_allow */);
}
}
}
}
// This test checks the behavior of mixed content blocking for the requests
// from a dedicated worker by changing the settings in WebPreferences
// with allow_running_insecure_content = false.
// Disabled due to being flaky. crbug.com/1116670
IN_PROC_BROWSER_TEST_P(
SSLUIWorkerFetchTest,
DISABLED_MixedContentSettings_DisallowRunningInsecureContent) {
ChromeContentBrowserClientForMixedContentTest browser_client;
content::ScopedContentBrowserClientSetting setting(&browser_client);
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
embedded_test_server()->ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(embedded_test_server()->Start());
WriteTestFiles(*embedded_test_server(), "example.com");
for (bool strict_mixed_content_checking : {true, false}) {
for (bool strictly_block_blockable_mixed_content : {true, false}) {
if (strict_mixed_content_checking) {
RunMixedContentSettingsTest(
&browser_client, false /* allow_running_insecure_content */,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, false /* expected_load */,
false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
} else if (strictly_block_blockable_mixed_content) {
RunMixedContentSettingsTest(
&browser_client, false /* allow_running_insecure_content */,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, false /* expected_load */,
false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
} else {
RunMixedContentSettingsTest(
&browser_client, false /* allow_running_insecure_content */,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, false /* expected_load */,
true /* expected_show_blocked */,
false /* expected_show_dangerous */,
true /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
true /* expected_show_dangerous_after_allow */);
}
}
}
}
// This test checks that all mixed content requests from a dedicated worker are
// blocked regardless of the settings in WebPreferences when
// block-all-mixed-content CSP is set with allow_running_insecure_content=true.
IN_PROC_BROWSER_TEST_P(
SSLUIWorkerFetchTest,
MixedContentSettingsWithBlockingCSP_AllowRunningInsecureContent) {
ChromeContentBrowserClientForMixedContentTest browser_client;
content::ScopedContentBrowserClientSetting setting(&browser_client);
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
embedded_test_server()->ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(embedded_test_server()->Start());
WriteTestFiles(*embedded_test_server(), "example.com");
WriteFile(FILE_PATH_LITERAL("worker.js.mock-http-headers"),
"HTTP/1.1 200 OK\n"
"Content-Type: application/javascript\n"
"Content-Security-Policy: block-all-mixed-content;");
for (bool strict_mixed_content_checking : {true, false}) {
for (bool strictly_block_blockable_mixed_content : {true, false}) {
RunMixedContentSettingsTest(
&browser_client, true /* allow_running_insecure_content */,
strict_mixed_content_checking, strictly_block_blockable_mixed_content,
false /* expected_load */, false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
}
}
}
// This test checks that all mixed content requests from a dedicated worker are
// blocked regardless of the settings in WebPreferences when
// block-all-mixed-content CSP is set with allow_running_insecure_content=false.
IN_PROC_BROWSER_TEST_P(
SSLUIWorkerFetchTest,
MixedContentSettingsWithBlockingCSP_DisallowRunningInsecureContent) {
ChromeContentBrowserClientForMixedContentTest browser_client;
content::ScopedContentBrowserClientSetting setting(&browser_client);
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
embedded_test_server()->ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(embedded_test_server()->Start());
WriteTestFiles(*embedded_test_server(), "example.com");
WriteFile(FILE_PATH_LITERAL("worker.js.mock-http-headers"),
"HTTP/1.1 200 OK\n"
"Content-Type: application/javascript\n"
"Content-Security-Policy: block-all-mixed-content;");
for (bool strict_mixed_content_checking : {true, false}) {
for (bool strictly_block_blockable_mixed_content : {true, false}) {
RunMixedContentSettingsTest(
&browser_client, false /* allow_running_insecure_content */,
strict_mixed_content_checking, strictly_block_blockable_mixed_content,
false /* expected_load */, false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
}
}
}
// This test checks that all mixed content requests from a dedicated worker
// which is started from a subframe are blocked if
// allow_running_insecure_content setting is false or
// strict_mixed_content_checking setting is true.
// TODO(carlosil): Re-enable to check if this triggers flakiness due to
// committed interstitials.
IN_PROC_BROWSER_TEST_P(SSLUIWorkerFetchTest, DISABLED_MixedContentSubFrame) {
ChromeContentBrowserClientForMixedContentTest browser_client;
content::ScopedContentBrowserClientSetting setting(&browser_client);
https_server_.ServeFilesFromDirectory(tmp_dir_.GetPath());
embedded_test_server()->ServeFilesFromDirectory(tmp_dir_.GetPath());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(embedded_test_server()->Start());
WriteTestFiles(*embedded_test_server(), "example.com");
WriteFile(FILE_PATH_LITERAL("worker_iframe.html"),
"<script>"
"var worker = new Worker('worker.js');"
"worker.addEventListener("
" 'message',"
" event => { parent.postMessage(event.data, '*'); });"
"</script>");
WriteFile(FILE_PATH_LITERAL("worker_test.html"),
"<script>"
"window.addEventListener("
" 'message',"
" event => { document.title = event.data; });"
"</script>"
"<iframe src=\"./worker_iframe.html\" />");
for (bool allow_running_insecure_content : {true, false}) {
for (bool strict_mixed_content_checking : {true, false}) {
for (bool strictly_block_blockable_mixed_content : {true, false}) {
if (allow_running_insecure_content && !strict_mixed_content_checking) {
RunMixedContentSettingsTest(
&browser_client, allow_running_insecure_content,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, true /* expected_load */,
false /* expected_show_blocked */,
true /* expected_show_dangerous */,
true /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
true /* expected_show_dangerous_after_allow */);
} else {
RunMixedContentSettingsTest(
&browser_client, allow_running_insecure_content,
strict_mixed_content_checking,
strictly_block_blockable_mixed_content, false /* expected_load */,
false /* expected_show_blocked */,
false /* expected_show_dangerous */,
false /* expected_load_after_allow */,
false /* expected_show_blocked_after_allow */,
false /* expected_show_dangerous_after_allow */);
}
}
}
}
}
INSTANTIATE_TEST_SUITE_P(
/* no prefix */,
SSLUIWorkerFetchTest,
::testing::Values(SSLUIWorkerFetchTestType::kUseFetch,
SSLUIWorkerFetchTestType::kUseImportScripts));
// Visits a page with unsafe content and makes sure that if a user exception
// to the certificate error is present, the image is loaded and script
// executes.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeContentsWithUserException) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_NO_FATAL_FAILURE(SetUpUnsafeContentsWithUserException(
"/ssl/page_with_unsafe_contents.html"));
ssl_test_util::CheckAuthenticationBrokenState(tab, CertError::NONE,
AuthState::NONE);
SecurityStateTabHelper* helper = SecurityStateTabHelper::FromWebContents(tab);
ASSERT_TRUE(helper);
std::unique_ptr<security_state::VisibleSecurityState> visible_security_state =
helper->GetVisibleSecurityState();
EXPECT_FALSE(visible_security_state->ran_mixed_content);
EXPECT_FALSE(visible_security_state->displayed_mixed_content);
EXPECT_TRUE(visible_security_state->ran_content_with_cert_errors);
EXPECT_TRUE(visible_security_state->displayed_content_with_cert_errors);
// In order to check that the image was loaded, we check its width.
// The actual image (Google logo) is 114 pixels wide, so we assume a good
// image is greater than 100.
EXPECT_GT(content::EvalJs(tab, "ImageWidth();"), 100);
EXPECT_EQ(true, content::EvalJs(tab, "IsFooSet();"));
// Test that active subresources with the same certificate errors as
// the main resources also get noted in |content_with_cert_errors_status|.
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_contents.html",
https_server_mismatched_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL(replacement_path)));
EXPECT_EQ(true, content::EvalJs(tab, "IsFooSet();"));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE);
visible_security_state = helper->GetVisibleSecurityState();
EXPECT_FALSE(visible_security_state->ran_mixed_content);
EXPECT_FALSE(visible_security_state->displayed_mixed_content);
EXPECT_TRUE(visible_security_state->ran_content_with_cert_errors);
EXPECT_TRUE(visible_security_state->displayed_content_with_cert_errors);
}
// Like the test above, but only displaying inactive content (an image).
IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeImageWithUserException) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_NO_FATAL_FAILURE(
SetUpUnsafeContentsWithUserException("/ssl/page_with_unsafe_image.html"));
SecurityStateTabHelper* helper = SecurityStateTabHelper::FromWebContents(tab);
ASSERT_TRUE(helper);
std::unique_ptr<security_state::VisibleSecurityState> visible_security_state =
helper->GetVisibleSecurityState();
EXPECT_FALSE(visible_security_state->ran_mixed_content);
EXPECT_FALSE(visible_security_state->displayed_mixed_content);
EXPECT_FALSE(visible_security_state->ran_content_with_cert_errors);
EXPECT_TRUE(visible_security_state->displayed_content_with_cert_errors);
EXPECT_EQ(0u, visible_security_state->cert_status);
// In order to check that the image was loaded, we check its width.
// The actual image (Google logo) is 114 pixels wide, so we assume a good
// image is greater than 100.
EXPECT_GT(content::EvalJs(tab, "ImageWidth();"), 100);
}
// Test that when the browser blocks displaying insecure content (iframes),
// the indicator shows a secure page, because the blocking made the otherwise
// unsafe page safe (the notification of this state is handled by other means)
IN_PROC_BROWSER_TEST_F(SSLUITestBlock, TestBlockDisplayingInsecureIframe) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_iframe.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
ssl_test_util::CheckAuthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Test that when the browser blocks running insecure content, the
// indicator shows a secure page, because the blocking made the otherwise
// unsafe page safe (the notification of this state is handled by other
// means).
IN_PROC_BROWSER_TEST_F(SSLUITestBlock, TestBlockRunningInsecureContent) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_runs_insecure_content.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
ssl_test_util::CheckAuthenticatedState(
browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE);
}
// Visit a page and establish a WebSocket connection over bad https with
// --ignore-certificate-errors. The connection should be established without
// interstitial page showing.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrors, TestWSS) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(wss_server_expired_.Start());
// Setup page title observer.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TitleWatcher watcher(tab, u"PASS");
watcher.AlsoWaitForTitle(u"FAIL");
// Visit bad HTTPS page.
GURL::Replacements replacements;
replacements.SetSchemeStr("https");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), wss_server_expired_.GetURL("connect_check.html")
.ReplaceComponents(replacements)));
// We shouldn't have an interstitial page showing here.
// Test page run a WebSocket wss connection test. The result will be shown
// as page title.
const std::u16string result = watcher.WaitAndGetTitle();
EXPECT_TRUE(base::EqualsCaseInsensitiveASCII(result, "pass"));
}
// Visit a page and establish a WebSocket connection over bad https with
// --ignore-certificate-errors-spki-list. The connection should be established
// without interstitial page showing.
#if !BUILDFLAG(IS_CHROMEOS) // Chrome OS does not support the flag.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIWSS, TestWSSExpired) {
ASSERT_TRUE(wss_server_expired_.Start());
// Setup page title observer.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TitleWatcher watcher(tab, u"PASS");
watcher.AlsoWaitForTitle(u"FAIL");
// Visit bad HTTPS page.
GURL::Replacements replacements;
replacements.SetSchemeStr("https");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), wss_server_expired_.GetURL("connect_check.html")
.ReplaceComponents(replacements)));
// We shouldn't have an interstitial page showing here.
// Test page run a WebSocket wss connection test. The result will be shown
// as page title.
const std::u16string result = watcher.WaitAndGetTitle();
EXPECT_TRUE(base::EqualsCaseInsensitiveASCII(result, "pass"));
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// Test that HTTPS pages with a bad certificate don't show an interstitial if
// the public key matches a value from --ignore-certificate-errors-spki-list.
#if !BUILDFLAG(IS_CHROMEOS) // Chrome OS does not support the flag.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestHTTPS) {
ASSERT_TRUE(https_server_mismatched_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_mismatched_.GetURL("/ssl/page_with_subresource.html")));
// We should see no interstitial. The script tag in the page should have
// loaded and ran (and wasn't blocked by the certificate error).
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
std::u16string title;
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(title, u"This script has loaded");
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// Test subresources from an origin with a bad certificate are loaded if the
// public key matches a value from --ignore-certificate-errors-spki-list.
#if !BUILDFLAG(IS_CHROMEOS) // Chrome OS does not support the flag.
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS,
TestInsecureSubresource) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_mismatched_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_with_unsafe_image.html",
https_server_mismatched_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
// We should see no interstitial.
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
// In order to check that the image was loaded, check its width.
// The actual image (Google logo) is 276 pixels wide.
EXPECT_GT(content::EvalJs(tab, "ImageWidth();"), 200);
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// Verifies that the interstitial can proceed, even if JavaScript is disabled.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialJavaScriptProceeds) {
HostContentSettingsMapFactory::GetForProfile(browser()->profile())
->SetDefaultContentSetting(ContentSettingsType::JAVASCRIPT,
CONTENT_SETTING_BLOCK);
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
content::LoadStopObserver observer(tab);
const std::string javascript =
"window.certificateErrorPageController.proceed();";
EXPECT_TRUE(content::ExecJs(tab, javascript));
observer.Wait();
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE);
}
// Verifies that the interstitial can go back, even if JavaScript is disabled.
// http://crbug.com/322948
IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialJavaScriptGoesBack) {
HostContentSettingsMapFactory::GetForProfile(browser()->profile())
->SetDefaultContentSetting(ContentSettingsType::JAVASCRIPT,
CONTENT_SETTING_BLOCK);
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
content::LoadStopObserver observer(tab);
const std::string javascript =
"window.certificateErrorPageController.dontProceed();";
EXPECT_TRUE(content::ExecJs(tab, javascript));
observer.Wait();
EXPECT_EQ("about:blank", tab->GetVisibleURL().spec());
}
// Verifies that an overridable interstitial has a proceed link.
IN_PROC_BROWSER_TEST_F(SSLUITest, ProceedLinkOverridable) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(chrome_browser_interstitials::InterstitialHasProceedLink(
tab->GetPrimaryMainFrame()));
}
IN_PROC_BROWSER_TEST_F(SSLUITest, TestLearnMoreLinkContainsErrorCode) {
ASSERT_TRUE(https_server_expired_.Start());
// Navigate to a site that causes an interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(
browser()->tab_strip_model()->GetActiveWebContents()));
// Simulate clicking the learn more link.
SendInterstitialCommand(browser()->tab_strip_model()->GetActiveWebContents(),
security_interstitials::CMD_OPEN_HELP_CENTER);
EXPECT_EQ(browser()
->tab_strip_model()
->GetActiveWebContents()
->GetVisibleURL()
.ref(),
base::NumberToString(net::ERR_CERT_DATE_INVALID));
}
// Checks that interstitials are not used for subframe SSL errors. Regression
// test for https://crbug.com/808797.
IN_PROC_BROWSER_TEST_F(SSLUITest, SubframeCertError) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/title1.html")));
// Insert a broken-HTTPS iframe on the page and check that a generic net
// error, not a certificate error page, is shown.
content::TestNavigationObserver observer(tab, 1);
std::string insert_frame = base::StringPrintf(
"var i = document.createElement('iframe');"
"i.src = '%s';"
"document.body.appendChild(i);",
https_server_expired_.GetURL("/ssl/google.html").spec().c_str());
EXPECT_TRUE(content::ExecJs(tab, insert_frame));
observer.Wait();
content::RenderFrameHost* child =
content::ChildFrameAt(tab->GetPrimaryMainFrame(), 0);
ASSERT_TRUE(child);
const std::string javascript = base::StringPrintf(
"(document.querySelector(\"#proceed-link\") === null) "
"? (%d) : (%d)",
security_interstitials::CMD_TEXT_NOT_FOUND,
security_interstitials::CMD_TEXT_FOUND);
int result = content::EvalJs(child, javascript).ExtractInt();
EXPECT_EQ(security_interstitials::CMD_TEXT_NOT_FOUND, result);
}
// Verifies that a non-overridable interstitial does not have a proceed link.
IN_PROC_BROWSER_TEST_F(SSLUITestHSTS, TestInterstitialOptionsNonOverridable) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
GURL::Replacements replacements;
replacements.SetHostStr(kHstsTestHostName);
GURL url = https_server_expired_.GetURL("/ssl/google.html")
.ReplaceComponents(replacements);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
// Since we are connecting to a different domain than the test server default,
// we also expect CERT_STATUS_COMMON_NAME_INVALID.
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID | net::CERT_STATUS_COMMON_NAME_INVALID,
AuthState::SHOWING_INTERSTITIAL);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
const std::string javascript = base::StringPrintf(
"(document.querySelector(\"#proceed-link\") === null) "
"? (%d) : (%d)",
security_interstitials::CMD_TEXT_NOT_FOUND,
security_interstitials::CMD_TEXT_FOUND);
int result =
content::EvalJs(tab->GetPrimaryMainFrame(), javascript).ExtractInt();
EXPECT_EQ(security_interstitials::CMD_TEXT_NOT_FOUND, result);
}
// Verifies that links in the interstitial open in a new tab.
// https://crbug.com/717616
IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialLinksOpenInNewTab) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
WebContents* interstitial_tab =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ASSERT_TRUE(
chrome_browser_interstitials::IsShowingSSLInterstitial(interstitial_tab));
ssl_test_util::CheckAuthenticationBrokenState(
interstitial_tab, net::CERT_STATUS_DATE_INVALID,
AuthState::SHOWING_INTERSTITIAL);
content::TestNavigationObserver nav_observer(nullptr);
nav_observer.StartWatchingNewWebContents();
SSLBlockingPage* ssl_interstitial =
static_cast<SSLBlockingPage*>(GetInterstitialPage(interstitial_tab));
security_interstitials::SecurityInterstitialControllerClient* client =
GetControllerClientFromSSLBlockingPage(ssl_interstitial);
// Mock out the help center URL so that our test will hit the test server
// instead of a real server.
// NOTE: The CMD_OPEN_HELP_CENTER code in
// components/security_interstitials/core/ssl_error_ui.cc ends up appending
// a path to whatever URL is passed to it. Since that path doesn't exist on
// our test server, this results in a 404. This is expected behavior, and
// things are still working as expected so long as the test passes!
const GURL mock_help_center_url = https_server_.GetURL("/title1.html");
client->SetBaseHelpCenterUrlForTesting(mock_help_center_url);
EXPECT_EQ(1, browser()->tab_strip_model()->count());
SendInterstitialCommand(interstitial_tab,
security_interstitials::CMD_OPEN_HELP_CENTER);
nav_observer.Wait();
EXPECT_EQ(2, browser()->tab_strip_model()->count());
WebContents* new_tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(new_tab);
EXPECT_EQ(mock_help_center_url.host(), new_tab->GetLastCommittedURL().host());
}
// Verifies that switching tabs, while showing interstitial page, will not
// affect the visibility of the interstitial.
// https://crbug.com/381439
IN_PROC_BROWSER_TEST_F(SSLUITest, InterstitialNotAffectedByHideShow) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(tab->GetRenderWidgetHostView()->IsShowing());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
EXPECT_TRUE(tab->GetRenderWidgetHostView()->IsShowing());
ASSERT_TRUE(AddTabAtIndex(0, https_server_.GetURL("/ssl/google.html"),
ui::PAGE_TRANSITION_TYPED));
EXPECT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(0, browser()->tab_strip_model()->active_index());
EXPECT_EQ(tab, browser()->tab_strip_model()->GetWebContentsAt(1));
EXPECT_FALSE(tab->GetRenderWidgetHostView()->IsShowing());
browser()->tab_strip_model()->ActivateTabAt(
1, TabStripUserGestureDetails(
TabStripUserGestureDetails::GestureType::kOther));
EXPECT_TRUE(tab->GetRenderWidgetHostView()->IsShowing());
}
// Verifies that if a bad certificate is seen for any host and the user proceeds
// through the interstitial, the decision to proceed is initially remembered.
// However, if this is followed by another visit, and a good certificate is seen
// for the same host, the original exception is forgotten.
IN_PROC_BROWSER_TEST_F(SSLUITestReduceSubresourceNotifications,
HasAllowExceptionForAnyHost) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
std::string https_server_expired_host =
https_server_expired_.GetURL("/ssl/google.html").host();
std::string https_server_host =
https_server_.GetURL("/ssl/google.html").host();
ASSERT_EQ(https_server_expired_host, https_server_host);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// First check that frame requests revoke the decision.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ProceedThroughInterstitial(tab);
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
EXPECT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
}
// Verifies that if a bad certificate is seen for any host and the user proceeds
// through the interstitial, the decision to proceed is initially remembered.
// However, if this is followed by another visit, and a good certificate is seen
// for the same host, the original exception is forgotten. The state of
// send_subresource_notification does not change in the Webcontents even after a
// good certificate has been seen until the browser process is restarted.
IN_PROC_BROWSER_TEST_F(
SSLUITestReduceSubresourceNotifications,
PRE_BadCertFollowedByGoodCertNavigationFollowedByRestart) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
std::string https_server_expired_host =
https_server_expired_.GetURL("/ssl/google.html").host();
std::string https_server_host =
https_server_.GetURL("/ssl/google.html").host();
ASSERT_EQ(https_server_expired_host, https_server_host);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// HTTPS-related warning exceptions have not been allowed by the user.
ASSERT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// Not sending subresource notifications since no HTTPS-exceptions have been
// allowed by the user.
ASSERT_FALSE(tab->GetSendSubresourceNotification());
// Navigate to a page with a certificate error.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Click through the interstitial.
ProceedThroughInterstitial(tab);
// HTTPS-related warning exception has been allowed by the user.
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// State in browser process has been updated, i.e., start renderers need to
// start sending subresource notifications.
EXPECT_TRUE(tab->GetSendSubresourceNotification());
// See a good certificate for the same host. This removes the allowed
// exception but `renderer_preferences_.send_subresource_notification_` is not
// set to false. This is because allowing and revoking HTTPS related warning
// exception is rare, and thus is update at the startup of the browser.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
EXPECT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
EXPECT_TRUE(tab->GetSendSubresourceNotification());
}
// Verifies that on browser restarts, we update `renderer_preferences_`
// according to state of allowed exceptions at browser start-up.
IN_PROC_BROWSER_TEST_F(SSLUITestReduceSubresourceNotifications,
BadCertFollowedByGoodCertNavigationFollowedByRestart) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
EXPECT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
EXPECT_FALSE(tab->GetSendSubresourceNotification());
}
// Tests whether any certificate error exceptions made are persisted across
// sessions. This also verifies persistence of `send_subresource_notification_`.
IN_PROC_BROWSER_TEST_F(SSLUITestReduceSubresourceNotifications,
PRE_CertDecisionPersistsSessions) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// HTTPS-related warning exceptions have not been allowed by the user.
ASSERT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// Not sending subresource notifications since no HTTPS-exceptions have been
// allowed by the user.
ASSERT_FALSE(tab->GetSendSubresourceNotification());
// Navigate to a page with a certificate error.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Click through the interstitial.
ProceedThroughInterstitial(tab);
// HTTPS-related warning exception has been allowed by the user.
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// renderer_preferences_.send_subresource_notification_ state updated.
EXPECT_TRUE(tab->GetSendSubresourceNotification());
}
IN_PROC_BROWSER_TEST_F(SSLUITestReduceSubresourceNotifications,
CertDecisionPersistsSessions) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// HTTPS-related warning exceptions has been allowed by the user in the past
// which has not expired.
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// State in browser persists after restart.
ASSERT_TRUE(tab->GetSendSubresourceNotification());
}
// Tests persistence of `send_subresource_notification_` when multiple bad
// certificates are allowed by the user.
IN_PROC_BROWSER_TEST_F(SSLUITestReduceSubresourceNotifications,
MultipleBadCertNavigations) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// HTTPS-related warning exceptions have not been allowed by the user.
ASSERT_FALSE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// Not sending subresource notifications since no HTTPS-exceptions have been
// allowed by the user.
ASSERT_FALSE(tab->GetSendSubresourceNotification());
// Navigate to a page with a certificate error.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
// Click through the interstitial.
ProceedThroughInterstitial(tab);
// HTTPS-related warning exception has been allowed by the user.
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
// renderer_preferences_.send_subresource_notification_ state updated.
EXPECT_TRUE(tab->GetSendSubresourceNotification());
// Navigate to a page with a certificate error, and click through the
// interstitial so the certificate is allowlisted.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL("https://site.test:" +
base::NumberToString(https_server_expired_.port()) +
"/ssl/blank_page.html")));
ProceedThroughInterstitial(tab);
// HTTPS-related warning exception has been allowed by the user.
EXPECT_TRUE(state->HasAllowExceptionForAnyHost(
tab->GetPrimaryMainFrame()->GetStoragePartition()));
EXPECT_TRUE(tab->GetSendSubresourceNotification());
}
// Verifies that if a bad certificate is seen for a host and the user proceeds
// through the interstitial, the decision to proceed is initially remembered.
// However, if this is followed by another visit, and a good certificate
// is seen for the same host, the original exception is forgotten.
IN_PROC_BROWSER_TEST_F(SSLUITest, BadCertFollowedByGoodCertNavigation) {
// It is necessary to use |https_server_expired_| rather than
// |https_server_mismatched| because the former shares a host with
// |https_server_| and cert exceptions are per host.
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
std::string https_server_expired_host =
https_server_expired_.GetURL("/ssl/google.html").host();
std::string https_server_host =
https_server_.GetURL("/ssl/google.html").host();
ASSERT_EQ(https_server_expired_host, https_server_host);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// First check that frame requests revoke the decision.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ProceedThroughInterstitial(tab);
EXPECT_TRUE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
EXPECT_FALSE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
}
// Verifies that if a bad certificate is seen for a host and the user proceeds
// through the interstitial, the decision to proceed is initially remembered.
// However, if this is followed by a subresource load, and a good certificate
// is seen for the same host via the subresource load, the original exception
// is forgotten.
IN_PROC_BROWSER_TEST_F(SSLUITest, BadCertFollowedByGoodCertSubresource) {
// As in SSLUITest.BadCertFollowedByGoodCertNavigation, it is necessary to use
// |https_server_expired_| rather than |https_server_mismatched| because the
// former shares a host with |https_server_| and cert exceptions are per host.
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
std::string https_server_expired_host =
https_server_expired_.GetURL("/ssl/google.html").host();
std::string https_server_host =
https_server_.GetURL("/ssl/google.html").host();
ASSERT_EQ(https_server_expired_host, https_server_host);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ProceedThroughInterstitial(tab);
EXPECT_TRUE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
GURL image = https_server_.GetURL("/ssl/google_files/logo.gif");
EXPECT_EQ(
true,
EvalJs(tab,
std::string("var img = document.createElement('img');img.src ='") +
image.spec() +
"';"
"new Promise(resolve => {"
" img.onload=function() { "
" resolve(true); };"
" document.body.appendChild(img);"
"});"));
EXPECT_FALSE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
}
// Verifies that if a bad certificate is seen for a host and the user proceeds
// through the interstitial, the decision to proceed is not forgotten once blob
// URLs are loaded (blob loads never have certificate errors). This is a
// regression test for https://crbug.com/1049625.
IN_PROC_BROWSER_TEST_F(SSLUITest, BadCertFollowedByBlobUrl) {
ASSERT_TRUE(https_server_expired_.Start());
std::string https_server_host =
https_server_expired_.GetURL("/ssl/google.html").host();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
StatefulSSLHostStateDelegate* state =
static_cast<StatefulSSLHostStateDelegate*>(
profile->GetSSLHostStateDelegate());
// Proceed through the interstitial, accepting the broken cert.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ProceedThroughInterstitial(tab);
ASSERT_TRUE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
// Load a blob URL.
content::WebContentsConsoleObserver console_observer(tab);
console_observer.SetPattern("hello from blob");
const char kScript[] = R"(
new Promise(function (resolvePromise, rejectPromise) {
var blob = new Blob(['console.log("hello from blob")'],
{type : 'application/javascript'});
script = document.createElement('script');
script.onerror = rejectPromise;
script.onload = () => resolvePromise('success');
script.src = URL.createObjectURL(blob);
document.body.appendChild(script);
});
)";
ASSERT_EQ("success", content::EvalJs(tab, kScript));
// Verify that the script from the blob has successfully run.
ASSERT_TRUE(console_observer.Wait());
// Verify that the decision to accept the broken cert has not been revoked
// (this is a regression test for https://crbug.com/1049625).
EXPECT_TRUE(state->HasAllowException(
https_server_host, tab->GetPrimaryMainFrame()->GetStoragePartition()));
}
// Tests that the SSLStatus of a navigation entry for an SSL
// interstitial matches the navigation entry once the interstitial is
// clicked through. https://crbug.com/529456
IN_PROC_BROWSER_TEST_F(SSLUITest,
SSLStatusMatchesOnInterstitialAndAfterProceed) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
EXPECT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
content::NavigationEntry* entry = tab->GetController().GetVisibleEntry();
ASSERT_TRUE(entry);
content::SSLStatus interstitial_ssl_status = entry->GetSSL();
ProceedThroughInterstitial(tab);
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(tab));
entry = tab->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
content::SSLStatus after_interstitial_ssl_status = entry->GetSSL();
EXPECT_TRUE(ComparePreAndPostInterstitialSSLStatuses(
interstitial_ssl_status, after_interstitial_ssl_status));
}
// As above, but for a bad clock interstitial. Tests that a clock
// interstitial's SSLStatus matches the SSLStatus of the HTTPS page
// after proceeding through a normal SSL interstitial.
IN_PROC_BROWSER_TEST_F(SSLUITest,
SSLStatusMatchesonClockInterstitialAndAfterProceed) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
// Set up the build and current clock times to be more than a year apart.
base::SimpleTestClock mock_clock;
mock_clock.SetNow(base::Time::NowFromSystemTime());
mock_clock.Advance(base::Days(367));
SSLErrorHandler::SetClockForTesting(&mock_clock);
ssl_errors::SetBuildTimeForTesting(base::Time::NowFromSystemTime());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingBadClockInterstitial(tab));
// Grab the SSLStatus on the clock interstitial.
content::NavigationEntry* entry = tab->GetController().GetVisibleEntry();
ASSERT_TRUE(entry);
content::SSLStatus clock_interstitial_ssl_status = entry->GetSSL();
// Put the clock back to normal, trigger a normal SSL interstitial,
// and proceed through it.
mock_clock.SetNow(base::Time::NowFromSystemTime());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/title1.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
ProceedThroughInterstitial(tab);
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(tab));
// Grab the SSLStatus from the page and check that it is the same as
// on the clock interstitial.
entry = tab->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
content::SSLStatus after_interstitial_ssl_status = entry->GetSSL();
EXPECT_TRUE(ComparePreAndPostInterstitialSSLStatuses(
clock_interstitial_ssl_status, after_interstitial_ssl_status));
}
// A fixture for testing on-demand network time queries on SSL
// certificate date errors. It can simulate a delayed network time
// request, and it allows the user to configure the experimental
// parameters of the NetworkTimeTracker. Expects only one network time
// request to be issued during the test.
class SSLNetworkTimeBrowserTest : public SSLUITest {
public:
SSLNetworkTimeBrowserTest() : SSLUITest() {
scoped_feature_list_.InitAndEnableFeatureWithParameters(
network_time::kNetworkTimeServiceQuerying,
{{"FetchBehavior", "on-demand-only"}});
}
SSLNetworkTimeBrowserTest(const SSLNetworkTimeBrowserTest&) = delete;
SSLNetworkTimeBrowserTest& operator=(const SSLNetworkTimeBrowserTest&) =
delete;
~SSLNetworkTimeBrowserTest() override = default;
void SetUpOnMainThread() override {
SSLUITest::SetUpOnMainThread();
controllable_response_ =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/", true);
ASSERT_TRUE(embedded_test_server()->Start());
g_browser_process->network_time_tracker()->SetTimeServerURLForTesting(
embedded_test_server()->GetURL("/"));
}
protected:
void TriggerTimeResponse() {
std::string response = "HTTP/1.1 200 OK\nContent-type: text/plain\n";
response += base::StringPrintf(
"Content-Length: %1d\n",
static_cast<int>(strlen(network_time::kGoodTimeResponseBody[0])));
response +=
"x-cup-server-proof: " +
std::string(network_time::kGoodTimeResponseServerProofHeader[0]);
response += "\n\n";
response += std::string(network_time::kGoodTimeResponseBody[0]);
controllable_response_->WaitForRequest();
controllable_response_->Send(response);
}
// Asserts that the first time request to the server is currently pending.
void CheckTimeQueryPending() {
base::Time unused_time;
base::TimeDelta unused_uncertainty;
ASSERT_EQ(network_time::NetworkTimeTracker::NETWORK_TIME_FIRST_SYNC_PENDING,
g_browser_process->network_time_tracker()->GetNetworkTime(
&unused_time, &unused_uncertainty));
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<net::test_server::ControllableHttpResponse>
controllable_response_;
};
// Tests that if an on-demand network time fetch returns that the clock
// is okay, a normal SSL interstitial is shown.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, OnDemandFetchClockOk) {
ASSERT_TRUE(https_server_expired_.Start());
// Use a testing clock set to the time that GoodTimeResponseHandler
// returns, to simulate the system clock matching the network time.
base::SimpleTestClock testing_clock;
SSLErrorHandler::SetClockForTesting(&testing_clock);
testing_clock.SetNow(base::Time::FromMillisecondsSinceUnixEpoch(
network_time::kGoodTimeResponseHandlerJsTime[0]));
// Set the build time to match the testing clock, to ensure that the
// build time heuristic doesn't fire.
ssl_errors::SetBuildTimeForTesting(testing_clock.Now());
// Set a long timeout to ensure that the on-demand time fetch completes.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_expired_.GetURL("/"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
// Once |interstitial_timer_observer| has fired, the request has been
// sent. Override the nonce that NetworkTimeTracker expects so that
// when the response comes back, it will validate. The nonce can only
// be overriden for the current in-flight request, so the test must
// call OverrideNonceForTesting() after the request has been sent and
// before the response has been received.
interstitial_timer_observer.WaitForTimerStarted();
g_browser_process->network_time_tracker()->OverrideNonceForTesting(123123123);
TriggerTimeResponse();
EXPECT_TRUE(contents->IsLoading());
// False, because an interstitial is not a normal load result.
EXPECT_FALSE(content::WaitForLoadStop(contents));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
}
// Tests that if an on-demand network time fetch returns that the clock
// is wrong, a bad clock interstitial is shown.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, OnDemandFetchClockWrong) {
ASSERT_TRUE(https_server_expired_.Start());
// Use a testing clock set to a time that is different from what
// GoodTimeResponseHandler returns, simulating a system clock that is
// 30 days ahead of the network time.
base::SimpleTestClock testing_clock;
SSLErrorHandler::SetClockForTesting(&testing_clock);
testing_clock.SetNow(base::Time::FromMillisecondsSinceUnixEpoch(
network_time::kGoodTimeResponseHandlerJsTime[0]));
testing_clock.Advance(base::Days(30));
// Set the build time to match the testing clock, to ensure that the
// build time heuristic doesn't fire.
ssl_errors::SetBuildTimeForTesting(testing_clock.Now());
// Set a long timeout to ensure that the on-demand time fetch completes.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_expired_.GetURL("/"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
// Once |interstitial_timer_observer| has fired, the request has been
// sent. Override the nonce that NetworkTimeTracker expects so that
// when the response comes back, it will validate. The nonce can only
// be overriden for the current in-flight request, so the test must
// call OverrideNonceForTesting() after the request has been sent and
// before the response has been received.
interstitial_timer_observer.WaitForTimerStarted();
g_browser_process->network_time_tracker()->OverrideNonceForTesting(123123123);
TriggerTimeResponse();
EXPECT_TRUE(contents->IsLoading());
// False, because an interstitial is not a normal load result.
EXPECT_FALSE(content::WaitForLoadStop(contents));
ASSERT_TRUE(
chrome_browser_interstitials::IsShowingBadClockInterstitial(contents));
}
// Tests that if the timeout expires before the network time fetch
// returns, then a normal SSL interstitial is shown.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest,
TimeoutExpiresBeforeFetchCompletes) {
ASSERT_TRUE(https_server_expired_.Start());
// Set the timer to fire immediately.
SSLErrorHandler::SetInterstitialDelayForTesting(base::TimeDelta());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
https_server_expired_.GetURL("/")));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
// Navigate away, and then trigger the network time response; no crash should
// occur.
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_.GetURL("/")));
ASSERT_NO_FATAL_FAILURE(CheckTimeQueryPending());
TriggerTimeResponse();
}
// Tests that if the user stops the page load before either the network
// time fetch completes or the timeout expires, then there is no interstitial.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, StopBeforeTimeoutExpires) {
ASSERT_TRUE(https_server_expired_.Start());
// Set the timer to a long delay.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_expired_.GetURL("/"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
contents->Stop();
EXPECT_TRUE(content::WaitForLoadStop(contents));
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(SSLErrorHandler::FromWebContents(contents));
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
// Navigate away, and then trigger the network time response; no crash should
// occur.
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/title1.html")));
ASSERT_NO_FATAL_FAILURE(CheckTimeQueryPending());
TriggerTimeResponse();
}
// Tests that if the user reloads the page before either the network
// time fetch completes or the timeout expires, then there is no interstitial.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, ReloadBeforeTimeoutExpires) {
ASSERT_TRUE(https_server_expired_.Start());
// Set the timer to a long delay.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_expired_.GetURL("/"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
content::TestNavigationObserver observer(contents);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
observer.Wait();
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(SSLErrorHandler::FromWebContents(contents));
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
// Navigate away, and then trigger the network time response and wait
// for the response; no crash should occur.
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_.GetURL("/")));
ASSERT_NO_FATAL_FAILURE(CheckTimeQueryPending());
TriggerTimeResponse();
}
// Tests that if the user navigates away before either the network time
// fetch completes or the timeout expires, then there is no
// interstitial.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest,
NavigateAwayBeforeTimeoutExpires) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(https_server_.Start());
// Set the timer to a long delay.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_expired_.GetURL("/"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
content::TestNavigationObserver observer(contents, 1);
browser()->OpenURL(
content::OpenURLParams(https_server_.GetURL("/"), content::Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false),
/*navigation_handle_callback=*/{});
observer.Wait();
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(SSLErrorHandler::FromWebContents(contents));
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
// Navigate away, and then trigger the network time response and wait
// for the response; no crash should occur.
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_.GetURL("/")));
ASSERT_NO_FATAL_FAILURE(CheckTimeQueryPending());
TriggerTimeResponse();
}
// Tests that if the user closes the tab before the network time fetch
// completes, it doesn't cause a crash.
IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest,
CloseTabBeforeNetworkFetchCompletes) {
ASSERT_TRUE(https_server_expired_.Start());
// Set the timer to fire immediately.
SSLErrorHandler::SetInterstitialDelayForTesting(base::TimeDelta());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
https_server_expired_.GetURL("/")));
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
// Open a second tab, close the first, and then trigger the network time
// response and wait for the response; no crash should occur.
ASSERT_TRUE(https_server_.Start());
ASSERT_FALSE(
AddTabAtIndex(1, https_server_.GetURL("/"), ui::PAGE_TRANSITION_TYPED));
chrome::CloseWebContents(browser(), contents, false);
ASSERT_NO_FATAL_FAILURE(CheckTimeQueryPending());
TriggerTimeResponse();
}
class CommonNameMismatchBrowserTest : public CertVerifierBrowserTest {
public:
CommonNameMismatchBrowserTest() : CertVerifierBrowserTest() {
// Enable finch experiment for SSL common name mismatch handling.
base::FieldTrialList::CreateFieldTrial("SSLCommonNameMismatchHandling",
"Enabled");
}
void SetUpOnMainThread() override {
CertVerifierBrowserTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
}
void TearDownOnMainThread() override {
CertVerifierBrowserTest::TearDownOnMainThread();
}
};
// Visit the URL www.mail.example.com on a server that presents a valid
// certificate for mail.example.com. Verify that the page navigates to
// mail.example.com.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
ShouldShowWWWSubdomainMismatchInterstitial) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
// Use the "spdy_pooling.pem" cert which has "mail.example.com"
// as one of its SANs.
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
// Request to "www.mail.example.com" should result in
// |net::ERR_CERT_COMMON_NAME_INVALID| error.
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "www.mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
// Request to "www.mail.example.com" should not result in any error.
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "mail.example.com",
verify_result_valid, net::OK);
// Use a complex URL to ensure the path, etc., are preserved. The path itself
// does not matter.
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b#anchor");
GURL::Replacements replacements;
replacements.SetHostStr("www.mail.example.com");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver observer(contents, 1);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_mismatched_url));
observer.Wait();
ssl_test_util::CheckSecurityState(contents, CertError::NONE,
security_state::SECURE, AuthState::NONE);
replacements.SetHostStr("mail.example.com");
GURL https_server_new_url = https_server_url.ReplaceComponents(replacements);
// Verify that the current URL is the suggested URL.
EXPECT_EQ(https_server_new_url.spec(),
contents->GetLastCommittedURL().spec());
}
// Visit the URL www.mail.example.com on a server that presents an invalid
// certificate for mail.example.com. Verify that the page shows an interstitial
// for www.mail.example.com with no crash.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
NoCrashIfBothSubdomainsHaveCommonNameErrors) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
// Use the "spdy_pooling.pem" cert which has "mail.example.com"
// as one of its SANs.
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
// Request to "www.mail.example.com" should result in
// |net::ERR_CERT_COMMON_NAME_INVALID| error.
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "www.mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
// Request to "mail.example.com" should also result in
// |net::ERR_CERT_COMMON_NAME_INVALID| error.
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
// Use a complex URL to ensure the path, etc., are preserved. The path itself
// does not matter.
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b#anchor");
GURL::Replacements replacements;
replacements.SetHostStr("www.mail.example.com");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
// Should simply show an interstitial, because both subdomains have common
// name errors.
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_mismatched_url));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(contents));
ssl_test_util::CheckSecurityState(
contents, net::CERT_STATUS_COMMON_NAME_INVALID, security_state::DANGEROUS,
AuthState::SHOWING_INTERSTITIAL);
}
// Visit the URL example.org on a server that presents a valid certificate
// for www.example.org. Verify that the page redirects to www.example.org.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
CheckWWWSubdomainMismatchInverse) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "example.org", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "www.example.org",
verify_result_valid, net::OK);
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b");
GURL::Replacements replacements;
replacements.SetHostStr("example.org");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver observer(contents, 1);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_mismatched_url));
observer.Wait();
ssl_test_util::CheckSecurityState(contents, CertError::NONE,
security_state::SECURE, AuthState::NONE);
}
namespace {
// Redirects incoming request to http://example.org.
std::unique_ptr<net::test_server::HttpResponse> HTTPSToHTTPRedirectHandler(
const net::EmbeddedTestServer* test_server,
const net::test_server::HttpRequest& request) {
GURL::Replacements replacements;
replacements.SetHostStr("example.org");
replacements.SetSchemeStr("http");
const GURL redirect_url =
test_server->base_url().ReplaceComponents(replacements);
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location", redirect_url.spec());
return std::move(http_response);
}
} // namespace
// Common name mismatch handling feature should ignore redirects when pinging
// the suggested hostname. Visit the URL example.org on a server that presents a
// valid certificate for www.example.org. In this case, www.example.org
// redirects to http://example.org, and the SSL error should not be redirected
// to this URL.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
WWWSubdomainMismatch_StopOnRedirects) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
// Redirect all URLs to http://example.org. Since this test will trigger only
// one request to check the suggested URL, redirecting all requests is OK.
// We would normally use content::SetupCrossSiteRedirector here, but that
// function does not support https to http redirects.
// This must be done before ServeFilesFromSourceDirectory(), otherwise the
// test server will serve files instead of redirecting requests to them.
https_server_example_domain.RegisterRequestHandler(base::BindRepeating(
&HTTPSToHTTPRedirectHandler, &https_server_example_domain));
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "example.org", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "www.example.org",
verify_result_valid, net::OK);
// The user will visit https://example.org:port/ssl/blank.html.
GURL::Replacements replacements;
replacements.SetHostStr("example.org");
const GURL https_server_mismatched_url =
https_server_example_domain.GetURL("/ssl/blank.html")
.ReplaceComponents(replacements);
// Should simply show an interstitial, because the suggested URL
// (https://www.example.org) redirected to http://example.org.
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server_mismatched_url));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(contents));
ssl_test_util::CheckSecurityState(
contents, net::CERT_STATUS_COMMON_NAME_INVALID, security_state::DANGEROUS,
AuthState::SHOWING_INTERSTITIAL);
}
// Tests this scenario:
// - |CommonNameMismatchHandler| does not give a callback as it's set into the
// state |IGNORE_REQUESTS_FOR_TESTING|. So no suggested URL check result can
// arrive.
// - A cert error triggers an interstitial timer with a very long timeout.
// - No suggested URL check results arrive, causing the tab to appear as loading
// indefinitely (also because the timer has a long timeout).
// - Stopping the page load shouldn't result in any interstitials.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
InterstitialStopNavigationWhileLoading) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "www.mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "mail.example.com",
verify_result_valid, net::OK);
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b");
GURL::Replacements replacements;
replacements.SetHostStr("www.mail.example.com");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
CommonNameMismatchHandler::set_state_for_testing(
CommonNameMismatchHandler::IGNORE_REQUESTS_FOR_TESTING);
// Set delay long enough so that the page appears loading.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_mismatched_url,
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
contents->Stop();
EXPECT_TRUE(content::WaitForLoadStop(contents));
SSLErrorHandler* ssl_error_handler =
SSLErrorHandler::FromWebContents(contents);
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(ssl_error_handler);
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
}
// Same as above, but instead of stopping, the loading page is reloaded. The end
// result is the same. (i.e. page load stops, no interstitials shown)
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
InterstitialReloadNavigationWhileLoading) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "www.mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "mail.example.com",
verify_result_valid, net::OK);
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b");
GURL::Replacements replacements;
replacements.SetHostStr("www.mail.example.com");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
CommonNameMismatchHandler::set_state_for_testing(
CommonNameMismatchHandler::IGNORE_REQUESTS_FOR_TESTING);
// Set delay long enough so that the page appears loading.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_mismatched_url,
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
content::TestNavigationObserver observer(contents, 1);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
observer.Wait();
SSLErrorHandler* ssl_error_handler =
SSLErrorHandler::FromWebContents(contents);
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(ssl_error_handler);
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
}
// Same as above, but instead of reloading, the page is navigated away. The
// new page should load, and no interstitials should be shown.
IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest,
InterstitialNavigateAwayWhileLoading) {
net::EmbeddedTestServer https_server_example_domain(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_example_domain.ServeFilesFromSourceDirectory(
GetChromeTestDataDir());
ASSERT_TRUE(https_server_example_domain.Start());
scoped_refptr<net::X509Certificate> cert =
https_server_example_domain.GetCertificate();
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
mock_cert_verifier()->AddResultForCertAndHost(
cert.get(), "www.mail.example.com", verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
net::CertVerifyResult verify_result_valid;
verify_result_valid.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "spdy_pooling.pem");
mock_cert_verifier()->AddResultForCertAndHost(cert.get(), "mail.example.com",
verify_result_valid, net::OK);
const GURL https_server_url =
https_server_example_domain.GetURL("/ssl/google.html?a=b");
GURL::Replacements replacements;
replacements.SetHostStr("www.mail.example.com");
const GURL https_server_mismatched_url =
https_server_url.ReplaceComponents(replacements);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
CommonNameMismatchHandler::set_state_for_testing(
CommonNameMismatchHandler::IGNORE_REQUESTS_FOR_TESTING);
// Set delay long enough so that the page appears loading.
SSLErrorHandler::SetInterstitialDelayForTesting(base::Hours(1));
SSLInterstitialTimerObserver interstitial_timer_observer(contents);
ui_test_utils::NavigateToURLWithDisposition(
browser(), https_server_mismatched_url,
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
interstitial_timer_observer.WaitForTimerStarted();
EXPECT_TRUE(contents->IsLoading());
content::TestNavigationObserver observer(contents, 1);
browser()->OpenURL(
content::OpenURLParams(GURL("https://google.com"), content::Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false),
/*navigation_handle_callback=*/{});
observer.Wait();
SSLErrorHandler* ssl_error_handler =
SSLErrorHandler::FromWebContents(contents);
// Make sure that the |SSLErrorHandler| is deleted.
EXPECT_FALSE(ssl_error_handler);
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(contents));
EXPECT_FALSE(contents->IsLoading());
}
class SSLBlockingPageIDNTest
: public chrome_browser_interstitials::SecurityInterstitialIDNTest {
protected:
// chrome_browser_interstitials::SecurityInterstitialIDNTest:
security_interstitials::SecurityInterstitialPage* CreateInterstitial(
WebContents* contents,
const GURL& request_url) const override {
net::SSLInfo ssl_info;
ssl_info.cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
ChromeSecurityBlockingPageFactory blocking_page_factory;
return blocking_page_factory
.CreateSSLPage(contents, net::ERR_CERT_CONTAINS_ERRORS, ssl_info,
request_url, 0, base::Time::NowFromSystemTime(), GURL())
.release();
}
};
// Flaky on mac OS and Windows: https://crbug.com/689846
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
#define MAYBE_SSLBlockingPageDecodesIDN DISABLED_SSLBlockingPageDecodesIDN
#else
#define MAYBE_SSLBlockingPageDecodesIDN SSLBlockingPageDecodesIDN
#endif
IN_PROC_BROWSER_TEST_F(SSLBlockingPageIDNTest,
MAYBE_SSLBlockingPageDecodesIDN) {
EXPECT_TRUE(VerifyIDNDecoded());
}
IN_PROC_BROWSER_TEST_F(CertVerifierBrowserTest, MockCertVerifierSmokeTest) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
ASSERT_TRUE(https_server.Start());
mock_cert_verifier()->set_default_result(
net::ERR_CERT_NAME_CONSTRAINT_VIOLATION);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server.GetURL("/ssl/google.html")));
ssl_test_util::CheckSecurityState(
browser()->tab_strip_model()->GetActiveWebContents(),
net::CERT_STATUS_NAME_CONSTRAINT_VIOLATION, security_state::DANGEROUS,
AuthState::SHOWING_INTERSTITIAL);
}
IN_PROC_BROWSER_TEST_F(SSLUITest, RestoreHasSSLState) {
ASSERT_TRUE(https_server_.Start());
GURL url(https_server_.GetURL("/ssl/google.html"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
content::NavigationEntry* entry =
tab->GetController().GetLastCommittedEntry();
std::unique_ptr<content::NavigationEntry> restored_entry =
content::NavigationController::CreateNavigationEntry(
url, content::Referrer(), /* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, ui::PAGE_TRANSITION_RELOAD,
false, std::string(), tab->GetBrowserContext(),
nullptr /* blob_url_loader_factory */);
std::unique_ptr<content::NavigationEntryRestoreContext> context =
content::NavigationEntryRestoreContext::Create();
restored_entry->SetPageState(entry->GetPageState(), context.get());
WebContents::CreateParams params(tab->GetBrowserContext());
std::unique_ptr<WebContents> tab2 = WebContents::Create(params);
WebContents* raw_tab2 = tab2.get();
tab->GetDelegate()->AddNewContents(
nullptr, std::move(tab2), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
blink::mojom::WindowFeatures(), false, nullptr);
std::vector<std::unique_ptr<content::NavigationEntry>> entries;
entries.push_back(std::move(restored_entry));
content::TestNavigationObserver observer(raw_tab2);
raw_tab2->GetController().Restore(entries.size() - 1,
content::RestoreType::kRestored, &entries);
raw_tab2->GetController().LoadIfNecessary();
observer.Wait();
ssl_test_util::CheckAuthenticatedState(raw_tab2, AuthState::NONE);
}
void SetupRestoredTabWithNavigation(
net::test_server::EmbeddedTestServer* https_server,
Browser* browser) {
ASSERT_TRUE(https_server->Start());
GURL url(https_server->GetURL("/ssl/google.html"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser, url));
WebContents* tab = browser->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver observer(tab);
EXPECT_TRUE(ExecJs(tab, "history.pushState({}, '', '');"));
observer.Wait();
ui_test_utils::NavigateToURLWithDisposition(
browser, GURL("about:blank"), WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
chrome::CloseTab(browser);
WebContents* blank_tab = browser->tab_strip_model()->GetActiveWebContents();
// Restore the tab.
ui_test_utils::TabAddedWaiter tab_added_waiter(browser);
chrome::RestoreTab(browser);
tab_added_waiter.Wait();
tab = browser->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(tab));
EXPECT_NE(tab, blank_tab);
}
// Simulate a browser-initiated in-page navigation in a restored tab.
// https://crbug.com/662267
IN_PROC_BROWSER_TEST_F(SSLUITest,
BrowserInitiatedExistingPageAfterRestoreHasSSLState) {
SetupRestoredTabWithNavigation(&https_server_, browser());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Simulate a renderer-initiated in-page navigation in a restored tab.
IN_PROC_BROWSER_TEST_F(SSLUITest,
RendererInitiatedExistingPageAfterRestoreHasSSLState) {
SetupRestoredTabWithNavigation(&https_server_, browser());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
content::TestNavigationObserver observer(tab);
ASSERT_TRUE(
content::ExecJs(tab, "location.replace(window.location.href + '#1')"));
observer.Wait();
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
namespace {
// A handler which changes the response. The first time it's called for
// |relative_url| it'll give an empty response. The second time it'll
// redirect to |redirect_url|.
std::unique_ptr<net::test_server::HttpResponse> ChangingHandler(
int* count,
const std::string& relative_url,
const GURL& redirect_url,
const net::test_server::HttpRequest& request) {
if (request.relative_url != relative_url)
return nullptr;
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
if ((*count)++) {
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location", redirect_url.spec());
}
return std::move(http_response);
}
} // namespace
// Check that SSL state isn't stale when navigating to an existing page that
// gives a different response. This covers the case of going from http to
// https. http://crbug.com/792221
IN_PROC_BROWSER_TEST_F(SSLUITest, ExistingPageHTTPToHTTPSSSLState) {
ASSERT_TRUE(https_server_.Start());
int count = 0;
std::string relative_url = "/foo";
GURL redirect_url = https_server_.GetURL("/simple.html");
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(ChangingHandler, &count, relative_url, redirect_url));
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url = embedded_test_server()->GetURL(relative_url);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
content::TestNavigationObserver observer(tab, 1);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
observer.Wait();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Check that SSL state isn't stale when navigating to an existing page that
// gives a different response. This covers the case of going from https to
// http URL. http://crbug.com/792221
IN_PROC_BROWSER_TEST_F(SSLUITest, ExistingPageHTTPSToHTTPSSLState) {
ASSERT_TRUE(embedded_test_server()->Start());
int count = 0;
std::string relative_url = "/foo";
GURL redirect_url = embedded_test_server()->GetURL("/simple.html");
https_server_.RegisterRequestHandler(
base::BindRepeating(ChangingHandler, &count, relative_url, redirect_url));
ASSERT_TRUE(https_server_.Start());
const GURL url = https_server_.GetURL(relative_url);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
content::TestNavigationObserver observer(tab, 1);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
observer.Wait();
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// We also manually check the cert on the NavigationEntry, since in the case
// of http URLs GetSecurityLevelForRequest will return SecurityLevel::NONE for
// http URLs.
content::NavigationEntry* entry = tab->GetController().GetVisibleEntry();
ASSERT_FALSE(entry->GetSSL().certificate);
}
// Checks that a restore followed immediately by a history navigation doesn't
// lose SSL state.
// Disabled since this is a test for bug 738177.
IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_RestoreThenNavigateHasSSLState) {
ASSERT_TRUE(https_server_.Start());
GURL url1(https_server_.GetURL("/ssl/google.html"));
GURL url2(https_server_.GetURL("/ssl/page_with_refs.html"));
ui_test_utils::NavigateToURLWithDisposition(
browser(), url1, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url2));
chrome::CloseTab(browser());
ui_test_utils::TabAddedWaiter tab_added_waiter(browser());
chrome::RestoreTab(browser());
tab_added_waiter.Wait();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationManager observer(tab, url1);
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
ASSERT_TRUE(observer.WaitForNavigationFinished());
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Simulate the URL changing when the user presses enter in the omnibox. This
// could happen when the user's login is expired and the server redirects them
// to a login page. This will be considered a same document navigation but we
// do want to update the SSL state.
IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentHasSSLState) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to a simple page and then perform an in-page navigation.
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), start_url));
GURL fragment_change_url(embedded_test_server()->GetURL("/title1.html#foo"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), fragment_change_url));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
// Replace the URL of the current NavigationEntry with one that will cause
// a server redirect when loaded.
{
GURL redirect_dest_url(https_server_.GetURL("/ssl/google.html"));
content::TestNavigationObserver observer(tab);
std::string script = "history.replaceState({}, '', '/server-redirect?" +
redirect_dest_url.spec() + "')";
EXPECT_TRUE(ExecJs(tab, script));
observer.Wait();
}
// Simulate the user hitting Enter in the omnibox without changing the URL.
{
content::TestNavigationObserver observer(tab);
tab->GetController().LoadURL(tab->GetLastCommittedURL(),
content::Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
observer.Wait();
}
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Simulate the user revisiting a page without triggering a reload (e.g., when
// clicking a bookmark with an anchor hash twice). As this is a same document
// navigation, the SSL state should be left intact despite not triggering a
// network request. Regression test for https://crbug.com/877618.
IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentHasSSLStateNoLoad) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
GURL start_url(https_server_.GetURL("/ssl/google.html#foo"));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), start_url));
// Simulate clicking on a bookmark.
{
content::LoadStopObserver observer(tab);
NavigateParams navigate_params(browser(), start_url,
ui::PAGE_TRANSITION_AUTO_BOOKMARK);
Navigate(&navigate_params);
observer.Wait();
}
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Checks that if a client redirect occurs while the page is loading, the SSL
// state reflects the final URL.
IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectSSLState) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
GURL https_url = https_server_.GetURL("/ssl/redirect.html?");
GURL http_url = embedded_test_server()->GetURL("/ssl/google.html");
GURL url(https_url.spec() + http_url.spec());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationManager navigation_observer_https(tab, url);
content::TestNavigationManager navigation_observer_http(tab, http_url);
tab->GetController().LoadURL(url, content::Referrer(),
ui::PAGE_TRANSITION_LINK, std::string());
ASSERT_TRUE(navigation_observer_https.WaitForNavigationFinished());
ASSERT_TRUE(navigation_observer_http.WaitForNavigationFinished());
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckUnauthenticatedState(tab, AuthState::NONE);
}
// Checks that if a redirect occurs while the page is loading from a mixed
// content to a valid HTTPS page, the SSL state reflects the final URL.
IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectFromMixedContentSSLState) {
ASSERT_TRUE(https_server_.Start());
GURL url = GURL(
https_server_.GetURL("/ssl/redirect_with_mixed_content.html").spec() +
"?" + https_server_.GetURL("/ssl/google.html").spec());
// Load a page that displays insecure content.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Checks that if a redirect occurs while the page is loading from a valid HTTPS
// page to a mixed content page, the SSL state reflects the final URL.
IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectToMixedContentSSLState) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
GURL redirect(https_server_.GetURL("/ssl/redirect.html"));
GURL final_url(
https_server_.GetURL("/ssl/page_displays_insecure_content.html"));
GURL url = GURL(redirect.spec() + "?" + final_url.spec());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationManager navigation_manager_redirect(tab, url);
content::TestNavigationManager navigation_manager_final_url(tab, final_url);
tab->GetController().LoadURL(url, content::Referrer(),
ui::PAGE_TRANSITION_LINK, std::string());
ASSERT_TRUE(navigation_manager_redirect.WaitForNavigationFinished());
ASSERT_TRUE(navigation_manager_final_url.WaitForNavigationFinished());
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckSecurityState(tab, CertError::NONE,
security_state::WARNING,
AuthState::DISPLAYED_INSECURE_CONTENT);
}
// Checks that same-document navigations during page load preserve SSL state.
IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentNavigationDuringLoadSSLState) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_.GetURL("/ssl/same_document_navigation_during_load.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Checks that same-document navigations after the page load preserve SSL
// state.
IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentNavigationAfterLoadSSLState) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(content::ExecJs(tab, "location.hash = Math.random()"));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Checks that navigations after pushState maintain the SSL status.
// Flaky, see https://crbug.com/872029 and https://crbug.com/872030.
IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_PushStateSSLState) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
content::TestNavigationObserver observer(tab);
EXPECT_TRUE(ExecJs(tab, "history.pushState({}, '', '');"));
observer.Wait();
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
EXPECT_TRUE(content::WaitForLoadStop(tab));
ssl_test_util::CheckAuthenticatedState(tab, AuthState::NONE);
}
// Regression test for http://crbug.com/635833 (crash when a window with no
// NavigationEntry commits).
IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreLocalhostCertErrors,
NoCrashOnLoadWithNoNavigationEntry) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(content::ExecJs(tab, "window.open()"));
}
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig>
MakeCaptivePortalConfig(int version_id,
const std::set<std::string>& spki_hashes) {
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(version_id);
for (const std::string& hash : spki_hashes) {
config_proto->add_captive_portal_cert()->set_sha256_hash(hash);
}
return config_proto;
}
// Tests the scenario where the OS reports a captive portal. A captive portal
// interstitial should be displayed. The test then switches OS captive portal
// status to false and reloads the page. This time, a normal SSL interstitial
// will be displayed.
IN_PROC_BROWSER_TEST_F(SSLUITest, OSReportsCaptivePortal) {
ASSERT_TRUE(https_server_mismatched_.Start());
base::HistogramTester histograms;
bool netwok_connectivity_reported = false;
SSLErrorHandler::SetOSReportsCaptivePortalForTesting(true);
SSLErrorHandler::SetReportNetworkConnectivityCallbackForTesting(
base::BindLambdaForTesting([&]() {
SSLErrorHandler::SetOSReportsCaptivePortalForTesting(false);
netwok_connectivity_reported = true;
}));
// Navigate to an unsafe page on the server.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/blank_page.html")));
ASSERT_TRUE(
chrome_browser_interstitials::IsShowingCaptivePortalInterstitial(tab));
EXPECT_FALSE(interstitial_timer_observer.timer_started());
// Check that the histogram for the captive portal cert was recorded.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(), 3);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_CAPTIVE_PORTAL_INTERSTITIAL_OVERRIDABLE, 1);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::OS_REPORTS_CAPTIVE_PORTAL, 1);
// Reload the URL. This time the OS should not report a captive portal.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_mismatched_.GetURL("/ssl/blank_page.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(netwok_connectivity_reported);
}
// Tests that the committed interstitial flag triggers the code path to show an
// error PageType instead of an interstitial PageType.
IN_PROC_BROWSER_TEST_F(SSLUITest, ErrorPage) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ssl_test_util::CheckSecurityState(tab, net::CERT_STATUS_DATE_INVALID,
security_state::DANGEROUS,
AuthState::SHOWING_ERROR);
content::NavigationEntry* entry = tab->GetController().GetVisibleEntry();
EXPECT_EQ(content::PAGE_TYPE_ERROR, entry->GetPageType());
}
using security_interstitials::InsecureFormNavigationThrottle;
// Visits a page that displays an insecure form inside an iframe, attempts to
// submit the form, and checks an interstitial is not shown (submissions of
// mixed forms inside iframes are separately blocked, and that behavior is
// tested in mixed_content_navigation_throttle_unittest.cc).
IN_PROC_BROWSER_TEST_F(
SSLUITest,
TestDoesNotDisplayInsecureFormSubmissionWarningInIframe) {
ChromeContentBrowserClientForMixedContentTest browser_client;
browser_client.SetMixedContentSettings(
false, /* allow_running_insecure_content */
false, /* strict_mixed_content_checking */
false /*strictly_block_blockable_mixed_content */);
content::ScopedContentBrowserClientSetting setting(&browser_client);
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
tab->OnWebPreferencesChanged();
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form_in_iframe.html",
https_server_.host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
content::TestNavigationObserver nav_observer(tab, 1);
content::WebContentsConsoleObserver console_observer(tab);
console_observer.SetPattern(
"Mixed Content: The page at * was loaded over a secure connection, but "
"contains a form that targets an insecure endpoint "
"'http://does-not-exist.test/ssl/google_files/logo.gif'. This endpoint "
"should be made available over a secure connection.");
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
// We shouldn't be displaying an interstitial.
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_FALSE(helper);
// Check console message was printed.
EXPECT_EQ(console_observer.messages().size(), 1u);
}
// Checks insecure form warning works for forms that submit on a new tab.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningTargetBlank) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form_target_blank.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
nav_observer.StartWatchingNewWebContents();
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
tab = browser()->tab_strip_model()->GetActiveWebContents();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
}
// Checks reloading the interstitial is not treated as proceeding on a POST
// form.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestReloadInsecureFormSubmissionWarningIsNotProceed) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
// Navigate to an insecure form, make sure we get a warning.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Reload the interstitial.
content::TestNavigationObserver reload_observer(tab, 1);
tab->GetController().Reload(content::ReloadType::NORMAL, false);
reload_observer.Wait();
// Check we get another interstitial.
helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
}
// Checks reloading the interstitial is not treated as proceeding on a GET form.
IN_PROC_BROWSER_TEST_F(
SSLUITest,
TestReloadInsecureFormSubmissionWarningIsNotProceedGetForm) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form_get.html",
embedded_test_server()->host_port_pair());
// Navigate to an insecure form that uses the GET method, make sure we get a
// warning.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Reload the interstitial.
content::TestNavigationObserver reload_observer(tab, 1);
tab->GetController().Reload(content::ReloadType::NORMAL, false);
reload_observer.Wait();
// Check we get another interstitial.
helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
}
// Checks navigating back and forward from the interstitial is not treated as
// proceeding on a GET form.
IN_PROC_BROWSER_TEST_F(
SSLUITest,
TestBackForwardOnInsecureFormSubmissionWarningIsNotProceedGetForm) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form_get.html",
embedded_test_server()->host_port_pair());
// Navigate to an insecure form that uses the GET method, make sure we get a
// warning.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Navigate back, then forward.
content::TestNavigationObserver back_observer(tab, 1);
tab->GetController().GoBack();
back_observer.Wait();
content::TestNavigationObserver forward_observer(tab, 1);
tab->GetController().GoForward();
forward_observer.Wait();
// Check we get another interstitial.
helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
// Currently the interstitial is only displayed when back/forward cache is
// enabled, so return early when the feature is disabled.
// TODO(crbug.com/40243001): Fix this.
if (!content::BackForwardCache::IsBackForwardCacheFeatureEnabled()) {
EXPECT_FALSE(helper->IsDisplayingInterstitial());
return;
}
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
}
// Check proceed works correctly on insecure form warning.
IN_PROC_BROWSER_TEST_F(SSLUITest, ProceedThroughInsecureFormWarning) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
GURL form_target_url("http://does-not-exist.test/ssl/google_files/logo.gif");
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// After clicking Proceed, we should not be on an interstitial, and be
// on the form target url;
ProceedThroughInterstitial(tab);
EXPECT_FALSE(helper->IsDisplayingInterstitial());
EXPECT_EQ(tab->GetVisibleURL(), form_target_url);
}
// Check don't proceed works correctly on insecure form warning.
IN_PROC_BROWSER_TEST_F(SSLUITest, GoBackFromInsecureFormWarning) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
GURL form_site_url = https_server_.GetURL(replacement_path);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), form_site_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// After clicking Don't Proceed, we should not be on an interstitial, and be
// back on the site containing the insecure form.
DontProceedThroughInterstitial(tab);
EXPECT_FALSE(helper->IsDisplayingInterstitial());
EXPECT_EQ(tab->GetVisibleURL(), form_site_url);
}
// Checks mixed form warnings work correctly for non-redirects.
IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureFormSubmissionWarning) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Check this was logged correctly as a non-redirect interstitial.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(interstitial_histogram,
InsecureFormNavigationThrottle::
InterstitialTriggeredState::kMixedFormDirect,
1);
}
// Checks interstitial is shown for mixed forms caused by a 307 POST http
// redirect, and that metrics are logged.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningRedirect) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_form_redirects_insecure.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Check this was logged correctly as a redirect mixed form that may expose
// form data.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(
interstitial_histogram,
InsecureFormNavigationThrottle::InterstitialTriggeredState::
kMixedFormRedirectWithFormData,
1);
}
// Checks interstitial is shown for mixed forms caused by a 308 POST http
// redirect, and that metrics are logged.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningRedirect308) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_form_redirects_308_insecure.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(helper->IsDisplayingInterstitial());
EXPECT_EQ(helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->GetTypeForTesting(),
security_interstitials::InsecureFormBlockingPage::kTypeForTesting);
// Check this was logged correctly as a redirect mixed form that may expose
// form data.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(
interstitial_histogram,
InsecureFormNavigationThrottle::InterstitialTriggeredState::
kMixedFormRedirectWithFormData,
1);
}
// Checks no interstitial is shown for mixed forms caused for a POST form with a
// 301 redirect, and that metrics are logged correctly.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningRedirect301) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
// This test posts to does-not-exist.test. Disable HTTPS upgrades on this
// hostname for the test to work.
// TODO(crbug.com/40248833): Remove the allowlist entry.
ScopedAllowHttpForHostnamesForTesting scoped_allow_http(
{"does-not-exist.test"}, browser()->profile()->GetPrefs());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_form_redirects_301_insecure.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
// There should have been no interstitial triggered.
EXPECT_FALSE(helper);
// Check this was logged correctly as a redirect mixed form that would not
// expose form data.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(
interstitial_histogram,
InsecureFormNavigationThrottle::InterstitialTriggeredState::
kMixedFormRedirectNoFormData,
1);
}
// Checks no interstitial is shown for mixed forms caused for a POST form with a
// 302 redirect, and that metrics are logged correctly.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningRedirect302) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
// This test posts to does-not-exist.test. Disable HTTPS upgrades on this
// hostname for the test to work.
// TODO(crbug.com/40248833): Remove the allowlist entry.
ScopedAllowHttpForHostnamesForTesting scoped_allow_http(
{"does-not-exist.test"}, browser()->profile()->GetPrefs());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_form_redirects_302_insecure.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
// There should have been no interstitial triggered.
EXPECT_FALSE(helper);
// Check this was logged correctly as a redirect mixed form that would not
// expose form data.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(
interstitial_histogram,
InsecureFormNavigationThrottle::InterstitialTriggeredState::
kMixedFormRedirectNoFormData,
1);
}
namespace {
// Redirects (with 307 code) requests with a redirect_to_http path to
// http://example.org. This custom handler is required for tests that include
// GET method forms to the redirect URL, since the built in /server-redirect-307
// handler takes the redirect-to URL as a query parameter, so it is not usable
// for GET method forms.
std::unique_ptr<net::test_server::HttpResponse> FormActionHTTPRedirectHandler(
const net::EmbeddedTestServer* test_server,
const net::test_server::HttpRequest& request) {
GURL absolute_url = test_server->GetURL(request.relative_url);
if (absolute_url.path() != "/redirect_to_http")
return nullptr;
GURL::Replacements replacements;
replacements.SetHostStr("example.org");
replacements.SetSchemeStr("http");
const GURL redirect_url =
test_server->base_url().ReplaceComponents(replacements);
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->set_code(net::HTTP_TEMPORARY_REDIRECT);
http_response->AddCustomHeader("Location", redirect_url.spec());
return std::move(http_response);
}
} // namespace
// Checks no interstitial is shown for mixed forms caused for a GET form with
// a 307 redirect to http, and that metrics are logged correctly.
IN_PROC_BROWSER_TEST_F(SSLUITest,
TestDisplaysInsecureFormSubmissionWarningRedirectGet) {
base::HistogramTester histograms;
const std::string interstitial_histogram =
"Security.MixedForm.InterstitialTriggerState";
ASSERT_TRUE(embedded_test_server()->Start());
https_server_.RegisterRequestHandler(
base::BindRepeating(&FormActionHTTPRedirectHandler, &https_server_));
ASSERT_TRUE(https_server_.Start());
// This test redirects to example.org. Disable HTTPS upgrades on this
// hostname for the test to work.
// TODO(crbug.com/40248833): Remove the allowlist entry.
ScopedAllowHttpForHostnamesForTesting scoped_allow_http(
{"example.org"}, browser()->profile()->GetPrefs());
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_form_redirects_insecure_get.html",
embedded_test_server()->host_port_pair());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
// There should have been no interstitial triggered.
EXPECT_FALSE(helper);
// Check this was logged correctly as a redirect mixed form that would not
// expose form data.
histograms.ExpectTotalCount(interstitial_histogram, 1);
histograms.ExpectBucketCount(
interstitial_histogram,
InsecureFormNavigationThrottle::InterstitialTriggeredState::
kMixedFormRedirectNoFormData,
1);
}
class MixedFormsPolicyTest : public policy::PolicyTest {};
// Check no warning is shown if disabled by policy.
IN_PROC_BROWSER_TEST_F(MixedFormsPolicyTest, NoWarningOptOutPolicy) {
ASSERT_TRUE(embedded_test_server()->Start());
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server.Start());
// Check pref is set to true by default.
EXPECT_TRUE(browser()->profile()->GetPrefs()->GetBoolean(
prefs::kMixedFormsWarningsEnabled));
// Set policy to disable mixed form warnings.
policy::PolicyMap policies;
policies.Set(policy::key::kInsecureFormsWarningsEnabled,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD, base::Value(false), nullptr);
UpdateProviderPolicy(policies);
// Pref should now be set to false.
EXPECT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
prefs::kMixedFormsWarningsEnabled));
std::string replacement_path =
SSLUITestBase::GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
GURL form_site_url = https_server.GetURL(replacement_path);
GURL form_target_url("http://does-not-exist.test/ssl/google_files/logo.gif");
// Navigate to site with insecure form and submit it.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), form_site_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(tab, 1);
ASSERT_TRUE(content::ExecJs(tab, "submitForm();"));
nav_observer.Wait();
// No interstitial should be shown, and we should be in the form action URL.
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
EXPECT_TRUE(!helper || !helper->IsDisplayingInterstitial());
EXPECT_EQ(tab->GetVisibleURL(), form_target_url);
}
namespace {
char kTestMITMSoftwareName[] = "Misconfigured Firewall";
char16_t kTestMITMSoftwareName16[] = u"Misconfigured Firewall";
class SSLUIMITMSoftwareTest : public CertVerifierBrowserTest {
public:
SSLUIMITMSoftwareTest()
: CertVerifierBrowserTest(),
https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
SSLUIMITMSoftwareTest(const SSLUIMITMSoftwareTest&) = delete;
SSLUIMITMSoftwareTest& operator=(const SSLUIMITMSoftwareTest&) = delete;
~SSLUIMITMSoftwareTest() override = default;
void SetUpOnMainThread() override {
CertVerifierBrowserTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
ssl_test_util::SetHSTSForHostName(browser()->profile(), kHstsTestHostName);
}
// Set up the cert verifier to return the error passed in as the cert_error
// parameter.
void SetUpCertVerifier(net::CertStatus cert_error) {
net::CertVerifyResult verify_result;
verify_result.verified_cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(verify_result.verified_cert);
verify_result.cert_status = cert_error;
mock_cert_verifier()->AddResultForCert(
https_server()->GetCertificate().get(), verify_result,
net::MapCertStatusToNetError(cert_error));
}
// Sets up an SSLErrorAssistantProto that lists |https_server_|'s default
// certificate as a MITM software certificate.
void SetUpMITMSoftwareCertList(uint32_t version_id) {
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(version_id);
chrome_browser_ssl::MITMSoftware* mitm_software =
config_proto->add_mitm_software();
mitm_software->set_name(kTestMITMSoftwareName);
mitm_software->set_issuer_common_name_regex(
https_server()->GetCertificate().get()->issuer().common_name);
mitm_software->set_issuer_organization_regex(
https_server()->GetCertificate().get()->issuer().organization_names[0]);
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_TRUE(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting() >
0);
}
// Returns a URL which triggers an interstitial with the host name that has
// HSTS set.
GURL GetHSTSTestURL() const {
GURL::Replacements replacements;
replacements.SetHostStr(kHstsTestHostName);
return https_server()
->GetURL("/ssl/blank_page.html")
.ReplaceComponents(replacements);
}
void TestMITMSoftwareInterstitial() {
base::HistogramTester histograms;
ASSERT_TRUE(https_server()->Start());
ASSERT_TRUE(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting() >
0);
// Navigate to an unsafe page on the server. Mock out the URL host name to
// equal the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetHSTSTestURL()));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingMITMInterstitial(tab));
EXPECT_FALSE(interstitial_timer_observer.timer_started());
// Check that the histograms for the MITM software interstitial were
// recorded.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(),
2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_NONOVERRIDABLE, 0);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL, 1);
}
void TestNoMITMSoftwareInterstitial() {
base::HistogramTester histograms;
ASSERT_TRUE(https_server()->Start());
ASSERT_TRUE(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting() >
0);
// Navigate to an unsafe page on the server. Mock out the URL host name to
// equal the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetHSTSTestURL()));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(interstitial_timer_observer.timer_started());
// Check that a MITM software interstitial was not recorded in histogram.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(),
2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_OVERRIDABLE, 0);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_NONOVERRIDABLE, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL, 0);
}
// Returns the https server. Guaranteed to be non-NULL.
const net::EmbeddedTestServer* https_server() const { return &https_server_; }
net::EmbeddedTestServer* https_server() { return &https_server_; }
private:
net::EmbeddedTestServer https_server_;
};
// The SSLUIMITMSoftwareEnabled and Disabled test classes exist so that the
// scoped feature list can be instantiated in the set up method of the class
// rather than in the test itself. Bug crbug.com/713390 was causing some of the
// tests in SSLUIMITMSoftwareTest to be flaky. Refactoring these tests so that
// the scoped feature list initialization is done in the set up method fixes
// this flakiness.
class SSLUIMITMSoftwareEnabledTest : public SSLUIMITMSoftwareTest {
public:
SSLUIMITMSoftwareEnabledTest() {
scoped_feature_list_.InitWithFeatures(
{kMITMSoftwareInterstitial} /* enabled */, {} /* disabled */);
}
SSLUIMITMSoftwareEnabledTest(const SSLUIMITMSoftwareEnabledTest&) = delete;
SSLUIMITMSoftwareEnabledTest& operator=(const SSLUIMITMSoftwareEnabledTest&) =
delete;
~SSLUIMITMSoftwareEnabledTest() override = default;
void SetUpOnMainThread() override {
SSLUIMITMSoftwareTest::SetUpOnMainThread();
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
class SSLUIMITMSoftwareDisabledTest : public SSLUIMITMSoftwareTest {
public:
SSLUIMITMSoftwareDisabledTest() {
scoped_feature_list_.InitWithFeatures(
{} /* enabled */, {kMITMSoftwareInterstitial} /* disabled */);
}
SSLUIMITMSoftwareDisabledTest(const SSLUIMITMSoftwareDisabledTest&) = delete;
SSLUIMITMSoftwareDisabledTest& operator=(
const SSLUIMITMSoftwareDisabledTest&) = delete;
~SSLUIMITMSoftwareDisabledTest() override = default;
void SetUpOnMainThread() override {
SSLUIMITMSoftwareTest::SetUpOnMainThread();
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
} // namespace
// Tests that the MITM software interstitial is not displayed when the feature
// is disabled by Finch.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareDisabledTest, DisabledWithFinch) {
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestNoMITMSoftwareInterstitial();
}
// Tests that the MITM software interstitial is displayed when the feature is
// enabled by Finch.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, EnabledWithFinch) {
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestMITMSoftwareInterstitial();
}
// Tests that if a certificates matches the common name of a known MITM software
// cert on the list but not the organization name, the MITM software
// interstitial will not be displayed.
IN_PROC_BROWSER_TEST_F(
SSLUIMITMSoftwareEnabledTest,
CertificateCommonNameMatchOnly_NoMITMSoftwareInterstitial) {
base::HistogramTester histograms;
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ASSERT_TRUE(https_server()->Start());
// Set up an error assistant proto with a list of MITM software regexed that
// the certificate issued by our server won't match.
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(kLargeVersionId);
chrome_browser_ssl::MITMSoftware* mitm_software =
config_proto->add_mitm_software();
mitm_software->set_name(kTestMITMSoftwareName);
mitm_software->set_issuer_common_name_regex(
https_server()->GetCertificate().get()->issuer().common_name);
mitm_software->set_issuer_organization_regex(
"pattern-that-does-not-match-anything");
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
// Navigate to an unsafe page on the server. Mock out the URL host name to
// equal the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetHSTSTestURL()));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(interstitial_timer_observer.timer_started());
// Check that a MITM software interstitial was not recorded in histogram.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(), 2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_NONOVERRIDABLE, 1);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL,
0);
}
// Tests that if a certificates matches the organization name of a known MITM
// software cert on the list but not the common name, the MITM software
// interstitial will not be displayed.
IN_PROC_BROWSER_TEST_F(
SSLUIMITMSoftwareEnabledTest,
CertificateOrganizationMatchOnly_NoMITMSoftwareInterstitial) {
base::HistogramTester histograms;
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ASSERT_TRUE(https_server()->Start());
// Set up an error assistant proto with a list of MITM software regexed that
// the certificate issued by our server won't match.
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(kLargeVersionId);
chrome_browser_ssl::MITMSoftware* mitm_software =
config_proto->add_mitm_software();
mitm_software->set_name(kTestMITMSoftwareName);
mitm_software->set_issuer_common_name_regex(
"pattern-that-does-not-match-anything");
mitm_software->set_issuer_organization_regex(
https_server()->GetCertificate().get()->issuer().organization_names[0]);
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
// Navigate to an unsafe page on the server. Mock out the URL host name to
// equal the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetHSTSTestURL()));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(interstitial_timer_observer.timer_started());
// Check that a MITM software interstitial was not recorded in histogram.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(), 2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_NONOVERRIDABLE, 1);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL,
0);
}
// Tests that if the certificate does not match any entry on the list of known
// MITM software, the MITM software interstitial will not be displayed.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest,
NonMatchingCertificate_NoMITMSoftwareInterstitial) {
base::HistogramTester histograms;
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ASSERT_TRUE(https_server()->Start());
// Set up an error assistant proto with a list of MITM software regexes that
// the certificate issued by our server won't match.
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(kLargeVersionId);
chrome_browser_ssl::MITMSoftware* mitm_software =
config_proto->add_mitm_software();
mitm_software->set_name("Non-Matching MITM Software");
mitm_software->set_issuer_common_name_regex(
"pattern-that-does-not-match-anything");
mitm_software->set_issuer_organization_regex(
"pattern-that-does-not-match-anything");
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
// Navigate to an unsafe page on the server. Mock out the URL host name to
// equal the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetHSTSTestURL()));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(interstitial_timer_observer.timer_started());
// Check that a MITM software interstitial was not recorded in histogram.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(), 2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_NONOVERRIDABLE, 1);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL,
0);
}
// Tests that if there is more than one error on the certificate the MITM
// software interstitial will not be displayed.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest,
TwoCertErrors_NoMITMSoftwareInterstitial) {
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID |
net::CERT_STATUS_COMMON_NAME_INVALID);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestNoMITMSoftwareInterstitial();
}
// Tests that a certificate error other than |CERT_STATUS_AUTHORITY_INVALID|
// will not trigger the MITM software interstitial.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest,
WrongCertError_NoMITMSoftwareInterstitial) {
SetUpCertVerifier(net::CERT_STATUS_COMMON_NAME_INVALID);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestNoMITMSoftwareInterstitial();
}
// Tests that if the error on the certificate served is overridable the MITM
// software interstitial will not be displayed.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest,
OverridableError_NoMITMSoftwareInterstitial) {
base::HistogramTester histograms;
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ASSERT_TRUE(https_server()->Start());
SetUpMITMSoftwareCertList(kLargeVersionId);
// Navigate to an unsafe page to trigger an interstitial, but don't replace
// the host name with the one set for HSTS.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
SSLInterstitialTimerObserver interstitial_timer_observer(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server()->GetURL("/ssl/blank_page.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(tab));
EXPECT_TRUE(interstitial_timer_observer.timer_started());
// Check that the histogram for an overridable SSL interstitial was
// recorded.
histograms.ExpectTotalCount(SSLErrorHandler::GetHistogramNameForTesting(), 2);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::HANDLE_ALL, 1);
histograms.ExpectBucketCount(
SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_SSL_INTERSTITIAL_OVERRIDABLE, 1);
histograms.ExpectBucketCount(SSLErrorHandler::GetHistogramNameForTesting(),
SSLErrorHandler::SHOW_MITM_SOFTWARE_INTERSTITIAL,
0);
}
// Tests that the correct strings are displayed on the interstitial in the
// enterprise managed case.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, EnterpriseManaged) {
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ChromeSecurityBlockingPageFactory::SetEnterpriseManagedForTesting(true);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestMITMSoftwareInterstitial();
const std::string expected_primary_paragraph =
l10n_util::GetStringFUTF8(IDS_MITM_SOFTWARE_PRIMARY_PARAGRAPH_ENTERPRISE,
base::EscapeForHTML(kTestMITMSoftwareName16));
const std::string expected_explanation = l10n_util::GetStringFUTF8(
IDS_MITM_SOFTWARE_EXPLANATION_ENTERPRISE,
base::EscapeForHTML(kTestMITMSoftwareName16),
l10n_util::GetStringUTF16(IDS_MITM_SOFTWARE_EXPLANATION));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
tab->GetPrimaryMainFrame(), expected_explanation));
EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
tab->GetPrimaryMainFrame(), expected_primary_paragraph));
}
// Tests that the correct strings are displayed on the interstitial in the
// non-enterprise managed case.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, NotEnterpriseManaged) {
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ChromeSecurityBlockingPageFactory::SetEnterpriseManagedForTesting(false);
SetUpMITMSoftwareCertList(kLargeVersionId);
TestMITMSoftwareInterstitial();
// Don't check the primary paragraph in the non-enterprise case, because it
// has escaped HTML characters which throw an error.
const std::string expected_explanation = l10n_util::GetStringFUTF8(
IDS_MITM_SOFTWARE_EXPLANATION_NONENTERPRISE,
base::EscapeForHTML(kTestMITMSoftwareName16),
l10n_util::GetStringUTF16(IDS_MITM_SOFTWARE_EXPLANATION));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
tab->GetPrimaryMainFrame(), expected_explanation));
}
// Initialize MITMSoftware certificate list but set the version_id to zero. This
// less than the version_id of the local resource bundle, so the dynamic
// update will be ignored and a non-MITM interstitial will be shown.
IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest,
IgnoreDynamicUpdateWithSmallVersionId) {
auto config_proto =
SSLErrorAssistant::GetErrorAssistantProtoFromResourceBundle();
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID);
ChromeSecurityBlockingPageFactory::SetEnterpriseManagedForTesting(false);
SetUpMITMSoftwareCertList(0u);
TestNoMITMSoftwareInterstitial();
}
// Checks that SimpleURLLoader, which uses services/network/url_loader.cc, goes
// through the new NetworkServiceClient interface to deliver cert error
// notifications to the browser which then overrides the certificate error.
IN_PROC_BROWSER_TEST_F(SSLUITest, SimpleURLLoaderCertError) {
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_NO_FATAL_FAILURE(SetUpUnsafeContentsWithUserException(
"/ssl/page_with_unsafe_contents.html"));
ssl_test_util::CheckAuthenticationBrokenState(tab, CertError::NONE,
AuthState::NONE);
EXPECT_EQ(net::OK,
content::LoadBasicRequest(
tab->GetPrimaryMainFrame(),
https_server_mismatched_.GetURL("/anchor_download_test.png")));
}
IN_PROC_BROWSER_TEST_F(SSLUITest, NetworkErrorDoesntRevokeExemptions) {
ASSERT_TRUE(https_server_expired_.Start());
GURL expired_url = https_server_expired_.GetURL("/title1.html");
int server_port = expired_url.IntPort();
// Navigate to the expired cert URL, make sure we get an interstitial.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), expired_url));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
// Click through the interstitial.
ProceedThroughInterstitial(tab);
// Shut down the server and navigate again to cause a network error.
ASSERT_TRUE(https_server_expired_.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), expired_url));
// Create a new server in the same url (including port), the certificate
// should still be invalid.
net::EmbeddedTestServer new_https_server(net::EmbeddedTestServer::TYPE_HTTPS);
new_https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
new_https_server.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(new_https_server.Start(server_port));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), expired_url));
// We shouldn't get an interstitial this time.
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(tab));
}
// Checks we don't attempt to show an interstitial (or crash) when visiting an
// SSL error related page in chrome://network-errors. Regression test for
// crbug.com/953812
IN_PROC_BROWSER_TEST_F(SSLUITest, NoInterstitialOnNetworkErrorPage) {
GURL invalid_cert_url(blink::kChromeUINetworkErrorURL);
GURL::Replacements replacements;
replacements.SetPathStr("-207");
invalid_cert_url = invalid_cert_url.ReplaceComponents(replacements);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), invalid_cert_url));
EXPECT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(
browser()->tab_strip_model()->GetActiveWebContents()));
}
// This SPKI hash is from a self signed certificate generated using the
// following openssl command:
// openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
// openssl x509 -noout -in certificate.pem -pubkey | \
// openssl asn1parse -noout -inform pem -out public.key;
// openssl dgst -sha256 -binary public.key | openssl enc -base64
// The actual value of the hash doesn't matter as long it's a valid SPKI hash.
const char kMatchingDynamicInterstitialCert[] =
"sha256/eFi0afYJLdI0YsZFu4U8ra2B5/5ynzfKkI88M94iVFA=";
namespace {
class SSLUIDynamicInterstitialTest : public CertVerifierBrowserTest {
public:
SSLUIDynamicInterstitialTest()
: CertVerifierBrowserTest(),
https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
SSLUIDynamicInterstitialTest(const SSLUIDynamicInterstitialTest&) = delete;
SSLUIDynamicInterstitialTest& operator=(const SSLUIDynamicInterstitialTest&) =
delete;
~SSLUIDynamicInterstitialTest() override = default;
void SetUpCertVerifier() {
scoped_refptr<net::X509Certificate> cert(https_server_.GetCertificate());
net::CertVerifyResult verify_result;
verify_result.verified_cert = cert;
verify_result.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
net::HashValue hash;
ASSERT_TRUE(hash.FromString(kMatchingDynamicInterstitialCert));
verify_result.public_key_hashes.push_back(hash);
mock_cert_verifier()->AddResultForCert(cert, verify_result,
net::ERR_CERT_COMMON_NAME_INVALID);
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
// Creates and returns a SSLErrorAssistantConfig object.
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig>
CreateSSLErrorAssistantConfig() {
auto config_proto =
std::make_unique<chrome_browser_ssl::SSLErrorAssistantConfig>();
config_proto->set_version_id(kLargeVersionId);
return config_proto;
}
// Adds a dynamic interstitial to |config_proto|. All of the dynamic
// interstitial's fields mismatch with |https_server_|'s SSL info.
void AddMismatchDynamicInterstitial(
chrome_browser_ssl::SSLErrorAssistantConfig* config_proto) {
chrome_browser_ssl::DynamicInterstitial* filter =
config_proto->add_dynamic_interstitial();
filter->set_interstitial_type(
chrome_browser_ssl::DynamicInterstitial::INTERSTITIAL_PAGE_SSL);
filter->set_cert_error(
chrome_browser_ssl::DynamicInterstitial::ERR_CERT_DATE_INVALID);
filter->add_sha256_hash("sha256/killdeer");
filter->add_sha256_hash("sha256/thickkne");
filter->set_issuer_common_name_regex("beeeater");
filter->set_issuer_organization_regex("honeycreeper");
filter->set_mitm_software_name(kTestMITMSoftwareName);
}
// Adds a dynamic interstitial to |config_proto| and returns it. All of the
// fields in the dynamic intersitial matches with |https_server_|'s
// SSL info. Optionally set the flag for triggering dynamic interstitials
// only on non-overridable errors.
chrome_browser_ssl::DynamicInterstitial* AddMatchingDynamicInterstitial(
chrome_browser_ssl::SSLErrorAssistantConfig* config_proto,
bool show_only_for_nonoverridable_errors = false) {
chrome_browser_ssl::DynamicInterstitial* filter =
config_proto->add_dynamic_interstitial();
filter->set_interstitial_type(chrome_browser_ssl::DynamicInterstitial::
INTERSTITIAL_PAGE_CAPTIVE_PORTAL);
filter->set_cert_error(
chrome_browser_ssl::DynamicInterstitial::ERR_CERT_COMMON_NAME_INVALID);
filter->add_sha256_hash("sha256/kingfisher");
filter->add_sha256_hash(kMatchingDynamicInterstitialCert);
filter->add_sha256_hash("sha256/flycatcher");
scoped_refptr<net::X509Certificate> cert = https_server_.GetCertificate();
filter->set_issuer_common_name_regex(cert.get()->issuer().common_name);
if (!cert.get()->issuer().organization_names.empty()) {
filter->set_issuer_organization_regex(
cert.get()->issuer().organization_names[0]);
}
filter->set_mitm_software_name(kTestMITMSoftwareName);
filter->set_support_url("https://google.com");
filter->set_show_only_for_nonoverridable_errors(
show_only_for_nonoverridable_errors);
return filter;
}
security_interstitials::SecurityInterstitialPage* GetInterstitialDelegate(
WebContents* tab) {
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
tab);
if (!helper)
return nullptr;
return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting();
}
private:
net::EmbeddedTestServer https_server_;
};
} // namespace
// Tests that the dynamic interstitial list is used when the feature is
// enabled via Finch. The list is passed to SSLErrorHandler via a proto.
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, Match) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
AddMatchingDynamicInterstitial(config_proto.get());
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
ASSERT_EQ(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, MatchUnknownCertError) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a matching dynamic interstitial with the UNKNOWN_CERT_ERROR status.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_cert_error(
chrome_browser_ssl::DynamicInterstitial::UNKNOWN_CERT_ERROR);
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
ASSERT_EQ(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest,
MatchEmptyCommonNameRegex) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a matching dynamic interstitial with an empty issuer common name
// regex.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_issuer_common_name_regex(std::string());
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
ASSERT_EQ(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest,
MatchEmptyOrganizationRegex) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a matching dynamic interstitial with an empty issuer organization
// name regex.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_issuer_organization_regex(std::string());
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
ASSERT_EQ(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, MismatchHash) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a dynamic interstitial with matching fields, except for the
// certificate hashes.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->clear_sha256_hash();
match->add_sha256_hash("sha256/sapsucker");
match->add_sha256_hash("sha256/flowerpiercer");
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
EXPECT_NE(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, MismatchCertError) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a dynamic interstitial with matching fields, except for the
// cert error field.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_cert_error(
chrome_browser_ssl::DynamicInterstitial::ERR_CERT_DATE_INVALID);
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
EXPECT_NE(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, MismatchCommonNameRegex) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a dynamic interstitial with matching fields, except for the
// issuer common name regex field.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_issuer_common_name_regex("beeeater");
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
EXPECT_NE(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest,
MismatchOrganizationRegex) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a dynamic interstitial with matching fields, except for the
// issuer organization name regex field.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get());
match->set_issuer_organization_regex("honeycreeper");
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
EXPECT_NE(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
IN_PROC_BROWSER_TEST_F(SSLUIDynamicInterstitialTest, MismatchWhenOverridable) {
ASSERT_TRUE(https_server()->Start());
SetUpCertVerifier();
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
{
std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> config_proto =
CreateSSLErrorAssistantConfig();
config_proto->set_version_id(kLargeVersionId);
AddMismatchDynamicInterstitial(config_proto.get());
// Add a matching dynamic interstitial, except for the
// show_only_for_nonoverridable_errors flag is set to true.
chrome_browser_ssl::DynamicInterstitial* match =
AddMatchingDynamicInterstitial(config_proto.get(), true);
match->set_cert_error(
chrome_browser_ssl::DynamicInterstitial::UNKNOWN_CERT_ERROR);
SSLErrorHandler::SetErrorAssistantProto(std::move(config_proto));
ASSERT_EQ(SSLErrorHandler::GetErrorAssistantProtoVersionIdForTesting(),
kLargeVersionId);
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
security_interstitials::SecurityInterstitialPage* interstitial_page =
GetInterstitialDelegate(tab);
ASSERT_TRUE(interstitial_page);
EXPECT_NE(CaptivePortalBlockingPage::kTypeForTesting,
interstitial_page->GetTypeForTesting());
}
}
// Tests that mixed content is tracked by origin hostname, not by URL. This is
// tested by checking that mixed content flags are set appropriately for
// about:blank URLs (who inherit the origin of their opener).
//
// Note: we test that mixed content flags are propagated from an opener page to
// about:blank, but not the other way around. This is because there is no way
// for a mixed content flag to propagate from about:blank to a different
// tab. Passive mixed content flags are not propagated from one tab to another,
// and for active mixed content, there's no way to bypass mixed content blocking
// on about:blank pages, so there's no way that the origin would get flagged for
// active mixed content from an about:blank page. (There's no way to bypass
// mixed content blocking on about:blank pages because the bypass is implemented
// as a content setting, which doesn't apply to about:blank.)
IN_PROC_BROWSER_TEST_F(SSLUITest, ActiveMixedContentTrackedByOrigin) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
std::string replacement_path = GetFilePathWithHostAndPortReplacement(
"/ssl/page_runs_insecure_content.html",
embedded_test_server()->host_port_pair());
// The insecure script is allowed to load because SSLUITestBase sets the
// --allow-running-insecure-content flag.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL(replacement_path)));
ssl_test_util::CheckAuthenticationBrokenState(
tab, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
// Open a new tab from the current page. After an initial navigation,
// navigate it to about:blank and check that the about:blank page is
// downgraded, because it shares an origin with |tab| which ran mixed
// content.
//
// Note that the security indicator is not downgraded on the initial
// about:blank navigation in the new tab. Initial about:blank navigations
// don't have navigation entries (yet), so there is no way to track the mixed
// content state for these navigations. See https://crbug.com/1038765.
ui_test_utils::TabAddedWaiter tab_waiter(browser());
ASSERT_TRUE(content::ExecJs(tab, "w = window.open()"));
tab_waiter.Wait();
WebContents* opened_tab = browser()->tab_strip_model()->GetWebContentsAt(1);
content::TestNavigationObserver first_navigation(opened_tab);
ASSERT_TRUE(content::ExecJs(
tab, content::JsReplace("w.location.href = $1",
embedded_test_server()->GetURL("/title1.html"))));
first_navigation.Wait();
ssl_test_util::CheckAuthenticationBrokenState(
opened_tab, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
content::TestNavigationObserver about_blank_navigation(opened_tab);
ASSERT_TRUE(content::ExecJs(tab, "w.location.href = 'about:blank'"));
about_blank_navigation.Wait();
ssl_test_util::CheckAuthenticationBrokenState(
opened_tab, CertError::NONE, AuthState::RAN_INSECURE_CONTENT);
}
// Tests that MixedContentShown histogram doesn't get logged when a site with
// a bad certificate loads a subresource (which also has a bad certificate).
IN_PROC_BROWSER_TEST_F(
SSLUITest,
MixedContentHistogramNotLoggedForSiteWithBadCertificate) {
ASSERT_TRUE(https_server_expired_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
// Navigate to a page with a certificate error, and click through the
// interstitial.
// page_with_subresource.html loads both a script (which would count as
// blockable mixed content), and an image (which would count as optionally
// blockable mixed content) from the same origin as the main site.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_expired_.GetURL("/ssl/page_with_subresource.html")));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
ProceedThroughInterstitial(tab);
}
// Tests that MixedContentShown histogram gets logged when a site with
// a valid certificate loads a subresource with a bad certificate.
IN_PROC_BROWSER_TEST_F(
SSLUITest,
MixedContentHistogramLoggedForBadCertificateSubresource) {
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_server_expired_.Start());
GURL base_url("https://site.test");
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
// Navigate to a page with a certificate error, and click through the
// interstitial so the certificate is allowlisted.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), GURL("https://site.test:" +
base::NumberToString(https_server_expired_.port()) +
"/ssl/blank_page.html")));
ProceedThroughInterstitial(tab);
// Navigate to a page with a valid certificate, that contains subresouces from
// the previously allowlisted bad certificate page.
base::StringPairs replacement_text;
replacement_text.push_back(make_pair(
"REPLACE_WITH_HOST_AND_PORT",
("site.test:" + base::NumberToString(https_server_expired_.port()))));
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_.GetURL((net::test_server::GetFilePathWithReplacements(
"/ssl/page_with_unsafe_contents.html", replacement_text)))));
}
// Tests that MixedContentShown histogram gets logged when a site with
// a valid certificate loads an insecure form.
IN_PROC_BROWSER_TEST_F(SSLUITest, MixedContentHistogramLoggedForInsecureForm) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_.GetURL("/ssl/page_displays_insecure_form.html")));
}
// Tests that MixedContentShown histogram gets logged when a site with
// a valid certificate loads an insecure blockable resource (a script).
// TODO(carlosil): This test works because SSLUITest has
// kMixedContentAutoupgrade disabled. When cleaning up the autoupgrade flag,
// this will need to be rewritten to use content settings.
IN_PROC_BROWSER_TEST_F(SSLUITest,
MixedContentHistogramLoggedForBlockableMixedContent) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_.GetURL("/ssl/page_runs_insecure_content.html")));
}
// Tests that MixedContentShown histogram gets logged when a site with
// a valid certificate loads an insecure optionally blockable resource (an
// image).
// TODO(carlosil): This test works because SSLUITest has
// kMixedContentAutoupgrade disabled. When cleaning up the autoupgrade flag,
// this will need to be rewritten to use content settings.
IN_PROC_BROWSER_TEST_F(
SSLUITest,
MixedContentHistogramLoggedForOptionallyBlockableMixedContent) {
ASSERT_TRUE(https_server_.Start());
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(tab);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
https_server_.GetURL("/ssl/page_displays_insecure_content.html")));
}
class SSLUIAutoReloadTest : public SSLUITest {
public:
SSLUIAutoReloadTest() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(embedder_support::kEnableAutoReload);
SSLUITest::SetUpCommandLine(command_line);
}
};
// SSL interstitials should disable autoreload timer.
IN_PROC_BROWSER_TEST_F(SSLUIAutoReloadTest, AutoReloadDisabled) {
ASSERT_TRUE(https_server_expired_.Start());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(tab));
ssl_test_util::CheckAuthenticationBrokenState(
tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL);
auto* reloader = error_page::NetErrorAutoReloader::FromWebContents(tab);
const std::optional<base::OneShotTimer>& timer =
reloader->next_reload_timer_for_testing();
EXPECT_EQ(std::nullopt, timer);
}
class SSLUITestWithEnhancedProtectionMessage : public SSLUITest {
public:
SSLUITestWithEnhancedProtectionMessage() = default;
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(SSLUITestWithEnhancedProtectionMessage,
VerifyEnhancedProtectionMessageShown) {
base::HistogramTester histograms;
const std::string interaction_histogram =
"interstitial.ssl_overridable.interaction";
safe_browsing::SetExtendedReportingPrefForTests(
browser()->profile()->GetPrefs(), true);
safe_browsing::SetSafeBrowsingState(
browser()->profile()->GetPrefs(),
safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);
ASSERT_TRUE(https_server_expired_.Start());
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
ExpectInterstitialElementHidden(contents, "enhanced-protection-message",
false /* expect_hidden */);
histograms.ExpectTotalCount(interaction_histogram, 2);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::TOTAL_VISITS, 1);
histograms.ExpectBucketCount(
interaction_histogram,
security_interstitials::MetricsHelper::SHOW_ENHANCED_PROTECTION, 1);
}
IN_PROC_BROWSER_TEST_F(SSLUITestWithEnhancedProtectionMessage,
VerifyEnhancedProtectionMessageNotShownAlreadyInEp) {
safe_browsing::SetExtendedReportingPrefForTests(
browser()->profile()->GetPrefs(), true);
safe_browsing::SetSafeBrowsingState(
browser()->profile()->GetPrefs(),
safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
ASSERT_TRUE(https_server_expired_.Start());
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
ExpectInterstitialElementHidden(contents, "extended-reporting-opt-in",
true /* expect_hidden */);
ExpectInterstitialElementHidden(contents, "enhanced-protection-message",
true /* expect_hidden */);
}
IN_PROC_BROWSER_TEST_F(SSLUITestWithEnhancedProtectionMessage,
VerifyEnhancedProtectionMessageNotShownManaged) {
policy::PolicyMap policies;
policies.Set(policy::key::kSafeBrowsingProtectionLevel,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
base::Value(/* standard protection */ 1), nullptr);
UpdateChromePolicy(policies);
ASSERT_TRUE(https_server_expired_.Start());
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_server_expired_.GetURL("/ssl/google.html")));
ASSERT_TRUE(chrome_browser_interstitials::IsShowingSSLInterstitial(contents));
ExpectInterstitialElementHidden(contents, "enhanced-protection-message",
true /* expect_hidden */);
}
class InsecureFormNavigationThrottleFencedFrameBrowserTest
: public InProcessBrowserTest {
public:
InsecureFormNavigationThrottleFencedFrameBrowserTest() = default;
~InsecureFormNavigationThrottleFencedFrameBrowserTest() override = default;
WebContents* GetWebContents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_helper_;
}
private:
content::test::FencedFrameTestHelper fenced_frame_helper_;
};
// Tests that a fenced frame doesn't create a security interstitial.
IN_PROC_BROWSER_TEST_F(InsecureFormNavigationThrottleFencedFrameBrowserTest,
DoNotCreateSecurityInterstitialInFencedFrame) {
ASSERT_TRUE(embedded_test_server()->Start());
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server.Start());
GURL initial_url = https_server.GetURL("/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));
std::string replacement_path =
SSLUITestBase::GetFilePathWithHostAndPortReplacement(
"/ssl/page_displays_insecure_form.html",
embedded_test_server()->host_port_pair());
GURL form_site_url = https_server.GetURL(replacement_path);
// Navigate to site with an insecure form and submit it in a fenced frame.
content::RenderFrameHost* fenced_frame =
fenced_frame_test_helper().CreateFencedFrame(browser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame(),
form_site_url);
ASSERT_TRUE(fenced_frame);
content::TestNavigationObserver observer(GetWebContents());
content::WebContentsConsoleObserver console_observer(GetWebContents());
console_observer.SetPattern(
"Mixed Content: The page at * was loaded over a secure connection, but "
"contains a form that targets an insecure endpoint "
"'http://does-not-exist.test/ssl/google_files/logo.gif'. This endpoint "
"should be made available over a secure connection.");
ASSERT_TRUE(content::ExecJs(fenced_frame, "submitForm();"));
observer.Wait();
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
GetWebContents());
// No interstitial should be created in the fenced frame, and the the fenced
// frame should be in |form_site_url| and primary mainframe should be in the
// initial URL.
EXPECT_TRUE(!helper || !helper->IsDisplayingInterstitial());
EXPECT_EQ(fenced_frame->GetLastCommittedURL(), form_site_url);
EXPECT_EQ(GetWebContents()->GetVisibleURL(), initial_url);
// Check console message was printed.
EXPECT_EQ(console_observer.messages().size(), 1u);
}
// TODO(jcampan): more tests to do below.
// Visit a page over https that contains a frame with a redirect.
// XMLHttpRequest insecure content in synchronous mode.
// XMLHttpRequest insecure content in asynchronous mode.
// XMLHttpRequest over bad ssl in synchronous mode.
// XMLHttpRequest over OK ssl in synchronous mode.
|