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
|
// 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.
//
// This file implements a standalone host process for Me2Me.
#include <algorithm>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/message_loop/message_pump_type.h"
#include "base/metrics/field_trial.h"
#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringize_macros.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/policy/policy_constants.h"
#include "components/webrtc/thread_wrapper.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_listener.h"
#include "mojo/core/embedder/scoped_ipc_support.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
#include "net/base/network_change_notifier.h"
#include "remoting/base/authentication_method.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/base/cloud_session_authz_service_client_factory.h"
#include "remoting/base/corp_session_authz_service_client_factory.h"
#include "remoting/base/cpu_utils.h"
#include "remoting/base/errors.h"
#include "remoting/base/host_settings.h"
#include "remoting/base/instance_identity_token_getter.h"
#include "remoting/base/instance_identity_token_getter_impl.h"
#include "remoting/base/is_google_email.h"
#include "remoting/base/local_session_policies_provider.h"
#include "remoting/base/logging.h"
#include "remoting/base/oauth_token_getter_impl.h"
#include "remoting/base/oauth_token_getter_proxy.h"
#include "remoting/base/rsa_key_pair.h"
#include "remoting/base/service_urls.h"
#include "remoting/base/session_policies.h"
#include "remoting/host/base/desktop_environment_options.h"
#include "remoting/host/base/host_exit_codes.h"
#include "remoting/host/base/switches.h"
#include "remoting/host/base/username.h"
#include "remoting/host/basic_desktop_environment.h"
#include "remoting/host/branding.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/cloud_heartbeat_service_client.h"
#include "remoting/host/config_file_watcher.h"
#include "remoting/host/config_watcher.h"
#include "remoting/host/corp_host_status_logger.h"
#include "remoting/host/crash_process.h"
#include "remoting/host/create_desktop_interaction_strategy_factory.h"
#include "remoting/host/desktop_environment.h"
#include "remoting/host/ftl_echo_message_listener.h"
#include "remoting/host/ftl_host_change_notification_listener.h"
#include "remoting/host/ftl_signaling_connector.h"
#include "remoting/host/heartbeat_sender.h"
#include "remoting/host/heartbeat_service_client.h"
#include "remoting/host/host_config.h"
#include "remoting/host/host_event_logger.h"
#include "remoting/host/host_power_save_blocker.h"
#include "remoting/host/input_injector.h"
#include "remoting/host/ipc_desktop_environment.h"
#include "remoting/host/me2me_desktop_environment.h"
#include "remoting/host/me2me_heartbeat_service_client.h"
#include "remoting/host/mojom/desktop_session.mojom.h"
#include "remoting/host/mojom/remoting_host.mojom.h"
#include "remoting/host/pairing_registry_delegate.h"
#include "remoting/host/pin_hash.h"
#include "remoting/host/policy_watcher.h"
#include "remoting/host/security_key/security_key_auth_handler.h"
#include "remoting/host/security_key/security_key_extension.h"
#include "remoting/host/session_policies_from_dict.h"
#include "remoting/host/shutdown_watchdog.h"
#include "remoting/host/test_echo_extension.h"
#include "remoting/host/usage_stats_consent.h"
#include "remoting/host/zombie_host_detector.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/chromium_port_allocator_factory.h"
#include "remoting/protocol/host_authentication_config.h"
#include "remoting/protocol/ice_config_fetcher_cloud.h"
#include "remoting/protocol/ice_config_fetcher_default.h"
#include "remoting/protocol/jingle_session_manager.h"
#include "remoting/protocol/me2me_host_authenticator_factory.h"
#include "remoting/protocol/pairing_registry.h"
#include "remoting/protocol/session_config.h"
#include "remoting/protocol/transport.h"
#include "remoting/protocol/transport_context.h"
#include "remoting/signaling/ftl_host_device_id_provider.h"
#include "remoting/signaling/ftl_signal_strategy.h"
#include "remoting/signaling/signal_strategy.h"
#include "remoting/signaling/signaling_id_util.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_types.h"
#include "third_party/webrtc/rtc_base/event_tracer.h"
#if BUILDFLAG(IS_POSIX)
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include "remoting/host/pam_authorization_factory_posix.h"
#include "remoting/host/posix/signal_handler.h"
#endif // BUILDFLAG(IS_POSIX)
#if BUILDFLAG(IS_APPLE)
#include "remoting/host/audio_capturer_mac.h"
#include "remoting/host/mac/agent_process_broker_client.h"
#include "remoting/host/mac/permission_utils.h"
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if defined(REMOTING_USE_X11)
#include <gtk/gtk.h>
#include "ui/events/platform/x11/x11_event_source.h"
#include "ui/gfx/x/connection.h"
#include "ui/gfx/x/xlib_support.h"
#endif // defined(REMOTING_USE_X11)
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include "base/linux_util.h"
#include "remoting/host/linux/audio_capturer_linux.h"
#include "remoting/host/linux/certificate_watcher.h"
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_WIN)
#include <commctrl.h>
#include "base/win/registry.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "remoting/host/pairing_registry_delegate_win.h"
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
#include "remoting/base/crash/crash_reporting_crashpad.h"
#include "remoting/host/host_wtmpdb_logger.h"
#endif // BUILDFLAG(IS_LINUX)
#if defined(REMOTING_MULTI_PROCESS)
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "remoting/host/ipc_host_event_logger.h"
#endif // defined(REMOTING_MULTI_PROCESS)
using remoting::protocol::PairingRegistry;
#if BUILDFLAG(IS_APPLE)
// The following creates a section that tells Mac OS X that it is OK to let us
// inject input in the login screen. Just the name of the section is important,
// not its contents.
__attribute__((used)) __attribute__((section(
"__CGPreLoginApp,__cgpreloginapp"))) static const char magic_section[] = "";
#endif // BUILDFLAG(IS_APPLE)
namespace {
#if !defined(REMOTING_MULTI_PROCESS)
// This is used for tagging system event logs.
const char kApplicationName[] = "chromoting";
// Value used for --host-config option to indicate that the path must be read
// from stdin.
const char kStdinConfigPath[] = "-";
#endif // !defined(REMOTING_MULTI_PROCESS)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// The command line switch used to pass name of the pipe to capture audio on
// linux.
const char kAudioPipeSwitchName[] = "audio-pipe-name";
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_POSIX)
// The command line switch used to pass name of the unix domain socket used to
// listen for security key requests.
const char kAuthSocknameSwitchName[] = "ssh-auth-sockname";
#endif // BUILDFLAG(IS_POSIX)
// The command line switch used by the parent to request the host to signal it
// when it is successfully started.
const char kSignalParentSwitchName[] = "signal-parent";
// Command line switch used to send a custom offline reason and exit.
const char kReportOfflineReasonSwitchName[] = "report-offline-reason";
// Maximum time to wait for clean shutdown to occur, before forcing termination
// of the process.
const int kShutdownTimeoutSeconds = 15;
// Maximum time to wait for reporting host-offline-reason to the service,
// before continuing normal process shutdown.
const int kHostOfflineReasonTimeoutSeconds = 10;
// Host offline reasons not associated with shutting down the host process
// and therefore not expressible through HostExitCodes enum.
const char kHostOfflineReasonPolicyReadError[] = "POLICY_READ_ERROR";
const char kHostOfflineReasonPolicyChangeRequiresRestart[] =
"POLICY_CHANGE_REQUIRES_RESTART";
const char kHostOfflineReasonZombieStateDetected[] = "ZOMBIE_STATE_DETECTED";
const char kHostOfflineReasonSuspended[] = "SUSPENDED";
// File to write webrtc trace events to. If not specified, webrtc trace events
// will not be enabled.
const char kWebRtcTraceEventFile[] = "webrtc-trace-event-file";
// Helper to check if a string value is in a Policy allowlist.
bool IsInAllowlist(std::string_view value,
const std::vector<std::string>& allowlist) {
return std::find_if(allowlist.begin(), allowlist.end(),
[&value](const std::string& allowed_value) {
return base::EqualsCaseInsensitiveASCII(value,
allowed_value);
}) != allowlist.end();
}
} // namespace
namespace remoting {
class HostProcess : public ConfigWatcher::Delegate,
public FtlHostChangeNotificationListener::Listener,
public HeartbeatSender::Delegate,
public IPC::Listener,
public base::RefCountedThreadSafe<HostProcess>,
#if BUILDFLAG(IS_MAC)
public mojom::AgentProcess,
#endif
public mojom::RemotingHostControl,
public mojom::WorkerProcessControl {
public:
// |shutdown_watchdog| is armed when shutdown is started, and should be kept
// alive as long as possible until the process exits (since destroying the
// watchdog disarms it).
HostProcess(std::unique_ptr<ChromotingHostContext> context,
int* exit_code_out,
ShutdownWatchdog* shutdown_watchdog);
HostProcess(const HostProcess&) = delete;
HostProcess& operator=(const HostProcess&) = delete;
// ConfigWatcher::Delegate interface.
void OnConfigUpdated(const std::string& serialized_config) override;
void OnConfigWatcherError() override;
// IPC::Listener implementation.
bool OnMessageReceived(const IPC::Message& message) override;
void OnChannelError() override;
void OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) override;
// FtlHostChangeNotificationListener::Listener overrides.
void OnHostDeleted() override;
#if BUILDFLAG(IS_MAC)
// mojom::AgentProcess overrides.
void ResumeProcess() override;
void SuspendProcess() override;
void BindRemotingHostControl(
mojo::PendingReceiver<mojom::RemotingHostControl> receiver) override;
#endif
private:
// See SetState method for a list of allowed state transitions.
enum HostState {
// Waiting for valid config and policies to be read from the disk.
// Either the host process has just been started, or it is trying to start
// again after temporarily going offline due to policy change or error.
HOST_STARTING,
// Host is started and running.
HOST_STARTED,
// Host is sending offline reason, before trying to restart.
HOST_GOING_OFFLINE_TO_RESTART,
// Host is sending offline reason, before shutting down.
HOST_GOING_OFFLINE_TO_STOP,
// Host has been stopped (host process will end soon).
HOST_STOPPED,
// Host has been suspended. Meaning it cannot send heartbeats or connect to
// signaling. In this state, it may either resume (transition to
// HOST_STARTING) or shut down (transition to HOST_GOING_OFFLINE_TO_STOP).
HOST_SUSPENDED,
};
enum PolicyState {
// Cannot start the host, because a valid policy has not been read yet.
POLICY_INITIALIZING,
// Policy was loaded successfully.
POLICY_LOADED,
// Policy error was detected, and we haven't yet sent out a
// host-offline-reason (i.e. because we haven't yet read the config).
POLICY_ERROR_REPORT_PENDING,
// Policy error was detected, and we have sent out a host-offline-reason.
POLICY_ERROR_REPORTED,
};
friend class base::RefCountedThreadSafe<HostProcess>;
~HostProcess() override;
void SetState(HostState target_state);
void StartOnNetworkThread();
void ShutdownOnNetworkThread();
#if BUILDFLAG(IS_POSIX)
// Callback passed to RegisterSignalHandler() to handle SIGTERM events.
void SigTermHandler(int signal_number);
#endif
// Called to initialize resources on the UI thread.
void StartOnUiThread();
// Initializes IPC control channel and config file path from |cmd_line|.
// Called on the UI thread.
bool InitWithCommandLine(const base::CommandLine* cmd_line);
// Called on the UI thread to start monitoring the configuration file.
void StartWatchingConfigChanges();
// Indicates whether |user_email| is allowed to access this machine based on
// |host_owner_emails_| and the client domain policies that are set.
// Provided as a Callback to Me2MeHostAuthenticatorFactory and is called for
// every connection attempt.
bool CheckAccessPermission(std::string_view user_email);
// Called on the network thread to set the host's Authenticator factory.
void CreateAuthenticatorFactory();
// Tear down resources that run on the UI thread.
void ShutdownOnUiThread();
// Determines whether a new config should be applied and handles starting or
// restarting the host process as necessary.
void OnConfigParsed(base::Value::Dict config);
// Applies the host config, returning true if successful.
bool ApplyConfig(const base::Value::Dict& config);
// Handles policy updates, by calling On*PolicyUpdate methods.
void OnPolicyUpdate(base::Value::Dict policies);
void OnPolicyError();
void ReportPolicyErrorAndRestartHost();
void ApplyHostDomainListPolicy();
void ApplyAllowRemoteAccessConnections();
bool OnClientDomainListPolicyUpdate(const base::Value::Dict& policies);
bool OnHostDomainListPolicyUpdate(const base::Value::Dict& policies);
bool OnPairingPolicyUpdate(const base::Value::Dict& policies);
bool OnGnubbyAuthPolicyUpdate(const base::Value::Dict& policies);
bool OnEnableUserInterfacePolicyUpdate(const base::Value::Dict& policies);
bool OnAllowRemoteAccessConnections(const base::Value::Dict& policies);
bool OnAllowPinAuthenticationUpdate(const base::Value::Dict& policies);
std::optional<ErrorCode> OnSessionPoliciesReceived(
const SessionPolicies& session_policies) const;
void InitializeSignaling();
void StartHostIfReady();
void StartHost();
// HeartbeatSender::Delegate implementation.
void OnFirstHeartbeatSuccessful() override;
void OnUpdateHostOwner(const std::string& host_owner) override;
void OnUpdateRequireSessionAuthorization(bool require_session_auth) override;
void OnHostNotFound() override;
void OnAuthFailed() override;
void OnZombieStateDetected();
void RestartHost(const std::string& host_offline_reason);
void ShutdownHost(HostExitCodes exit_code);
// Helper methods doing the work needed by RestartHost and ShutdownHost.
void GoOffline(const std::string& host_offline_reason);
void OnHostOfflineReasonAck(bool success);
// mojom::WorkerProcessControl implementation.
void CrashProcess(const std::string& function_name,
const std::string& file_name,
int line_number) override;
// mojom::RemotingHostControl implementation.
#if BUILDFLAG(IS_WIN)
void ApplyHostConfig(base::Value::Dict serialized_config) override;
void InitializePairingRegistry(
::mojo::PlatformHandle privileged_handle,
::mojo::PlatformHandle unprivileged_handle) override;
#endif
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
void BindChromotingHostServices(
mojo::PendingReceiver<mojom::ChromotingHostServices> receiver,
int peer_pid) override;
#endif
#if BUILDFLAG(IS_MAC)
void ConnectAgentProcessBroker();
void OnAgentProcessTerminationRequested();
void OnAgentProcessBrokerDisconnected();
#endif
std::unique_ptr<ChromotingHostContext> context_;
#if BUILDFLAG(IS_MAC)
// Created and used on the network thread.
std::unique_ptr<AgentProcessBrokerClient> agent_process_broker_client_;
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Watch for certificate changes and kill the host when changes occur
std::unique_ptr<CertificateWatcher> cert_watcher_;
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Created on the UI thread but used from the network thread.
base::FilePath host_config_path_;
std::string host_config_;
std::unique_ptr<DesktopEnvironmentFactory> desktop_environment_factory_;
// Accessed on the network thread.
HostState state_ = HOST_STARTING;
std::unique_ptr<ConfigWatcher> config_watcher_;
std::string host_id_;
std::string pin_hash_;
scoped_refptr<RsaKeyPair> key_pair_;
std::string oauth_refresh_token_;
std::string service_account_email_;
base::Value::Dict config_;
std::set<std::string> host_owner_emails_;
std::unique_ptr<PolicyWatcher> policy_watcher_;
PolicyState policy_state_ = POLICY_INITIALIZING;
std::vector<std::string> client_domain_list_;
std::vector<std::string> host_domain_list_;
bool allow_pairing_ = true;
bool enable_user_interface_ = true;
bool allow_remote_access_connections_ = true;
std::optional<bool> allow_pin_auth_;
bool is_cloud_host_ = false;
bool is_corp_host_ = false;
bool require_session_authorization_ = false;
LocalSessionPoliciesProvider local_session_policies_provider_;
DesktopEnvironmentOptions desktop_environment_options_;
bool security_key_auth_policy_enabled_ = false;
bool security_key_extension_supported_ = true;
// Allows us to override field trials which are causing issues for chromoting.
std::unique_ptr<base::FieldTrialList> field_trial_list_;
// Used to specify which window to stream, if enabled.
webrtc::WindowId window_id_ = 0;
// Must outlive |signal_strategy_| and |ftl_signaling_connector_|.
std::unique_ptr<OAuthTokenGetterImpl> oauth_token_getter_;
// Must outlive |heartbeat_sender_| and |host_|.
std::unique_ptr<InstanceIdentityTokenGetter> instance_identity_token_getter_;
// Must outlive |signal_strategy_| and |heartbeat_sender_|.
std::unique_ptr<ZombieHostDetector> zombie_host_detector_;
// Signal strategies must outlive |ftl_signaling_connector_|.
std::unique_ptr<SignalStrategy> signal_strategy_;
std::unique_ptr<FtlSignalingConnector> ftl_signaling_connector_;
std::unique_ptr<HeartbeatSender> heartbeat_sender_;
std::unique_ptr<FtlHostChangeNotificationListener>
ftl_host_change_notification_listener_;
std::unique_ptr<FtlEchoMessageListener> ftl_echo_message_listener_;
std::unique_ptr<HostEventLogger> host_event_logger_;
#if BUILDFLAG(IS_LINUX)
std::unique_ptr<HostWtmpdbLogger> host_wtmpdb_logger_;
#endif
std::unique_ptr<HostPowerSaveBlocker> power_save_blocker_;
// Only set if |is_corp_host_| is true.
std::unique_ptr<CorpHostStatusLogger> corp_host_status_logger_;
std::unique_ptr<ChromotingHost> host_;
// Used to keep this HostProcess alive until it is shutdown.
scoped_refptr<HostProcess> self_;
std::unique_ptr<mojo::core::ScopedIPCSupport> ipc_support_;
#if defined(REMOTING_MULTI_PROCESS)
// Accessed on the UI thread.
std::unique_ptr<IPC::ChannelProxy> daemon_channel_;
// Raw interface pointer which refers to the object owned by
// |desktop_environment_factory_|.
raw_ptr<DesktopSessionConnector> desktop_session_connector_ = nullptr;
#endif // defined(REMOTING_MULTI_PROCESS)
raw_ptr<int> exit_code_out_;
bool signal_parent_ = false;
std::string report_offline_reason_;
scoped_refptr<PairingRegistry> pairing_registry_;
raw_ptr<ShutdownWatchdog> shutdown_watchdog_;
// On Mac, `remoting_host_control_` is bound by the BindRemotingHostControl IPC,
// so it's a regular mojo receiver, while on Windows, this is bound by the
// legacy OnAssociatedInterfaceRequest, which requires using an associated
// receiver.
#if BUILDFLAG(IS_MAC)
mojo::Receiver<mojom::RemotingHostControl> remoting_host_control_{this};
#else
mojo::AssociatedReceiver<mojom::RemotingHostControl> remoting_host_control_{
this};
#endif
mojo::AssociatedReceiver<mojom::WorkerProcessControl> worker_process_control_{
this};
#if BUILDFLAG(IS_APPLE)
// When using the command line option to check the Accessibility or Screen
// Recording permission, these track the permission state and indicate that
// the host should exit immediately with the result.
bool checking_permission_state_ = false;
bool permission_granted_ = false;
#endif // BUILDFLAG(IS_APPLE)
};
HostProcess::HostProcess(std::unique_ptr<ChromotingHostContext> context,
int* exit_code_out,
ShutdownWatchdog* shutdown_watchdog)
: context_(std::move(context)),
desktop_environment_options_(DesktopEnvironmentOptions::CreateDefault()),
self_(this),
exit_code_out_(exit_code_out),
shutdown_watchdog_(shutdown_watchdog) {
// TODO(zijiehe):
// desktop_environment_options_.desktop_capture_options()
// ->set_use_update_notifications(true);
// And remove the same line from me2me_desktop_environment.cc.
StartOnUiThread();
#if BUILDFLAG(IS_APPLE)
if (checking_permission_state_) {
*exit_code_out = (permission_granted_ ? EXIT_SUCCESS : EXIT_FAILURE);
}
#endif
}
HostProcess::~HostProcess() {
// Verify that UI components have been torn down.
DCHECK(!config_watcher_);
DCHECK(!desktop_environment_factory_);
// We might be getting deleted on one of the threads the |host_context| owns,
// so we need to post it back to the caller thread to safely join & delete the
// threads it contains. This will go away when we move to AutoThread.
// |context_.release()| will null |context_| before the method is invoked, so
// we need to pull out the task-runner on which to call DeleteSoon first.
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
context_->ui_task_runner();
task_runner->DeleteSoon(FROM_HERE, context_.release());
}
bool HostProcess::InitWithCommandLine(const base::CommandLine* cmd_line) {
#if BUILDFLAG(IS_APPLE)
if (cmd_line->HasSwitch(kCheckAccessibilityPermissionSwitchName)) {
checking_permission_state_ = true;
permission_granted_ = mac::CanInjectInput();
return false;
}
if (cmd_line->HasSwitch(kCheckScreenRecordingPermissionSwitchName)) {
checking_permission_state_ = true;
permission_granted_ = mac::CanRecordScreen();
if (!permission_granted_) {
// This adds the host bundle to the list of apps under Security & Privacy
// -> Screen Recording. This may also show a system prompt (if the bundle
// was not previously in the list).
mac::RequestScreenCapturePermission();
}
return false;
}
if (cmd_line->HasSwitch(kListAudioDevicesSwitchName)) {
std::vector<AudioCapturerMac::AudioDeviceInfo> audio_devices =
AudioCapturerMac::GetAudioDevices();
printf("Audio devices:\n");
for (const auto& audio_device : audio_devices) {
printf("\n");
printf(" Device name: %s\n", audio_device.device_name.c_str());
printf(" Device UID: %s\n", audio_device.device_uid.c_str());
}
return false;
}
#endif // BUILDFLAG(IS_APPLE)
// Mojo keeps the task runner passed to it alive forever, so an
// AutoThreadTaskRunner should not be passed to it. Otherwise, the process may
// never shut down cleanly.
ipc_support_ = std::make_unique<mojo::core::ScopedIPCSupport>(
context_->network_task_runner()->task_runner(),
mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST);
#if defined(REMOTING_MULTI_PROCESS)
auto endpoint =
mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(*cmd_line);
if (!endpoint.is_valid()) {
LOG(ERROR) << "IPC channel endpoint provided via command line param was "
"missing or invalid";
return false;
}
auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint));
// Connect to the daemon process.
daemon_channel_ = IPC::ChannelProxy::Create(
invitation
.ExtractMessagePipe(cmd_line->GetSwitchValueASCII(kMojoPipeToken))
.release(),
IPC::Channel::MODE_CLIENT, this, context_->network_task_runner(),
base::SingleThreadTaskRunner::GetCurrentDefault());
#else // !defined(REMOTING_MULTI_PROCESS)
if (cmd_line->HasSwitch(kHostConfigSwitchName)) {
host_config_path_ = cmd_line->GetSwitchValuePath(kHostConfigSwitchName);
// Read config from stdin if necessary.
if (host_config_path_ == base::FilePath(kStdinConfigPath)) {
base::ReadStreamToString(stdin, &host_config_);
}
} else {
base::FilePath default_config_dir = remoting::GetConfigDir();
host_config_path_ = default_config_dir.Append(kDefaultHostConfigFile);
}
if (host_config_path_ != base::FilePath(kStdinConfigPath) &&
!base::PathExists(host_config_path_)) {
LOG(ERROR) << "Can't find host config at " << host_config_path_.value();
return false;
}
#endif // !defined(REMOTING_MULTI_PROCESS)
signal_parent_ = cmd_line->HasSwitch(kSignalParentSwitchName);
if (cmd_line->HasSwitch(kReportOfflineReasonSwitchName)) {
report_offline_reason_ =
cmd_line->GetSwitchValueASCII(kReportOfflineReasonSwitchName);
if (report_offline_reason_.empty()) {
LOG(ERROR) << "--" << kReportOfflineReasonSwitchName
<< " requires an argument.";
return false;
}
}
return true;
}
void HostProcess::OnConfigUpdated(const std::string& serialized_config) {
HOST_LOG << "Parsing new host configuration.";
std::optional<base::Value::Dict> config(
HostConfigFromJson(serialized_config));
if (!config.has_value()) {
LOG(ERROR) << "Invalid configuration.";
ShutdownHost(kInvalidHostConfigurationExitCode);
return;
}
OnConfigParsed(std::move(*config));
}
void HostProcess::OnConfigParsed(base::Value::Dict config) {
if (!context_->network_task_runner()->BelongsToCurrentThread()) {
context_->network_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&HostProcess::OnConfigParsed, this, std::move(config)));
return;
}
// Filter out duplicates.
if (config_ == config) {
return;
}
HOST_LOG << "Applying new host configuration.";
config_ = std::move(config);
if (!ApplyConfig(config_)) {
LOG(ERROR) << "Failed to apply the configuration.";
ShutdownHost(kInvalidHostConfigurationExitCode);
return;
}
if (state_ == HOST_STARTING) {
StartHostIfReady();
} else if (state_ == HOST_STARTED) {
// Reapply policies that could be affected by a new config.
DCHECK_EQ(policy_state_, POLICY_LOADED);
ApplyHostDomainListPolicy();
ApplyAllowRemoteAccessConnections();
// TODO(sergeyu): Here we assume that PIN is the only part of the config
// that may change while the service is running. Change ApplyConfig() to
// detect other changes in the config and restart host if necessary here.
CreateAuthenticatorFactory();
}
}
void HostProcess::OnConfigWatcherError() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
ShutdownHost(kInvalidHostConfigurationExitCode);
}
// Allowed state transitions (enforced via DCHECKs in SetState method):
// STARTING->STARTED (once we have valid config + policy)
// STARTING->SUSPENDED (on Mac where host processes need to be brokered)
// STARTING->GOING_OFFLINE_TO_STOP
// STARTING->GOING_OFFLINE_TO_RESTART
// STARTED->GOING_OFFLINE_TO_STOP
// STARTED->GOING_OFFLINE_TO_RESTART
// STARTED->SUSPENDED (informed by broker process to give way to process with
// higher priority)
// SUSPENDED->STARTING (resumed by broker process)
// SUSPENDED->GOING_OFFLINE_TO_STOP
// GOING_OFFLINE_TO_RESTART->GOING_OFFLINE_TO_STOP
// GOING_OFFLINE_TO_RESTART->STARTING (after OnHostOfflineReasonAck)
// GOING_OFFLINE_TO_STOP->STOPPED (after OnHostOfflineReasonAck)
//
// |host_| must be not-null in STARTED state and nullptr in all other states
// (although this invariant can be temporarily violated when doing
// synchronous processing on the networking thread).
void HostProcess::SetState(HostState target_state) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
// DCHECKs below enforce state allowed transitions listed in HostState.
switch (state_) {
case HOST_STARTING:
DCHECK((target_state == HOST_STARTED) ||
(target_state == HOST_GOING_OFFLINE_TO_STOP) ||
(target_state == HOST_GOING_OFFLINE_TO_RESTART) ||
(target_state == HOST_SUSPENDED))
<< state_ << " -> " << target_state;
break;
case HOST_STARTED:
DCHECK((target_state == HOST_GOING_OFFLINE_TO_STOP) ||
(target_state == HOST_GOING_OFFLINE_TO_RESTART) ||
(target_state == HOST_SUSPENDED))
<< state_ << " -> " << target_state;
break;
case HOST_GOING_OFFLINE_TO_RESTART:
DCHECK((target_state == HOST_GOING_OFFLINE_TO_STOP) ||
(target_state == HOST_STARTING) ||
(target_state == HOST_SUSPENDED))
<< state_ << " -> " << target_state;
break;
case HOST_GOING_OFFLINE_TO_STOP:
DCHECK_EQ(target_state, HOST_STOPPED);
break;
case HOST_SUSPENDED:
DCHECK((target_state == HOST_GOING_OFFLINE_TO_STOP) ||
(target_state == HOST_STARTING))
<< state_ << " -> " << target_state;
break;
case HOST_STOPPED: // HOST_STOPPED is a terminal state.
default:
NOTREACHED() << state_ << " -> " << target_state;
}
state_ = target_state;
}
void HostProcess::StartOnNetworkThread() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (state_ != HOST_STARTING) {
// Host was shutdown before the task had a chance to run.
return;
}
#if !defined(REMOTING_MULTI_PROCESS)
if (host_config_path_ == base::FilePath(kStdinConfigPath)) {
// Process config we've read from stdin.
OnConfigUpdated(host_config_);
} else {
// Start watching the host configuration file.
config_watcher_ = std::make_unique<ConfigFileWatcher>(
context_->network_task_runner(), context_->file_task_runner(),
host_config_path_);
config_watcher_->Watch(this);
}
#endif // !defined(REMOTING_MULTI_PROCESS)
#if BUILDFLAG(IS_POSIX)
remoting::RegisterSignalHandler(
SIGTERM, base::BindRepeating(&HostProcess::SigTermHandler,
base::Unretained(this)));
#endif // BUILDFLAG(IS_POSIX)
}
void HostProcess::ShutdownOnNetworkThread() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
config_watcher_.reset();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
cert_watcher_.reset();
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
}
#if BUILDFLAG(IS_POSIX)
void HostProcess::SigTermHandler(int signal_number) {
DCHECK(signal_number == SIGTERM);
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
HOST_LOG << "Caught SIGTERM: Shutting down...";
ShutdownHost(kSuccessExitCode);
}
#endif // BUILDFLAG(IS_POSIX)
bool HostProcess::CheckAccessPermission(std::string_view user_email_view) {
// |user_email_view| may already be in a canonical form but we transform it
// just in case so that it matches the format we use in |host_owner_emails_|.
// TODO: joedow - Add an overload for GetCanonicalEmail() which takes a
// std::string_view.
auto canonical_email = GetCanonicalEmail(std::string(user_email_view));
auto email_parts = base::SplitStringOnce(canonical_email, '@');
if (!email_parts) {
LOG(ERROR) << "Unexpected email address format: " << user_email_view;
return false;
}
if (!host_owner_emails_.contains(canonical_email)) {
LOG(ERROR) << canonical_email << " does not have access to this machine.";
return false;
}
// Verify the remote user is not disallowed based on the client domain policy.
if (client_domain_list_.empty()) {
return true;
}
auto [_, domain] = *email_parts;
bool allowed_by_policy = IsInAllowlist(domain, client_domain_list_);
LOG_IF(ERROR, !allowed_by_policy) << canonical_email << " has a domain which "
<< "is not in the client domain allowlist.";
return allowed_by_policy;
}
void HostProcess::CreateAuthenticatorFactory() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (state_ != HOST_STARTED) {
return;
}
std::string local_certificate = key_pair_->GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
ShutdownHost(kInitializationFailed);
return;
}
auto auth_config = std::make_unique<protocol::HostAuthenticationConfig>(
local_certificate, key_pair_);
if (is_cloud_host_) {
CHECK(require_session_authorization_);
// |instance_identity_token_getter_| is initialized when we configured the
// heartbeat sender to target Cloud APIs, the expectation is that it will
// be initialized well before the point we need it for session authz.
CHECK(instance_identity_token_getter_);
auth_config->AddSessionAuthzAuth(
base::MakeRefCounted<CloudSessionAuthzServiceClientFactory>(
oauth_token_getter_.get(), instance_identity_token_getter_.get(),
context_->url_loader_factory()));
} else if (require_session_authorization_ ||
(is_corp_host_ && !allow_pin_auth_.value_or(false))) {
auth_config->AddSessionAuthzAuth(
base::MakeRefCounted<CorpSessionAuthzServiceClientFactory>(
context_->url_loader_factory(),
context_->create_client_cert_store_callback(),
service_account_email_, oauth_refresh_token_));
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
if (!cert_watcher_) {
cert_watcher_ = std::make_unique<CertificateWatcher>(
base::BindRepeating(&HostProcess::ShutdownHost,
base::Unretained(this), kSuccessExitCode),
context_->file_task_runner());
cert_watcher_->Start();
}
cert_watcher_->SetMonitor(host_->status_monitor());
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
} else {
scoped_refptr<PairingRegistry> pairing_registry;
if (allow_pairing_) {
// On Windows |pairing_registry_| is initialized in
// InitializePairingRegistry().
#if !BUILDFLAG(IS_WIN)
if (!pairing_registry_) {
std::unique_ptr<PairingRegistry::Delegate> delegate =
CreatePairingRegistryDelegate();
if (delegate) {
pairing_registry_ = new PairingRegistry(context_->file_task_runner(),
std::move(delegate));
}
}
#endif // BUILDFLAG(IS_WIN)
pairing_registry = pairing_registry_;
}
auth_config->AddPairingAuth(pairing_registry);
auth_config->AddSharedSecretAuth(pin_hash_);
host_->set_pairing_registry(pairing_registry);
}
HOST_LOG << "Host's supported authentication methods: ";
for (const auto& method : auth_config->GetSupportedMethods()) {
HOST_LOG << " " << AuthenticationMethodToString(method);
}
std::unique_ptr<protocol::AuthenticatorFactory> factory =
std::make_unique<protocol::Me2MeHostAuthenticatorFactory>(
base::BindRepeating(&HostProcess::CheckAccessPermission, this),
std::move(auth_config));
#if BUILDFLAG(IS_POSIX)
// On Linux and Mac, perform a PAM authorization step after authentication.
factory = std::make_unique<PamAuthorizationFactory>(std::move(factory));
#endif // BUILDFLAG(IS_POSIX)
host_->SetAuthenticatorFactory(std::move(factory));
}
// IPC::Listener implementation.
bool HostProcess::OnMessageReceived(const IPC::Message& message) {
NOTREACHED() << "Received unexpected IPC type: " << message.type();
}
void HostProcess::OnChannelError() {
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread());
// Shutdown the host if the daemon process disconnects the IPC channel.
context_->network_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&HostProcess::ShutdownHost, this, kSuccessExitCode));
}
void HostProcess::OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) {
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread());
#if defined(REMOTING_MULTI_PROCESS)
if (interface_name == mojom::RemotingHostControl::Name_) {
if (remoting_host_control_.is_bound()) {
LOG(ERROR) << "Receiver already bound for associated interface: "
<< mojom::RemotingHostControl::Name_;
CrashProcess(__FUNCTION__, __FILE__, __LINE__);
}
mojo::PendingAssociatedReceiver<mojom::RemotingHostControl>
pending_receiver(std::move(handle));
remoting_host_control_.Bind(std::move(pending_receiver));
} else if (interface_name == mojom::WorkerProcessControl::Name_) {
if (worker_process_control_.is_bound()) {
LOG(ERROR) << "Receiver already bound for associated interface: "
<< mojom::WorkerProcessControl::Name_;
CrashProcess(__FUNCTION__, __FILE__, __LINE__);
}
mojo::PendingAssociatedReceiver<mojom::WorkerProcessControl>
pending_receiver(std::move(handle));
worker_process_control_.Bind(std::move(pending_receiver));
} else if (interface_name == mojom::DesktopSessionConnectionEvents::Name_) {
if (!desktop_session_connector_->BindConnectionEventsReceiver(
std::move(handle))) {
LOG(ERROR) << "Failed to bind Receiver for associated interface: "
<< mojom::DesktopSessionConnectionEvents::Name_;
CrashProcess(__FUNCTION__, __FILE__, __LINE__);
}
} else {
LOG(ERROR) << "Unknown associated interface requested: " << interface_name
<< ", crashing the network process";
CrashProcess(__FUNCTION__, __FILE__, __LINE__);
}
#else // !defined(REMOTING_MULTI_PROCESS)
LOG(ERROR) << "Unexpected call requesting an associated interface: "
<< interface_name << ", crashing the network process";
CrashProcess(__FUNCTION__, __FILE__, __LINE__);
#endif // !defined(REMOTING_MULTI_PROCESS)
}
void HostProcess::StartOnUiThread() {
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread());
if (!InitWithCommandLine(base::CommandLine::ForCurrentProcess())) {
// Shutdown the host if the command line is invalid.
ShutdownOnUiThread();
return;
}
// Determine if the CPU this host is running on meets a set of minimum
// requirements. Note that this isn't a perfect solution as it is possible
// that the host will have crashed prior to reaching this point in the code,
// however this is the earliest time we can log an offline reason to the
// directory if it is unsupported.
if (!IsCpuSupported()) {
report_offline_reason_ = ExitCodeToString(kCpuNotSupported);
}
if (!report_offline_reason_.empty()) {
// Don't need to do any UI initialization.
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::StartOnNetworkThread, this));
return;
}
HostSettings::Initialize();
policy_watcher_ = PolicyWatcher::CreateWithTaskRunner(
context_->file_task_runner(), context_->management_service());
policy_watcher_->StartWatching(
base::BindRepeating(&HostProcess::OnPolicyUpdate, base::Unretained(this)),
base::BindRepeating(&HostProcess::OnPolicyError, base::Unretained(this)));
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// If an audio pipe is specific on the command-line then initialize
// AudioCapturerLinux to capture from it.
base::FilePath audio_pipe_name =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
kAudioPipeSwitchName);
if (!audio_pipe_name.empty()) {
remoting::AudioCapturerLinux::InitializePipeReader(
context_->audio_task_runner(), audio_pipe_name);
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_POSIX)
base::FilePath security_key_socket_name =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
kAuthSocknameSwitchName);
if (!security_key_socket_name.empty()) {
remoting::SecurityKeyAuthHandler::SetSecurityKeySocketName(
security_key_socket_name);
} else {
security_key_extension_supported_ = false;
}
#endif // BUILDFLAG(IS_POSIX)
// Create a desktop environment factory appropriate to the build type &
// platform.
#if defined(REMOTING_MULTI_PROCESS)
// Set up the AssociatedRemote used to send requests to the Daemon process.
// We need to do a little dance here using a pending associated receiver so
// that the remote is associated with the proper task_runner since it will be
// invoked on the network thread.
mojo::AssociatedRemote<mojom::DesktopSessionManager> remote;
mojo::GenericPendingAssociatedReceiver pending_receiver =
remote.BindNewEndpointAndPassReceiver(context_->network_task_runner());
daemon_channel_->GetRemoteAssociatedInterface(std::move(pending_receiver));
IpcDesktopEnvironmentFactory* desktop_environment_factory =
new IpcDesktopEnvironmentFactory(
context_->audio_task_runner(), context_->network_task_runner(),
context_->network_task_runner(), std::move(remote));
desktop_session_connector_ = desktop_environment_factory;
#else // !defined(REMOTING_MULTI_PROCESS)
Me2MeDesktopEnvironmentFactory* desktop_environment_factory =
new Me2MeDesktopEnvironmentFactory(
context_->network_task_runner(), context_->ui_task_runner(),
CreateDesktopInteractionStrategyFactory(
context_->network_task_runner(), context_->ui_task_runner(),
context_->video_capture_task_runner(),
context_->input_task_runner()));
#endif // !defined(REMOTING_MULTI_PROCESS)
desktop_environment_factory_.reset(desktop_environment_factory);
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::StartOnNetworkThread, this));
}
void HostProcess::ShutdownOnUiThread() {
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread());
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::ShutdownOnNetworkThread, this));
// Tear down resources that need to be torn down on the UI thread.
desktop_environment_factory_.reset();
policy_watcher_.reset();
#if defined(REMOTING_MULTI_PROCESS)
daemon_channel_.reset();
desktop_session_connector_ = nullptr;
#endif // defined(REMOTING_MULTI_PROCESS)
// Release the remotes after the daemon channel has been closed.
remoting_host_control_.reset();
worker_process_control_.reset();
// It is now safe for the HostProcess to be deleted.
self_ = nullptr;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Cause the global AudioPipeReader to be freed, otherwise the audio
// thread will remain in-use and prevent the process from exiting.
// TODO(wez): DesktopEnvironmentFactory should own the pipe reader.
// See crbug.com/161373 and crbug.com/104544.
AudioCapturerLinux::InitializePipeReader(nullptr, base::FilePath());
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(REMOTING_USE_X11)
context_->input_task_runner()->PostTask(
FROM_HERE,
base::BindOnce([]() { delete ui::X11EventSource::GetInstance(); }));
#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) &&
// defined(REMOTING_USE_X11)
}
void HostProcess::OnHostNotFound() {
LOG(ERROR) << "Host ID not found.";
ShutdownHost(kInvalidHostIdExitCode);
}
void HostProcess::OnFirstHeartbeatSuccessful() {
if (state_ != HOST_STARTED) {
return;
}
HOST_LOG << "Host ready to receive connections.";
#if BUILDFLAG(IS_POSIX)
if (signal_parent_) {
kill(getppid(), SIGUSR1);
signal_parent_ = false;
}
#endif
}
void HostProcess::OnUpdateHostOwner(const std::string& owner_email) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!owner_email.empty());
// Use a canonical email form here for matching against FTL signaling IDs.
auto new_owner_email = GetCanonicalEmail(owner_email);
if (host_owner_emails_.contains(new_owner_email)) {
return;
}
LOG(INFO) << "Adding '" << new_owner_email << "' to host owner emails.";
host_owner_emails_.emplace(std::move(new_owner_email));
ApplyHostDomainListPolicy();
}
void HostProcess::OnUpdateRequireSessionAuthorization(bool require) {
if (require == require_session_authorization_) {
return;
}
LOG(INFO) << "Updating require_session_authorization from "
<< require_session_authorization_ << " to " << require;
require_session_authorization_ = require;
}
void HostProcess::OnHostDeleted() {
LOG(ERROR) << "Host was deleted from the directory.";
ShutdownHost(kHostDeletedExitCode);
}
#if BUILDFLAG(IS_MAC)
void HostProcess::ResumeProcess() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (state_ == HOST_GOING_OFFLINE_TO_STOP) {
return;
}
HOST_LOG << "Resuming process";
SetState(HOST_STARTING);
StartHostIfReady();
}
void HostProcess::SuspendProcess() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (state_ == HOST_SUSPENDED || state_ == HOST_GOING_OFFLINE_TO_STOP) {
return;
}
HOST_LOG << "Suspending process";
SetState(HOST_SUSPENDED);
GoOffline(kHostOfflineReasonSuspended);
}
void HostProcess::BindRemotingHostControl(
mojo::PendingReceiver<mojom::RemotingHostControl> receiver) {
if (!context_->ui_task_runner()->BelongsToCurrentThread()) {
context_->ui_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::BindRemotingHostControl, this,
std::move(receiver)));
return;
}
DCHECK(!remoting_host_control_.is_bound());
remoting_host_control_.Bind(std::move(receiver));
}
#endif
#if BUILDFLAG(IS_WIN)
void HostProcess::ApplyHostConfig(base::Value::Dict config) {
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread());
OnConfigParsed(std::move(config));
}
void HostProcess::InitializePairingRegistry(
::mojo::PlatformHandle privileged_handle,
::mojo::PlatformHandle unprivileged_handle) {
// This IPC is handled on the UI thread and bounced over to the network thread
// so being called on any other thread is unexpected.
DCHECK(context_->ui_task_runner()->BelongsToCurrentThread() ||
context_->network_task_runner()->BelongsToCurrentThread());
if (context_->ui_task_runner()->BelongsToCurrentThread()) {
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::InitializePairingRegistry, this,
std::move(privileged_handle),
std::move(unprivileged_handle)));
return;
}
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
// |pairing_registry_| must only be initialized once.
DCHECK(!pairing_registry_) << "Received multiple calls to initialize the "
<< "pairing registry";
std::unique_ptr<PairingRegistryDelegateWin> delegate(
new PairingRegistryDelegateWin());
delegate->SetRootKeys(static_cast<HKEY>(privileged_handle.ReleaseHandle()),
static_cast<HKEY>(unprivileged_handle.ReleaseHandle()));
pairing_registry_ =
new PairingRegistry(context_->file_task_runner(), std::move(delegate));
// (Re)Create the authenticator factory now that |pairing_registry_| has been
// initialized.
CreateAuthenticatorFactory();
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
void HostProcess::BindChromotingHostServices(
mojo::PendingReceiver<mojom::ChromotingHostServices> receiver,
int peer_pid) {
if (context_->ui_task_runner()->BelongsToCurrentThread()) {
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::BindChromotingHostServices,
this, std::move(receiver), peer_pid));
return;
}
// This IPC is handled on the UI thread and bounced over to the network thread
// so being called on any other thread is unexpected.
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (!host_) {
LOG(ERROR) << "Binding rejected. Host has not started.";
return;
}
host_->BindChromotingHostServices(std::move(receiver), peer_pid);
}
#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#if BUILDFLAG(IS_MAC)
void HostProcess::ConnectAgentProcessBroker() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
agent_process_broker_client_ = std::make_unique<AgentProcessBrokerClient>(
base::BindOnce(&HostProcess::OnAgentProcessTerminationRequested,
base::Unretained(this)),
base::BindOnce(&HostProcess::OnAgentProcessBrokerDisconnected,
base::Unretained(this)));
if (!agent_process_broker_client_->ConnectToServer()) {
LOG(ERROR) << "Failed to connect to agent process broker.";
ShutdownHost(kInitializationFailed);
return;
}
agent_process_broker_client_->OnAgentProcessLaunched(this);
}
void HostProcess::OnAgentProcessTerminationRequested() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
HOST_LOG << "Host terminated by agent process broker.";
ShutdownHost(kTerminatedByAgentProcessBroker);
}
void HostProcess::OnAgentProcessBrokerDisconnected() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
HOST_LOG << "Agent process broker disconnected.";
ShutdownHost(kAgentProcessBrokerDisconnected);
}
#endif // BUILDFLAG(IS_MAC)
// Applies the host config, returning true if successful.
bool HostProcess::ApplyConfig(const base::Value::Dict& config) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
const std::string* host_id = config.FindString(kHostIdConfigPath);
if (!host_id) {
LOG(ERROR) << "Host config is missing a required path: `"
<< kHostIdConfigPath << "`";
return false;
}
host_id_ = *host_id;
const std::string* key_base64 = config.FindString(kPrivateKeyConfigPath);
if (!key_base64) {
LOG(ERROR) << "Host config is missing a required path: `"
<< kPrivateKeyConfigPath << "`";
return false;
}
key_pair_ = RsaKeyPair::FromString(*key_base64);
if (!key_pair_.get()) {
LOG(ERROR) << "Host config has an invalid value for path: `"
<< kPrivateKeyConfigPath << "`";
return false;
}
// Retrieve the service account used for signaling and backend requests.
const std::string* service_account_email =
config.FindString(kServiceAccountConfigPath);
if (!service_account_email) {
LOG(ERROR) << "Host config is missing a required path: `"
<< kServiceAccountConfigPath << "`";
return false;
}
service_account_email_ = *service_account_email;
// Retrieve robot account credentials for session signaling.
const std::string* oauth_refresh_token =
config.FindString(kOAuthRefreshTokenConfigPath);
if (!oauth_refresh_token) {
LOG(ERROR) << "Host config is missing a required path: `"
<< kOAuthRefreshTokenConfigPath << "`";
return false;
}
oauth_refresh_token_ = *oauth_refresh_token;
// Retrieve the host_owner field value.
const std::string* host_owner = config.FindString(kHostOwnerConfigPath);
if (!host_owner) {
LOG(ERROR) << "Host config is missing a required path: `"
<< kHostOwnerConfigPath << "`";
return false;
}
// TODO: joedow - Remove the email check once all Corp hosts have a hint set.
bool has_google_email = IsGoogleEmail(*host_owner);
OnUpdateHostOwner(*host_owner);
auto* host_type_hint = config.FindString(kHostTypeHintPath);
is_cloud_host_ = (host_type_hint && *host_type_hint == kCloudHostTypeHint);
// TODO: joedow - Remove the !is_cloud_host override here when all Corp hosts
// have a hint set. This is used to allow Googlers to test with Cloud hosts.
is_corp_host_ = (host_type_hint && *host_type_hint == kCorpHostTypeHint) ||
(has_google_email && !is_cloud_host_);
require_session_authorization_ =
config.FindBool(kRequireSessionAuthorizationPath).value_or(false);
const std::string* host_secret_hash =
config.FindString(kHostSecretHashConfigPath);
if (require_session_authorization_) {
HOST_LOG << "Host config specifies that Session Authorization is required.";
HOST_LOG << "PIN authentication is disabled.";
} else if (host_secret_hash) {
if (!ParsePinHashFromConfig(*host_secret_hash, host_id_, &pin_hash_)) {
LOG(ERROR) << "Host config has an invalid value for path: `"
<< kHostSecretHashConfigPath << "`";
return false;
}
} else if (is_corp_host_) {
// TODO: joedow - Remove this codepath once all Corp host configs include
// the kRequireSessionAuthorizationPath attribute.
HOST_LOG << "No value store for: " << kHostSecretHashConfigPath << ". PIN "
<< "authentication is disabled.";
} else {
LOG(ERROR) << "Host config is missing a required path: `"
<< kHostSecretHashConfigPath << "`";
return false;
}
return true;
}
void HostProcess::OnPolicyUpdate(base::Value::Dict policies) {
if (!context_->network_task_runner()->BelongsToCurrentThread()) {
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::OnPolicyUpdate, this,
std::move(policies)));
return;
}
// Update the local policies held by `local_session_policies_provider_`. This
// will notify any active client sessions of the updated local session
// policies. Those sessions will terminate themselves if their effective
// session policies come from `local_session_policies_provider_`.
// Use the platform policies instead of `policies`, since the latter only has
// incremental changes.
std::optional<SessionPolicies> local_session_policies =
SessionPoliciesFromDict(policy_watcher_->GetPlatformPolicies());
if (!local_session_policies.has_value()) {
OnPolicyError();
return;
}
local_session_policies_provider_.set_local_policies(*local_session_policies);
bool restart_required = false;
restart_required |= OnClientDomainListPolicyUpdate(policies);
restart_required |= OnHostDomainListPolicyUpdate(policies);
restart_required |= OnPairingPolicyUpdate(policies);
restart_required |= OnGnubbyAuthPolicyUpdate(policies);
restart_required |= OnEnableUserInterfacePolicyUpdate(policies);
restart_required |= OnAllowRemoteAccessConnections(policies);
restart_required |= OnAllowPinAuthenticationUpdate(policies);
policy_state_ = POLICY_LOADED;
if (state_ == HOST_STARTING) {
DCHECK(!host_);
StartHostIfReady();
} else if (state_ == HOST_STARTED) {
if (restart_required) {
RestartHost(kHostOfflineReasonPolicyChangeRequiresRestart);
}
}
}
void HostProcess::OnPolicyError() {
if (!context_->network_task_runner()->BelongsToCurrentThread()) {
context_->network_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::OnPolicyError, this));
return;
}
if (policy_state_ != POLICY_ERROR_REPORTED) {
policy_state_ = POLICY_ERROR_REPORT_PENDING;
if ((state_ == HOST_STARTED) ||
(state_ == HOST_STARTING && !config_.empty())) {
ReportPolicyErrorAndRestartHost();
}
}
}
void HostProcess::ReportPolicyErrorAndRestartHost() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!config_.empty());
DCHECK_EQ(policy_state_, POLICY_ERROR_REPORT_PENDING);
policy_state_ = POLICY_ERROR_REPORTED;
HOST_LOG << "Restarting the host due to policy errors.";
RestartHost(kHostOfflineReasonPolicyReadError);
}
void HostProcess::ApplyHostDomainListPolicy() {
if (state_ != HOST_STARTED) {
return;
}
HOST_LOG << "Policy sets host domains: "
<< base::JoinString(host_domain_list_, ", ");
if (host_domain_list_.empty()) {
return;
}
std::set<std::string> allowed_emails;
for (const std::string& owner_email : host_owner_emails_) {
auto email_parts = base::SplitStringOnce(owner_email, '@');
if (!email_parts.has_value()) {
LOG(WARNING) << owner_email << " is not a valid email address";
continue;
}
auto domain = email_parts->second;
bool allowed_by_policy = IsInAllowlist(domain, host_domain_list_);
if (allowed_by_policy) {
allowed_emails.emplace(owner_email);
} else {
LOG(WARNING) << owner_email << " is not allowed by host domain policy";
}
}
host_owner_emails_.swap(allowed_emails);
if (host_owner_emails_.empty()) {
LOG(ERROR) << "No owner emails are allowed based on host domain policy.";
ShutdownHost(kInvalidHostDomainExitCode);
}
}
void HostProcess::ApplyAllowRemoteAccessConnections() {
if (state_ != HOST_STARTED) {
return;
}
HOST_LOG << "Policy allows remote access connections: "
<< allow_remote_access_connections_;
if (!allow_remote_access_connections_) {
ShutdownHost(kRemoteAccessDisallowedExitCode);
}
}
bool HostProcess::OnHostDomainListPolicyUpdate(
const base::Value::Dict& policies) {
// Returns false: never restart the host after this policy update.
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
const base::Value::List* list =
policies.FindList(policy::key::kRemoteAccessHostDomainList);
if (!list) {
return false;
}
host_domain_list_.clear();
for (const auto& value : *list) {
host_domain_list_.push_back(value.GetString());
}
ApplyHostDomainListPolicy();
return false;
}
bool HostProcess::OnClientDomainListPolicyUpdate(
const base::Value::Dict& policies) {
// Returns true if the host has to be restarted after this policy update.
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
const base::Value::List* list =
policies.FindList(policy::key::kRemoteAccessHostClientDomainList);
if (!list) {
return false;
}
client_domain_list_.clear();
for (const auto& value : *list) {
client_domain_list_.push_back(value.GetString());
}
return true;
}
bool HostProcess::OnPairingPolicyUpdate(const base::Value::Dict& policies) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::optional<bool> allow_pairing =
policies.FindBool(policy::key::kRemoteAccessHostAllowClientPairing);
if (!allow_pairing.has_value()) {
return false;
}
allow_pairing_ = *allow_pairing;
if (allow_pairing_) {
HOST_LOG << "Policy enables client pairing.";
} else {
HOST_LOG << "Policy disables client pairing.";
}
return true;
}
bool HostProcess::OnGnubbyAuthPolicyUpdate(const base::Value::Dict& policies) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::optional<bool> security_key_auth_policy_enabled =
policies.FindBool(policy::key::kRemoteAccessHostAllowGnubbyAuth);
if (!security_key_auth_policy_enabled.has_value()) {
return false;
}
security_key_auth_policy_enabled_ = *security_key_auth_policy_enabled;
if (security_key_auth_policy_enabled_) {
HOST_LOG << "Policy enables security key auth.";
} else {
HOST_LOG << "Policy disables security key auth.";
}
return true;
}
bool HostProcess::OnAllowPinAuthenticationUpdate(
const base::Value::Dict& policies) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
const base::Value* allow_pin_auth =
policies.Find(policy::key::kRemoteAccessHostAllowPinAuthentication);
if (!allow_pin_auth) {
return false;
}
// Save the value until we have parsed the host config since the default
// behavior depends on whether the user is a googler.
if (allow_pin_auth->is_none()) {
// The policy has been unset.
allow_pin_auth_.reset();
} else {
allow_pin_auth_ = allow_pin_auth->GetIfBool();
DCHECK(allow_pin_auth_.has_value());
if (*allow_pin_auth_) {
HOST_LOG << "Policy allows PIN and pairing authentication methods.";
} else {
HOST_LOG << "Policy disallows PIN or pairing authentication methods.";
}
}
// Restart required.
return true;
}
bool HostProcess::OnEnableUserInterfacePolicyUpdate(
const base::Value::Dict& policies) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::optional<bool> enable_user_interface =
policies.FindBool(policy::key::kRemoteAccessHostEnableUserInterface);
if (!enable_user_interface) {
return false;
}
// Save the value until we have parsed the host config since we only want the
// policy to be applied to machines owned by a Googler.
enable_user_interface_ = *enable_user_interface;
if (enable_user_interface_) {
HOST_LOG << "Policy enables user interface for non-curtained sessions.";
} else {
HOST_LOG << "Policy disables user interface for non-curtained sessions.";
}
// Restart required.
return true;
}
bool HostProcess::OnAllowRemoteAccessConnections(
const base::Value::Dict& policies) {
// Returns false: never restart the host after this policy update.
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::optional<bool> allow_remote_access_connections = policies.FindBool(
policy::key::kRemoteAccessHostAllowRemoteAccessConnections);
if (!allow_remote_access_connections.has_value()) {
return false;
}
// Update the value if the policy was set and retrieval was successful.
allow_remote_access_connections_ = *allow_remote_access_connections;
ApplyAllowRemoteAccessConnections();
return false;
}
std::optional<ErrorCode> HostProcess::OnSessionPoliciesReceived(
const SessionPolicies& session_policies) const {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
// We currently only validate the host_username_match_required policy here.
// Other policies are validated by ClientSession.
if (!session_policies.host_username_match_required.value_or(false)) {
return std::nullopt;
}
#if BUILDFLAG(IS_WIN)
VLOG(1) << "Policy host_username_match_required ignored since it is not "
<< "supported on Windows.";
return std::nullopt;
#else // BUILDFLAG(IS_WIN) #else
#if BUILDFLAG(IS_APPLE)
// On Mac, we run as root at the login screen, so the username won't match.
// However, there's no need to enforce the policy at the login screen, as
// the client will have to reconnect if a login occurs.
if (getuid() == 0) {
return std::nullopt;
}
#endif
std::string username = GetUsername();
LOG(INFO) << "Current local username is '" << username << "'";
std::set<std::string> allowed_emails;
for (const std::string& owner_email : host_owner_emails_) {
auto email_parts = base::SplitStringOnce(owner_email, '@');
if (!email_parts.has_value()) {
LOG(WARNING) << owner_email << " is not a valid email address";
continue;
}
auto owner_username = email_parts->first;
if (base::EqualsCaseInsensitiveASCII(username, owner_username)) {
LOG(INFO) << owner_email << " matches the local username";
allowed_emails.emplace(owner_email);
} else {
LOG(WARNING) << owner_email << " does not match the local username";
}
}
if (allowed_emails.empty()) {
LOG(ERROR) << "No owner emails are allowed based on match username policy.";
// TODO: crbug.com/359977809 - Add a new error code for mismatched username.
return ErrorCode::DISALLOWED_BY_POLICY;
}
return std::nullopt;
#endif // BUILDFLAG(IS_WIN) #else
}
void HostProcess::InitializeSignaling() {
DCHECK(!host_id_.empty()); // ApplyConfig() should already have been run.
DCHECK(!signal_strategy_);
DCHECK(!oauth_token_getter_);
DCHECK(!ftl_signaling_connector_);
DCHECK(!heartbeat_sender_);
auto oauth_credentials =
std::make_unique<OAuthTokenGetter::OAuthAuthorizationCredentials>(
service_account_email_, oauth_refresh_token_,
/* is_service_account */ true);
// Unretained is sound because we own the OAuthTokenGetterImpl, and the
// callback will never be invoked once it is destroyed.
oauth_token_getter_ = std::make_unique<OAuthTokenGetterImpl>(
std::move(oauth_credentials), context_->url_loader_factory(), false);
zombie_host_detector_ = std::make_unique<ZombieHostDetector>(base::BindOnce(
&HostProcess::OnZombieStateDetected, base::Unretained(this)));
auto ftl_signal_strategy = std::make_unique<FtlSignalStrategy>(
std::make_unique<OAuthTokenGetterProxy>(
oauth_token_getter_->GetWeakPtr()),
context_->url_loader_factory(),
std::make_unique<FtlHostDeviceIdProvider>(host_id_),
zombie_host_detector_.get());
ftl_signaling_connector_ = std::make_unique<FtlSignalingConnector>(
ftl_signal_strategy.get(),
base::BindOnce(&HostProcess::OnAuthFailed, base::Unretained(this)));
ftl_signaling_connector_->Start();
// Create the appropriate API service client (corp, cloud, or me2me) for the
// HeartbeatSender.
std::unique_ptr<HeartbeatServiceClient> service_client;
if (is_cloud_host_) {
// Initialize |instance_identity_token_getter_| so it can be used to
// generate tokens for calling the private Remoting Cloud API.
instance_identity_token_getter_ =
std::make_unique<InstanceIdentityTokenGetterImpl>(
base::StringPrintf(
"https://%s",
ServiceUrls::GetInstance()->remoting_cloud_private_endpoint()),
context_->url_loader_factory());
service_client = std::make_unique<CloudHeartbeatServiceClient>(
host_id_, oauth_token_getter_.get(),
instance_identity_token_getter_.get(), context_->url_loader_factory());
// TODO: joedow - Implement CorpHeartbeatServiceClient.
// } else if (is_corp_host_) {
// service_client = std::make_unique<CorpHeartbeatServiceClient>(
// host_id_, oauth_token_getter_.get(),
// context_->url_loader_factory());
} else {
service_client = std::make_unique<Me2MeHeartbeatServiceClient>(
host_id_, is_corp_host_, oauth_token_getter_.get(),
context_->url_loader_factory());
}
heartbeat_sender_ = std::make_unique<HeartbeatSender>(
this, host_id_, ftl_signal_strategy.get(), oauth_token_getter_.get(),
std::move(service_client), zombie_host_detector_.get(),
context_->url_loader_factory(), is_corp_host_);
signal_strategy_ = std::move(ftl_signal_strategy);
zombie_host_detector_->Start();
}
void HostProcess::StartHostIfReady() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK_EQ(state_, HOST_STARTING);
// Start the host if both the config and the policies are loaded.
if (!config_.empty()) {
if (!report_offline_reason_.empty()) {
SetState(HOST_GOING_OFFLINE_TO_STOP);
GoOffline(report_offline_reason_);
} else if (policy_state_ == POLICY_LOADED) {
StartHost();
} else if (policy_state_ == POLICY_ERROR_REPORT_PENDING) {
ReportPolicyErrorAndRestartHost();
}
}
}
void HostProcess::StartHost() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!host_);
#if BUILDFLAG(IS_MAC)
if (!agent_process_broker_client_) {
HOST_LOG << "Suspending process to wait for broker outcome";
SetState(HOST_SUSPENDED);
ConnectAgentProcessBroker();
return;
}
#endif
// This thread is used as a network thread in WebRTC.
webrtc::ThreadWrapper::EnsureForCurrentMessageLoop();
// Initialize global field trials. In case this code runs a second time,
// check for any previous instance - see crbug.com/349062464.
if (!field_trial_list_) {
field_trial_list_ = std::make_unique<base::FieldTrialList>();
// Override LossBasedBweV2 trial.
// TODO(b/266103942): Remove this override once we figure out why the BWE is
// crashing for some users and have a fix available.
base::FieldTrialList::CreateTrialsFromString(
"WebRTC-Bwe-LossBasedBweV2/Enabled:false/");
}
SetState(HOST_STARTED);
InitializeSignaling();
// Create the appropriate API service client (corp, cloud, or me2me) for the
// IceConfigFetcher.
std::unique_ptr<protocol::IceConfigFetcher> ice_config_fetcher;
if (is_cloud_host_) {
ice_config_fetcher = std::make_unique<protocol::IceConfigFetcherCloud>(
context_->url_loader_factory(), oauth_token_getter_.get(),
instance_identity_token_getter_.get());
// TODO: joedow - Implement IceConfigFetcherCorp.
// } else if (is_corp_host_) {
// ice_config_fetcher = std::make_unique<protocol::IceConfigFetcherCorp>(
// context_->url_loader_factory(), oauth_token_getter_.get());
} else {
ice_config_fetcher = std::make_unique<protocol::IceConfigFetcherDefault>(
context_->url_loader_factory(), oauth_token_getter_.get());
}
scoped_refptr<protocol::TransportContext> transport_context =
new protocol::TransportContext(
std::make_unique<protocol::ChromiumPortAllocatorFactory>(),
webrtc::ThreadWrapper::current()->SocketServer(),
std::move(ice_config_fetcher), protocol::TransportRole::SERVER);
std::unique_ptr<protocol::SessionManager> session_manager(
new protocol::JingleSessionManager(signal_strategy_.get()));
std::unique_ptr<protocol::CandidateSessionConfig> protocol_config =
protocol::CandidateSessionConfig::CreateDefault();
if (!desktop_environment_factory_->SupportsAudioCapture()) {
protocol_config->DisableAudioChannel();
}
protocol_config->set_webrtc_supported(true);
session_manager->set_protocol_config(std::move(protocol_config));
if (is_corp_host_) {
// Enabling this policy means that a local user sitting at a host would not
// see any UI or indication that a remote user was connected. We do have a
// few use cases for this internally where we know for a fact that there
// will not be a local user. Since that isn't something we can control
// externally, we don't want to apply this policy for non-Corp machines.
desktop_environment_options_.set_enable_user_interface(
enable_user_interface_);
corp_host_status_logger_ = CorpHostStatusLogger::CreateForRemoteAccess(
context_->url_loader_factory(), context_->CreateClientCertStore(),
&local_session_policies_provider_, service_account_email_,
oauth_refresh_token_);
corp_host_status_logger_->StartObserving(*session_manager);
}
desktop_environment_options_.set_enable_remote_webauthn(true);
#if BUILDFLAG(IS_WIN)
// Set a default value for whether to allow the dxgi capturer. This value can
// be explicitly disallowed by the client when session options are applied.
// The desktop process will check whether DXGI is supported in the session
// it is capturing before attempting to use it.
desktop_environment_options_.desktop_capture_options()
->set_allow_directx_capturer(true);
#endif
host_ = std::make_unique<ChromotingHost>(
desktop_environment_factory_.get(), std::move(session_manager),
transport_context, context_->audio_task_runner(),
context_->video_encode_task_runner(), desktop_environment_options_,
base::BindRepeating(&HostProcess::OnSessionPoliciesReceived,
base::Unretained(this)),
&local_session_policies_provider_);
if (security_key_auth_policy_enabled_ && security_key_extension_supported_) {
host_->AddExtension(
std::make_unique<SecurityKeyExtension>(context_->file_task_runner()));
}
host_->AddExtension(std::make_unique<TestEchoExtension>());
#if BUILDFLAG(IS_LINUX)
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch(kEnableWtmpdb)) {
host_wtmpdb_logger_ =
std::make_unique<HostWtmpdbLogger>(host_->status_monitor());
}
#endif
power_save_blocker_ = std::make_unique<HostPowerSaveBlocker>(
host_->status_monitor(), context_->ui_task_runner(),
context_->file_task_runner());
ftl_host_change_notification_listener_ =
std::make_unique<FtlHostChangeNotificationListener>(
this, signal_strategy_.get());
ftl_echo_message_listener_ = std::make_unique<FtlEchoMessageListener>(
base::BindRepeating(&HostProcess::CheckAccessPermission, this),
signal_strategy_.get());
// Set up reporting the host status notifications.
#if defined(REMOTING_MULTI_PROCESS)
mojo::AssociatedRemote<mojom::HostStatusObserver> remote;
daemon_channel_->GetRemoteAssociatedInterface(&remote);
host_event_logger_ = std::make_unique<IpcHostEventLogger>(
host_->status_monitor(), std::move(remote));
#else // !defined(REMOTING_MULTI_PROCESS)
host_event_logger_ =
HostEventLogger::Create(host_->status_monitor(), kApplicationName);
#endif // !defined(REMOTING_MULTI_PROCESS)
// The email provided here is only used for logging via OnHostStarted().
// TODO: joedow - Update host observer interface to handle multiple email
// addresses.
host_->Start(*host_owner_emails_.begin());
#if BUILDFLAG(IS_LINUX)
// For Windows and Mac, ChromotingHostServices connections are handled by
// another process, then the message pipe is forwarded to the network process.
host_->StartChromotingHostServices();
#endif
CreateAuthenticatorFactory();
ApplyHostDomainListPolicy();
ApplyAllowRemoteAccessConnections();
}
void HostProcess::OnAuthFailed() {
ShutdownHost(kInvalidOAuthCredentialsExitCode);
}
void HostProcess::OnZombieStateDetected() {
RestartHost(kHostOfflineReasonZombieStateDetected);
}
void HostProcess::RestartHost(const std::string& host_offline_reason) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!host_offline_reason.empty());
SetState(HOST_GOING_OFFLINE_TO_RESTART);
GoOffline(host_offline_reason);
}
void HostProcess::ShutdownHost(HostExitCodes exit_code) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
*exit_code_out_ = exit_code;
switch (state_) {
case HOST_SUSPENDED:
case HOST_STARTING:
case HOST_STARTED:
SetState(HOST_GOING_OFFLINE_TO_STOP);
GoOffline(ExitCodeToString(exit_code));
break;
case HOST_GOING_OFFLINE_TO_RESTART:
SetState(HOST_GOING_OFFLINE_TO_STOP);
break;
case HOST_GOING_OFFLINE_TO_STOP:
case HOST_STOPPED:
// Host is already stopped or being stopped. No action is required.
break;
}
}
void HostProcess::GoOffline(const std::string& host_offline_reason) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!host_offline_reason.empty());
DCHECK((state_ == HOST_GOING_OFFLINE_TO_STOP) ||
(state_ == HOST_GOING_OFFLINE_TO_RESTART) ||
(state_ == HOST_SUSPENDED));
// Shut down everything except the HostSignalingManager.
host_.reset();
host_event_logger_.reset();
power_save_blocker_.reset();
corp_host_status_logger_.reset();
ftl_host_change_notification_listener_.reset();
// Before shutting down HostSignalingManager, send the |host_offline_reason|
// if possible (i.e. if we have the config).
if (
// Host is deleted. There is no need to report the host offline reason
// back to directory.
host_offline_reason == ExitCodeToString(kHostDeletedExitCode) ||
// kTerminatedByAgentProcessBroker and kHostOfflineReasonSuspended imply
// that there is another host process heartbeating. Reporting the offline
// reason will make the host appear to be offline.
host_offline_reason ==
ExitCodeToString(kTerminatedByAgentProcessBroker) ||
host_offline_reason == kHostOfflineReasonSuspended) {
OnHostOfflineReasonAck(true);
return;
} else if (!config_.empty()) {
if (!signal_strategy_) {
InitializeSignaling();
}
HOST_LOG << "SendHostOfflineReason: sending " << host_offline_reason << ".";
heartbeat_sender_->SetHostOfflineReason(
host_offline_reason, base::Seconds(kHostOfflineReasonTimeoutSeconds),
base::BindOnce(&HostProcess::OnHostOfflineReasonAck, this));
return; // Shutdown will resume after OnHostOfflineReasonAck.
}
// Continue the shutdown without sending the host offline reason.
HOST_LOG << "Can't send offline reason (" << host_offline_reason << ") "
<< "without a valid host config.";
OnHostOfflineReasonAck(false);
}
void HostProcess::OnHostOfflineReasonAck(bool success) {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
DCHECK(!host_); // Assert that the host is really offline at this point.
HOST_LOG << "SendHostOfflineReason " << (success ? "succeeded." : "failed.");
heartbeat_sender_.reset();
oauth_token_getter_.reset();
instance_identity_token_getter_.reset();
ftl_signaling_connector_.reset();
ftl_echo_message_listener_.reset();
signal_strategy_.reset();
zombie_host_detector_.reset();
if (state_ == HOST_GOING_OFFLINE_TO_RESTART) {
SetState(HOST_STARTING);
StartHostIfReady();
} else if (state_ == HOST_GOING_OFFLINE_TO_STOP) {
SetState(HOST_STOPPED);
shutdown_watchdog_->SetExitCode(*exit_code_out_);
shutdown_watchdog_->Arm();
config_watcher_.reset();
#if BUILDFLAG(IS_MAC)
agent_process_broker_client_.reset();
#endif
// Complete the rest of shutdown on the main thread.
context_->ui_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&HostProcess::ShutdownOnUiThread, this));
} else if (state_ != HOST_SUSPENDED) {
NOTREACHED();
}
}
void HostProcess::CrashProcess(const std::string& function_name,
const std::string& file_name,
int line_number) {
// The daemon requested us to crash the process.
::remoting::CrashProcess(function_name, file_name, line_number);
}
int HostProcessMain() {
HOST_LOG << "Starting host process: version " << STRINGIZE(VERSION);
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if defined(REMOTING_USE_X11)
// Initialize Xlib for multi-threaded use, allowing non-Chromium code to
// use X11 safely (such as the WebRTC capturer, GTK ...)
x11::InitXlib();
#endif // defined(REMOTING_USE_X11)
#if defined(REMOTING_USE_X11)
if (!cmd_line->HasSwitch(kReportOfflineReasonSwitchName)) {
// Required for any calls into GTK functions, such as the Disconnect and
// Continue windows, though these should not be used for the Me2Me case
// (crbug.com/104377).
#if GTK_CHECK_VERSION(3, 90, 0)
gtk_init();
#else
gtk_init(nullptr, nullptr);
#endif
}
#endif // defined(REMOTING_USE_X11)
// Need to prime the host OS version value for linux to prevent IO on the
// network thread. base::GetLinuxDistro() caches the result.
base::GetLinuxDistro();
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
if (cmd_line->HasSwitch(kWebRtcTraceEventFile)) {
webrtc::tracing::SetupInternalTracer();
webrtc::tracing::StartInternalCapture(
cmd_line->GetSwitchValuePath(kWebRtcTraceEventFile)
.AsUTF8Unsafe()
.c_str());
}
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Me2Me");
// Create the main task executor and start helper threads.
base::SingleThreadTaskExecutor main_task_executor(base::MessagePumpType::UI);
base::RunLoop run_loop;
std::unique_ptr<ChromotingHostContext> context =
ChromotingHostContext::Create(base::MakeRefCounted<AutoThreadTaskRunner>(
main_task_executor.task_runner(), run_loop.QuitClosure()));
if (!context) {
return kInitializationFailed;
}
#if BUILDFLAG(IS_LINUX)
// Log and cleanup the crash database. We do this after a short delay so that
// the crash database has a chance to be updated properly if we just got
// relaunched after a crash.
// TODO(garykac): When Crashpad is enabled for the network process on Windows
// we will need to enable this code on Windows as well.
if (IsUsageStatsAllowed()) {
scoped_refptr<base::SequencedTaskRunner> task_runner_crashdb =
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT});
task_runner_crashdb->PostDelayedTask(
FROM_HERE, base::BindOnce(&LogAndCleanupCrashDatabase),
base::Seconds(3));
}
#endif // defined(REMOTING_ENABLE_CRASH_REPORTING)
// NetworkChangeNotifier must be initialized after SingleThreadTaskExecutor.
std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier(
net::NetworkChangeNotifier::CreateIfNeeded());
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(REMOTING_USE_X11)
// Create an X11EventSource on all UI threads, so the global X11 connection
// (x11::Connection::Get()) can dispatch X events.
auto event_source =
std::make_unique<ui::X11EventSource>(x11::Connection::Get());
context->input_task_runner()->PostTask(
FROM_HERE,
base::BindOnce([]() { new ui::X11EventSource(x11::Connection::Get()); }));
#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) &&
// defined(REMOTING_USE_X11)
// Create & start the HostProcess using these threads.
// TODO(wez): The HostProcess holds a reference to itself until Shutdown().
// Remove this hack as part of the multi-process refactoring.
int exit_code = kSuccessExitCode;
ShutdownWatchdog shutdown_watchdog(base::Seconds(kShutdownTimeoutSeconds));
new HostProcess(std::move(context), &exit_code, &shutdown_watchdog);
// Run the main (also UI) task executor until the host no longer needs it.
run_loop.Run();
// Block until tasks blocking shutdown have completed their execution.
base::ThreadPoolInstance::Get()->Shutdown();
if (cmd_line->HasSwitch(kWebRtcTraceEventFile)) {
webrtc::tracing::ShutdownInternalTracer();
}
return exit_code;
}
} // namespace remoting
|