network_service.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "services/network/network_service.h"
  5. #include <map>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/bind.h"
  9. #include "base/callback.h"
  10. #include "base/check.h"
  11. #include "base/check_op.h"
  12. #include "base/command_line.h"
  13. #include "base/cxx17_backports.h"
  14. #include "base/debug/crash_logging.h"
  15. #include "base/debug/dump_without_crashing.h"
  16. #include "base/environment.h"
  17. #include "base/feature_list.h"
  18. #include "base/files/file_util.h"
  19. #include "base/logging.h"
  20. #include "base/memory/ptr_util.h"
  21. #include "base/memory/raw_ptr.h"
  22. #include "base/metrics/histogram_functions.h"
  23. #include "base/metrics/histogram_macros.h"
  24. #include "base/task/thread_pool.h"
  25. #include "base/timer/timer.h"
  26. #include "base/values.h"
  27. #include "build/build_config.h"
  28. #include "build/chromecast_buildflags.h"
  29. #include "build/chromeos_buildflags.h"
  30. #include "components/network_session_configurator/common/network_features.h"
  31. #include "components/os_crypt/os_crypt.h"
  32. #include "mojo/public/cpp/bindings/scoped_message_error_crash_key.h"
  33. #include "mojo/public/cpp/system/functions.h"
  34. #include "net/base/features.h"
  35. #include "net/base/logging_network_change_observer.h"
  36. #include "net/base/network_change_notifier.h"
  37. #include "net/base/network_change_notifier_posix.h"
  38. #include "net/base/port_util.h"
  39. #include "net/cert/cert_database.h"
  40. #include "net/cert/ct_log_response_parser.h"
  41. #include "net/cert/internal/system_trust_store.h"
  42. #include "net/cert/signed_tree_head.h"
  43. #include "net/cookies/cookie_util.h"
  44. #include "net/dns/host_resolver.h"
  45. #include "net/dns/host_resolver_manager.h"
  46. #include "net/dns/public/dns_config_overrides.h"
  47. #include "net/dns/public/dns_over_https_config.h"
  48. #include "net/dns/public/doh_provider_entry.h"
  49. #include "net/dns/system_dns_config_change_notifier.h"
  50. #include "net/dns/test_dns_config_service.h"
  51. #include "net/http/http_auth_handler_factory.h"
  52. #include "net/log/file_net_log_observer.h"
  53. #include "net/log/net_log.h"
  54. #include "net/log/net_log_capture_mode.h"
  55. #include "net/log/net_log_util.h"
  56. #include "net/nqe/network_quality_estimator.h"
  57. #include "net/socket/client_socket_pool_manager.h"
  58. #include "net/ssl/ssl_key_logger_impl.h"
  59. #include "net/url_request/url_request_context.h"
  60. #include "services/network/crl_set_distributor.h"
  61. #include "services/network/dns_config_change_manager.h"
  62. #include "services/network/first_party_sets/first_party_sets_manager.h"
  63. #include "services/network/http_auth_cache_copier.h"
  64. #include "services/network/net_log_exporter.h"
  65. #include "services/network/net_log_proxy_sink.h"
  66. #include "services/network/network_context.h"
  67. #include "services/network/public/cpp/crash_keys.h"
  68. #include "services/network/public/cpp/features.h"
  69. #include "services/network/public/cpp/initiator_lock_compatibility.h"
  70. #include "services/network/public/cpp/load_info_util.h"
  71. #include "services/network/public/cpp/network_switches.h"
  72. #include "services/network/public/cpp/parsed_headers.h"
  73. #include "services/network/public/mojom/first_party_sets.mojom.h"
  74. #include "services/network/public/mojom/key_pinning.mojom.h"
  75. #include "services/network/public/mojom/network_service_test.mojom.h"
  76. #include "services/network/url_loader.h"
  77. #if BUILDFLAG(IS_ANDROID) && defined(ARCH_CPU_ARMEL)
  78. #include "crypto/openssl_util.h"
  79. #include "third_party/boringssl/src/include/openssl/cpu.h"
  80. #endif
  81. #if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
  82. BUILDFLAG(IS_CHROMEOS_LACROS)
  83. #include "components/os_crypt/key_storage_config_linux.h"
  84. #endif
  85. #if BUILDFLAG(IS_ANDROID)
  86. #include "base/android/application_status_listener.h"
  87. #include "net/android/http_auth_negotiate_android.h"
  88. #endif
  89. #if BUILDFLAG(IS_CT_SUPPORTED)
  90. #include "components/certificate_transparency/ct_features.h"
  91. #include "services/network/ct_log_list_distributor.h"
  92. #include "services/network/sct_auditing/sct_auditing_cache.h"
  93. #endif
  94. namespace net {
  95. class FirstPartySetEntry;
  96. }
  97. namespace network {
  98. namespace {
  99. NetworkService* g_network_service = nullptr;
  100. std::unique_ptr<net::NetworkChangeNotifier> CreateNetworkChangeNotifierIfNeeded(
  101. net::NetworkChangeNotifier::ConnectionType initial_connection_type,
  102. net::NetworkChangeNotifier::ConnectionSubtype initial_connection_subtype,
  103. bool mock_network_change_notifier) {
  104. // There is a global singleton net::NetworkChangeNotifier if NetworkService
  105. // is running inside of the browser process.
  106. if (mock_network_change_notifier)
  107. return net::NetworkChangeNotifier::CreateMockIfNeeded();
  108. return net::NetworkChangeNotifier::CreateIfNeeded(initial_connection_type,
  109. initial_connection_subtype);
  110. }
  111. void OnGetNetworkList(std::unique_ptr<net::NetworkInterfaceList> networks,
  112. mojom::NetworkService::GetNetworkListCallback callback,
  113. bool success) {
  114. if (success) {
  115. std::move(callback).Run(*networks);
  116. } else {
  117. std::move(callback).Run(absl::nullopt);
  118. }
  119. }
  120. #if BUILDFLAG(IS_ANDROID) && BUILDFLAG(USE_KERBEROS)
  121. // Used for Negotiate authentication on Android, which needs to generate tokens
  122. // in the browser process.
  123. class NetworkServiceAuthNegotiateAndroid : public net::HttpAuthMechanism {
  124. public:
  125. NetworkServiceAuthNegotiateAndroid(NetworkContext* network_context,
  126. const net::HttpAuthPreferences* prefs)
  127. : network_context_(network_context), auth_negotiate_(prefs) {}
  128. ~NetworkServiceAuthNegotiateAndroid() override = default;
  129. // HttpAuthMechanism implementation:
  130. bool Init(const net::NetLogWithSource& net_log) override {
  131. return auth_negotiate_.Init(net_log);
  132. }
  133. bool NeedsIdentity() const override {
  134. return auth_negotiate_.NeedsIdentity();
  135. }
  136. bool AllowsExplicitCredentials() const override {
  137. return auth_negotiate_.AllowsExplicitCredentials();
  138. }
  139. net::HttpAuth::AuthorizationResult ParseChallenge(
  140. net::HttpAuthChallengeTokenizer* tok) override {
  141. return auth_negotiate_.ParseChallenge(tok);
  142. }
  143. int GenerateAuthToken(const net::AuthCredentials* credentials,
  144. const std::string& spn,
  145. const std::string& channel_bindings,
  146. std::string* auth_token,
  147. const net::NetLogWithSource& net_log,
  148. net::CompletionOnceCallback callback) override {
  149. network_context_->client()->OnGenerateHttpNegotiateAuthToken(
  150. auth_negotiate_.server_auth_token(), auth_negotiate_.can_delegate(),
  151. auth_negotiate_.GetAuthAndroidNegotiateAccountType(), spn,
  152. base::BindOnce(&NetworkServiceAuthNegotiateAndroid::Finish,
  153. weak_factory_.GetWeakPtr(), auth_token,
  154. std::move(callback)));
  155. return net::ERR_IO_PENDING;
  156. }
  157. void SetDelegation(net::HttpAuth::DelegationType delegation_type) override {
  158. auth_negotiate_.SetDelegation(delegation_type);
  159. }
  160. private:
  161. void Finish(std::string* auth_token_out,
  162. net::CompletionOnceCallback callback,
  163. int result,
  164. const std::string& auth_token) {
  165. *auth_token_out = auth_token;
  166. std::move(callback).Run(result);
  167. }
  168. raw_ptr<NetworkContext> network_context_ = nullptr;
  169. net::android::HttpAuthNegotiateAndroid auth_negotiate_;
  170. base::WeakPtrFactory<NetworkServiceAuthNegotiateAndroid> weak_factory_{this};
  171. };
  172. std::unique_ptr<net::HttpAuthMechanism> CreateAuthSystem(
  173. NetworkContext* network_context,
  174. const net::HttpAuthPreferences* prefs) {
  175. return std::make_unique<NetworkServiceAuthNegotiateAndroid>(network_context,
  176. prefs);
  177. }
  178. #endif
  179. // Called when NetworkService received a bad IPC message (but only when
  180. // NetworkService is running in a separate process - otherwise the existing bad
  181. // message handling inside the Browser process is sufficient).
  182. void HandleBadMessage(const std::string& error) {
  183. LOG(WARNING) << "Mojo error in NetworkService: " << error;
  184. mojo::debug::ScopedMessageErrorCrashKey crash_key_value(error);
  185. base::debug::DumpWithoutCrashing();
  186. network::debug::ClearDeserializationCrashKeyString();
  187. }
  188. } // namespace
  189. // static
  190. const base::TimeDelta NetworkService::kInitialDohProbeTimeout =
  191. base::Seconds(5);
  192. // Handler of delaying calls to NetworkContext::ActivateDohProbes() until after
  193. // an initial service startup delay.
  194. class NetworkService::DelayedDohProbeActivator {
  195. public:
  196. explicit DelayedDohProbeActivator(NetworkService* network_service)
  197. : network_service_(network_service) {
  198. DCHECK(network_service_);
  199. // Delay initial DoH probes to prevent interference with startup tasks.
  200. doh_probes_timer_.Start(
  201. FROM_HERE, NetworkService::kInitialDohProbeTimeout,
  202. base::BindOnce(&DelayedDohProbeActivator::ActivateAllDohProbes,
  203. base::Unretained(this)));
  204. }
  205. DelayedDohProbeActivator(const DelayedDohProbeActivator&) = delete;
  206. DelayedDohProbeActivator& operator=(const DelayedDohProbeActivator&) = delete;
  207. // Activates DoH probes for |network_context| iff the initial startup delay
  208. // has expired. Intended to be called on registration of contexts to activate
  209. // probes for contexts created and registered after the initial delay has
  210. // expired.
  211. void MaybeActivateDohProbes(NetworkContext* network_context) {
  212. // If timer is still running, probes will be started on completion.
  213. if (doh_probes_timer_.IsRunning())
  214. return;
  215. network_context->ActivateDohProbes();
  216. }
  217. // Attempts to activate DoH probes for all contexts registered with the
  218. // service. Intended to be called on expiration of |doh_probes_timer_| to
  219. // activate probes for contexts registered during the initial delay.
  220. void ActivateAllDohProbes() {
  221. for (auto* network_context : network_service_->network_contexts_) {
  222. MaybeActivateDohProbes(network_context);
  223. }
  224. }
  225. private:
  226. const raw_ptr<NetworkService> network_service_;
  227. // If running, DoH probes will be started on completion. If not running, DoH
  228. // probes may be started at any time.
  229. base::OneShotTimer doh_probes_timer_;
  230. };
  231. NetworkService::NetworkService(
  232. std::unique_ptr<service_manager::BinderRegistry> registry,
  233. mojo::PendingReceiver<mojom::NetworkService> receiver,
  234. bool delay_initialization_until_set_client)
  235. : net_log_(net::NetLog::Get()), registry_(std::move(registry)) {
  236. DCHECK(!g_network_service);
  237. g_network_service = this;
  238. // |registry_| is nullptr when an in-process NetworkService is
  239. // created directly, like in most unit tests.
  240. if (registry_)
  241. mojo::SetDefaultProcessErrorHandler(base::BindRepeating(&HandleBadMessage));
  242. if (receiver.is_valid())
  243. Bind(std::move(receiver));
  244. if (!delay_initialization_until_set_client)
  245. Initialize(mojom::NetworkServiceParams::New());
  246. }
  247. void NetworkService::Initialize(mojom::NetworkServiceParamsPtr params,
  248. bool mock_network_change_notifier) {
  249. if (initialized_)
  250. return;
  251. initialized_ = true;
  252. #if BUILDFLAG(IS_ANDROID) && defined(ARCH_CPU_ARMEL)
  253. // Make sure OpenSSL is initialized before using it to histogram data.
  254. crypto::EnsureOpenSSLInit();
  255. // Measure CPUs with broken NEON units. See https://crbug.com/341598.
  256. UMA_HISTOGRAM_BOOLEAN("Net.HasBrokenNEON", CRYPTO_has_broken_NEON());
  257. // Measure Android kernels with missing AT_HWCAP2 auxv fields. See
  258. // https://crbug.com/boringssl/46.
  259. UMA_HISTOGRAM_BOOLEAN("Net.NeedsHWCAP2Workaround",
  260. CRYPTO_needs_hwcap2_workaround());
  261. #endif
  262. if (!params->environment.empty())
  263. SetEnvironment(std::move(params->environment));
  264. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  265. // Record this once per session, though the switch is appled on a
  266. // per-NetworkContext basis.
  267. UMA_HISTOGRAM_BOOLEAN(
  268. "Net.Certificate.IgnoreCertificateErrorsSPKIListPresent",
  269. command_line->HasSwitch(switches::kIgnoreCertificateErrorsSPKIList));
  270. network_change_manager_ = std::make_unique<NetworkChangeManager>(
  271. CreateNetworkChangeNotifierIfNeeded(
  272. net::NetworkChangeNotifier::ConnectionType(
  273. params->initial_connection_type),
  274. net::NetworkChangeNotifier::ConnectionSubtype(
  275. params->initial_connection_subtype),
  276. mock_network_change_notifier));
  277. trace_net_log_observer_.WatchForTraceStart(net_log_);
  278. // Add an observer that will emit network change events to |net_log_|.
  279. // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
  280. // logging the network change before other IO thread consumers respond to it.
  281. network_change_observer_ =
  282. std::make_unique<net::LoggingNetworkChangeObserver>(net_log_);
  283. network_quality_estimator_manager_ =
  284. std::make_unique<NetworkQualityEstimatorManager>(net_log_);
  285. dns_config_change_manager_ = std::make_unique<DnsConfigChangeManager>();
  286. host_resolver_manager_ = std::make_unique<net::HostResolverManager>(
  287. net::HostResolver::ManagerOptions(),
  288. net::NetworkChangeNotifier::GetSystemDnsConfigNotifier(), net_log_);
  289. host_resolver_factory_ = std::make_unique<net::HostResolver::Factory>();
  290. http_auth_cache_copier_ = std::make_unique<HttpAuthCacheCopier>();
  291. crl_set_distributor_ = std::make_unique<CRLSetDistributor>();
  292. #if BUILDFLAG(IS_CT_SUPPORTED)
  293. ct_log_list_distributor_ = std::make_unique<CtLogListDistributor>();
  294. #endif
  295. doh_probe_activator_ = std::make_unique<DelayedDohProbeActivator>(this);
  296. trust_token_key_commitments_ = std::make_unique<TrustTokenKeyCommitments>();
  297. if (params->default_observer) {
  298. default_url_loader_network_service_observer_.Bind(
  299. std::move(params->default_observer));
  300. }
  301. first_party_sets_manager_ =
  302. std::make_unique<FirstPartySetsManager>(params->first_party_sets_enabled);
  303. #if BUILDFLAG(IS_CT_SUPPORTED)
  304. constexpr size_t kMaxSCTAuditingCacheEntries = 1024;
  305. sct_auditing_cache_ =
  306. std::make_unique<SCTAuditingCache>(kMaxSCTAuditingCacheEntries);
  307. #endif
  308. }
  309. NetworkService::~NetworkService() {
  310. DCHECK_EQ(this, g_network_service);
  311. doh_probe_activator_.reset();
  312. g_network_service = nullptr;
  313. // Destroy owned network contexts.
  314. DestroyNetworkContexts();
  315. // All NetworkContexts (Owned and unowned) must have been deleted by this
  316. // point.
  317. DCHECK(network_contexts_.empty());
  318. if (file_net_log_observer_) {
  319. file_net_log_observer_->StopObserving(nullptr /*polled_data*/,
  320. base::OnceClosure());
  321. }
  322. if (initialized_)
  323. trace_net_log_observer_.StopWatchForTraceStart();
  324. }
  325. void NetworkService::ReplaceSystemDnsConfigForTesting() {
  326. // Create a test `net::DnsConfigService` that will yield a dummy config once.
  327. auto config_service = std::make_unique<net::TestDnsConfigService>();
  328. config_service->SetConfigForRefresh(
  329. net::DnsConfig({net::IPEndPoint(net::IPAddress::IPv4Localhost(), 1234)}));
  330. // Replace the existing `net::DnsConfigService` and flush the lines once to
  331. // replace the system DNS config, in case we already received it.
  332. auto* notifier = net::NetworkChangeNotifier::GetSystemDnsConfigNotifier();
  333. DCHECK(notifier);
  334. notifier->SetDnsConfigServiceForTesting( // IN-TEST
  335. std::move(config_service));
  336. notifier->RefreshConfig();
  337. // Force-disable the system resolver so that HostResolverManager will actually
  338. // use the replacement config.
  339. host_resolver_manager_->DisableSystemResolverForTesting(); // IN-TEST
  340. }
  341. void NetworkService::SetTestDohConfigForTesting(
  342. net::SecureDnsMode secure_dns_mode,
  343. const net::DnsOverHttpsConfig& doh_config) {
  344. DCHECK_EQ(dns_config_overrides_set_by_, FunctionTag::None);
  345. dns_config_overrides_set_by_ = FunctionTag::SetTestDohConfigForTesting;
  346. // Overlay DoH settings on top of the system config, whenever it is received.
  347. net::DnsConfigOverrides overrides;
  348. overrides.secure_dns_mode = secure_dns_mode;
  349. overrides.dns_over_https_config = doh_config;
  350. host_resolver_manager_->SetDnsConfigOverrides(std::move(overrides));
  351. // Force-disable the system resolver so that HostResolverManager will actually
  352. // query the test DoH server.
  353. host_resolver_manager_->DisableSystemResolverForTesting(); // IN-TEST
  354. }
  355. std::unique_ptr<NetworkService> NetworkService::Create(
  356. mojo::PendingReceiver<mojom::NetworkService> receiver) {
  357. return std::make_unique<NetworkService>(nullptr, std::move(receiver));
  358. }
  359. // static
  360. std::unique_ptr<NetworkService> NetworkService::CreateForTesting() {
  361. auto network_service = std::make_unique<NetworkService>(
  362. std::make_unique<service_manager::BinderRegistry>());
  363. network_service->InitMockNetworkChangeNotifierForTesting(); // IN-TEST
  364. return network_service;
  365. }
  366. void NetworkService::RegisterNetworkContext(NetworkContext* network_context) {
  367. DCHECK_EQ(0u, network_contexts_.count(network_context));
  368. network_contexts_.insert(network_context);
  369. if (quic_disabled_)
  370. network_context->DisableQuic();
  371. // The params may already be present, so we propagate it
  372. // to this new network_context. When params gets changed
  373. // via ConfigureHttpAuthPrefs method, we propagate the change
  374. // to all NetworkContexts in |network_contexts_|
  375. if (http_auth_dynamic_network_service_params_) {
  376. network_context->OnHttpAuthDynamicParamsChanged(
  377. http_auth_dynamic_network_service_params_.get());
  378. }
  379. if (doh_probe_activator_)
  380. doh_probe_activator_->MaybeActivateDohProbes(network_context);
  381. #if BUILDFLAG(IS_CT_SUPPORTED)
  382. network_context->url_request_context()
  383. ->transport_security_state()
  384. ->SetCTEmergencyDisabled(!ct_enforcement_enabled_);
  385. #endif // BUILDFLAG(IS_CT_SUPPORTED)
  386. }
  387. void NetworkService::DeregisterNetworkContext(NetworkContext* network_context) {
  388. DCHECK_EQ(1u, network_contexts_.count(network_context));
  389. network_contexts_.erase(network_context);
  390. }
  391. #if BUILDFLAG(IS_CHROMEOS_ASH)
  392. void NetworkService::ReinitializeLogging(mojom::LoggingSettingsPtr settings) {
  393. logging::LoggingSettings logging_settings;
  394. logging_settings.logging_dest = settings->logging_dest;
  395. base::ScopedFD log_file_descriptor = settings->log_file_descriptor.TakeFD();
  396. logging_settings.log_file = fdopen(log_file_descriptor.release(), "a");
  397. if (!logging_settings.log_file) {
  398. LOG(ERROR) << "Failed to open new log file handle";
  399. return;
  400. }
  401. if (!logging::InitLogging(logging_settings))
  402. LOG(ERROR) << "Unable to reinitialize logging";
  403. }
  404. #endif
  405. void NetworkService::CreateNetLogEntriesForActiveObjects(
  406. net::NetLog::ThreadSafeObserver* observer) {
  407. std::set<net::URLRequestContext*> contexts;
  408. for (NetworkContext* nc : network_contexts_)
  409. contexts.insert(nc->url_request_context());
  410. return net::CreateNetLogEntriesForActiveObjects(contexts, observer);
  411. }
  412. void NetworkService::SetParams(mojom::NetworkServiceParamsPtr params) {
  413. Initialize(std::move(params));
  414. }
  415. void NetworkService::StartNetLog(base::File file,
  416. net::NetLogCaptureMode capture_mode,
  417. base::Value::Dict client_constants) {
  418. base::Value::Dict constants = net::GetNetConstants();
  419. constants.Merge(std::move(client_constants));
  420. file_net_log_observer_ = net::FileNetLogObserver::CreateUnboundedPreExisting(
  421. std::move(file), capture_mode,
  422. std::make_unique<base::Value>(std::move(constants)));
  423. file_net_log_observer_->StartObserving(net_log_);
  424. }
  425. void NetworkService::AttachNetLogProxy(
  426. mojo::PendingRemote<mojom::NetLogProxySource> proxy_source,
  427. mojo::PendingReceiver<mojom::NetLogProxySink> proxy_sink) {
  428. if (!net_log_proxy_sink_)
  429. net_log_proxy_sink_ = std::make_unique<NetLogProxySink>();
  430. net_log_proxy_sink_->AttachSource(std::move(proxy_source),
  431. std::move(proxy_sink));
  432. }
  433. void NetworkService::SetSSLKeyLogFile(base::File file) {
  434. net::SSLClientSocket::SetSSLKeyLogger(
  435. std::make_unique<net::SSLKeyLoggerImpl>(std::move(file)));
  436. }
  437. void NetworkService::CreateNetworkContext(
  438. mojo::PendingReceiver<mojom::NetworkContext> receiver,
  439. mojom::NetworkContextParamsPtr params) {
  440. owned_network_contexts_.emplace(std::make_unique<NetworkContext>(
  441. this, std::move(receiver), std::move(params),
  442. base::BindOnce(&NetworkService::OnNetworkContextConnectionClosed,
  443. base::Unretained(this))));
  444. }
  445. void NetworkService::ConfigureStubHostResolver(
  446. bool insecure_dns_client_enabled,
  447. net::SecureDnsMode secure_dns_mode,
  448. const net::DnsOverHttpsConfig& dns_over_https_config,
  449. bool additional_dns_types_enabled) {
  450. // Enable or disable the insecure part of DnsClient. "DnsClient" is the class
  451. // that implements the stub resolver.
  452. host_resolver_manager_->SetInsecureDnsClientEnabled(
  453. insecure_dns_client_enabled, additional_dns_types_enabled);
  454. // Configure DNS over HTTPS.
  455. DCHECK(dns_config_overrides_set_by_ == FunctionTag::None ||
  456. dns_config_overrides_set_by_ ==
  457. FunctionTag::ConfigureStubHostResolver);
  458. dns_config_overrides_set_by_ = FunctionTag::ConfigureStubHostResolver;
  459. net::DnsConfigOverrides overrides;
  460. overrides.dns_over_https_config = dns_over_https_config;
  461. overrides.secure_dns_mode = secure_dns_mode;
  462. overrides.allow_dns_over_https_upgrade =
  463. base::FeatureList::IsEnabled(features::kDnsOverHttpsUpgrade);
  464. host_resolver_manager_->SetDnsConfigOverrides(overrides);
  465. }
  466. void NetworkService::DisableQuic() {
  467. quic_disabled_ = true;
  468. for (auto* network_context : network_contexts_) {
  469. network_context->DisableQuic();
  470. }
  471. }
  472. void NetworkService::SetUpHttpAuth(
  473. mojom::HttpAuthStaticParamsPtr http_auth_static_params) {
  474. DCHECK(!http_auth_static_network_service_params_);
  475. DCHECK(network_contexts_.empty());
  476. http_auth_static_network_service_params_ = std::move(http_auth_static_params);
  477. }
  478. void NetworkService::ConfigureHttpAuthPrefs(
  479. mojom::HttpAuthDynamicParamsPtr http_auth_dynamic_params) {
  480. // We need to store it as a member variable because the method
  481. // NetworkService::RegisterNetworkContext(NetworkContext *network_context)
  482. // uses it to populate the HttpAuthPreferences of the incoming network_context
  483. // with the latest dynamic params of the NetworkService.
  484. http_auth_dynamic_network_service_params_ =
  485. std::move(http_auth_dynamic_params);
  486. for (NetworkContext* network_context : network_contexts_) {
  487. network_context->OnHttpAuthDynamicParamsChanged(
  488. http_auth_dynamic_network_service_params_.get());
  489. }
  490. }
  491. void NetworkService::SetRawHeadersAccess(
  492. int32_t process_id,
  493. const std::vector<url::Origin>& origins) {
  494. DCHECK(process_id);
  495. if (!origins.size()) {
  496. raw_headers_access_origins_by_pid_.erase(process_id);
  497. } else {
  498. raw_headers_access_origins_by_pid_[process_id] =
  499. base::flat_set<url::Origin>(origins.begin(), origins.end());
  500. }
  501. }
  502. void NetworkService::SetMaxConnectionsPerProxy(int32_t max_connections) {
  503. int new_limit = max_connections;
  504. if (new_limit < 0)
  505. new_limit = net::kDefaultMaxSocketsPerProxyServer;
  506. // Clamp the value between min_limit and max_limit.
  507. int max_limit = 99;
  508. int min_limit = net::ClientSocketPoolManager::max_sockets_per_group(
  509. net::HttpNetworkSession::NORMAL_SOCKET_POOL);
  510. new_limit = base::clamp(new_limit, min_limit, max_limit);
  511. // Assign the global limit.
  512. net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
  513. net::HttpNetworkSession::NORMAL_SOCKET_POOL, new_limit);
  514. }
  515. bool NetworkService::HasRawHeadersAccess(int32_t process_id,
  516. const GURL& resource_url) const {
  517. // Allow raw headers for browser-initiated requests.
  518. if (!process_id)
  519. return true;
  520. auto it = raw_headers_access_origins_by_pid_.find(process_id);
  521. if (it == raw_headers_access_origins_by_pid_.end())
  522. return false;
  523. return it->second.find(url::Origin::Create(resource_url)) != it->second.end();
  524. }
  525. net::NetLog* NetworkService::net_log() const {
  526. return net_log_;
  527. }
  528. void NetworkService::GetNetworkChangeManager(
  529. mojo::PendingReceiver<mojom::NetworkChangeManager> receiver) {
  530. network_change_manager_->AddReceiver(std::move(receiver));
  531. }
  532. void NetworkService::GetNetworkQualityEstimatorManager(
  533. mojo::PendingReceiver<mojom::NetworkQualityEstimatorManager> receiver) {
  534. network_quality_estimator_manager_->AddReceiver(std::move(receiver));
  535. }
  536. void NetworkService::GetDnsConfigChangeManager(
  537. mojo::PendingReceiver<mojom::DnsConfigChangeManager> receiver) {
  538. dns_config_change_manager_->AddReceiver(std::move(receiver));
  539. }
  540. void NetworkService::GetNetworkList(
  541. uint32_t policy,
  542. mojom::NetworkService::GetNetworkListCallback callback) {
  543. auto networks = std::make_unique<net::NetworkInterfaceList>();
  544. auto* raw_networks = networks.get();
  545. // net::GetNetworkList may block depending on platform.
  546. base::ThreadPool::PostTaskAndReplyWithResult(
  547. FROM_HERE, {base::MayBlock()},
  548. base::BindOnce(&net::GetNetworkList, raw_networks, policy),
  549. base::BindOnce(&OnGetNetworkList, std::move(networks),
  550. std::move(callback)));
  551. }
  552. void NetworkService::UpdateCRLSet(
  553. base::span<const uint8_t> crl_set,
  554. mojom::NetworkService::UpdateCRLSetCallback callback) {
  555. crl_set_distributor_->OnNewCRLSet(crl_set, std::move(callback));
  556. }
  557. void NetworkService::OnCertDBChanged() {
  558. net::CertDatabase::GetInstance()->NotifyObserversCertDBChanged();
  559. }
  560. void NetworkService::SetEncryptionKey(const std::string& encryption_key) {
  561. OSCrypt::SetRawEncryptionKey(encryption_key);
  562. }
  563. void NetworkService::OnMemoryPressure(
  564. base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
  565. base::MemoryPressureListener::NotifyMemoryPressure(memory_pressure_level);
  566. }
  567. void NetworkService::OnPeerToPeerConnectionsCountChange(uint32_t count) {
  568. network_quality_estimator_manager_->GetNetworkQualityEstimator()
  569. ->OnPeerToPeerConnectionsCountChange(count);
  570. }
  571. #if BUILDFLAG(IS_ANDROID)
  572. void NetworkService::OnApplicationStateChange(
  573. base::android::ApplicationState state) {
  574. for (auto* network_context : network_contexts_)
  575. network_context->app_status_listener()->Notify(state);
  576. }
  577. #endif
  578. void NetworkService::SetEnvironment(
  579. std::vector<mojom::EnvironmentVariablePtr> environment) {
  580. std::unique_ptr<base::Environment> env(base::Environment::Create());
  581. for (const auto& variable : environment)
  582. env->SetVar(variable->name, variable->value);
  583. }
  584. void NetworkService::SetTrustTokenKeyCommitments(
  585. const std::string& raw_commitments,
  586. base::OnceClosure done) {
  587. trust_token_key_commitments_->ParseAndSet(raw_commitments);
  588. std::move(done).Run();
  589. }
  590. void NetworkService::ParseHeaders(
  591. const GURL& url,
  592. const scoped_refptr<net::HttpResponseHeaders>& headers,
  593. ParseHeadersCallback callback) {
  594. std::move(callback).Run(PopulateParsedHeaders(headers.get(), url));
  595. }
  596. #if BUILDFLAG(IS_CT_SUPPORTED)
  597. void NetworkService::ClearSCTAuditingCache() {
  598. sct_auditing_cache_->ClearCache();
  599. }
  600. void NetworkService::ConfigureSCTAuditing(
  601. mojom::SCTAuditingConfigurationPtr configuration) {
  602. sct_auditing_cache_->Configure(std::move(configuration));
  603. }
  604. void NetworkService::UpdateCtLogList(std::vector<mojom::CTLogInfoPtr> log_list,
  605. base::Time update_time,
  606. UpdateCtLogListCallback callback) {
  607. log_list_ = std::move(log_list);
  608. ct_log_list_update_time_ = update_time;
  609. if (base::FeatureList::IsEnabled(
  610. certificate_transparency::features::
  611. kCertificateTransparencyComponentUpdater)) {
  612. ct_log_list_distributor_->OnNewCtConfig(log_list_);
  613. for (auto* context : network_contexts_) {
  614. context->OnCTLogListUpdated(log_list_, update_time);
  615. context->url_request_context()
  616. ->transport_security_state()
  617. ->SetCTLogListUpdateTime(update_time);
  618. }
  619. }
  620. std::move(callback).Run();
  621. }
  622. void NetworkService::UpdateCtKnownPopularSCTs(
  623. const std::vector<std::vector<uint8_t>>& sct_hashes,
  624. UpdateCtLogListCallback callback) {
  625. sct_auditing_cache_->set_popular_scts(std::move(sct_hashes));
  626. std::move(callback).Run();
  627. }
  628. void NetworkService::SetCtEnforcementEnabled(
  629. bool enabled,
  630. SetCtEnforcementEnabledCallback callback) {
  631. ct_enforcement_enabled_ = enabled;
  632. DCHECK(base::FeatureList::IsEnabled(
  633. certificate_transparency::features::
  634. kCertificateTransparencyComponentUpdater));
  635. for (auto* context : network_contexts_) {
  636. context->url_request_context()
  637. ->transport_security_state()
  638. ->SetCTEmergencyDisabled(!ct_enforcement_enabled_);
  639. }
  640. std::move(callback).Run();
  641. }
  642. #endif // BUILDFLAG(IS_CT_SUPPORTED)
  643. void NetworkService::UpdateKeyPinsList(mojom::PinListPtr pin_list,
  644. base::Time update_time) {
  645. pins_list_updated_ = true;
  646. pinsets_.clear();
  647. host_pins_.clear();
  648. pins_list_update_time_ = update_time;
  649. for (const auto& pinset : pin_list->pinsets) {
  650. pinsets_.emplace_back(pinset->name, pinset->static_spki_hashes,
  651. pinset->bad_static_spki_hashes, pinset->report_uri);
  652. }
  653. for (const auto& info : pin_list->host_pins) {
  654. host_pins_.emplace_back(info->hostname, info->pinset_name,
  655. info->include_subdomains);
  656. }
  657. for (NetworkContext* context : network_contexts_) {
  658. net::TransportSecurityState* state =
  659. context->url_request_context()->transport_security_state();
  660. if (state) {
  661. state->UpdatePinList(pinsets_, host_pins_, pins_list_update_time_);
  662. }
  663. }
  664. }
  665. #if BUILDFLAG(IS_ANDROID)
  666. void NetworkService::DumpWithoutCrashing(base::Time dump_request_time) {
  667. static base::debug::CrashKeyString* time_key =
  668. base::debug::AllocateCrashKeyString("time_since_dump_request_ms",
  669. base::debug::CrashKeySize::Size32);
  670. base::debug::ScopedCrashKeyString scoped_time(
  671. time_key, base::NumberToString(
  672. (base::Time::Now() - dump_request_time).InMilliseconds()));
  673. base::debug::DumpWithoutCrashing();
  674. }
  675. #endif
  676. void NetworkService::BindTestInterface(
  677. mojo::PendingReceiver<mojom::NetworkServiceTest> receiver) {
  678. if (registry_) {
  679. auto pipe = receiver.PassPipe();
  680. registry_->TryBindInterface(mojom::NetworkServiceTest::Name_, &pipe);
  681. }
  682. }
  683. void NetworkService::SetFirstPartySets(mojom::PublicFirstPartySetsPtr sets) {
  684. first_party_sets_manager_->SetCompleteSets(std::move(sets));
  685. }
  686. void NetworkService::SetExplicitlyAllowedPorts(
  687. const std::vector<uint16_t>& ports) {
  688. net::SetExplicitlyAllowedPorts(ports);
  689. }
  690. std::unique_ptr<net::HttpAuthHandlerFactory>
  691. NetworkService::CreateHttpAuthHandlerFactory(NetworkContext* network_context) {
  692. if (!http_auth_static_network_service_params_) {
  693. return net::HttpAuthHandlerFactory::CreateDefault(
  694. network_context->GetHttpAuthPreferences()
  695. #if BUILDFLAG(IS_ANDROID) && BUILDFLAG(USE_KERBEROS)
  696. ,
  697. base::BindRepeating(&CreateAuthSystem, network_context)
  698. #endif
  699. );
  700. }
  701. return net::HttpAuthHandlerRegistryFactory::Create(
  702. network_context->GetHttpAuthPreferences()
  703. #if BUILDFLAG(USE_EXTERNAL_GSSAPI)
  704. ,
  705. http_auth_static_network_service_params_->gssapi_library_name
  706. #endif
  707. #if BUILDFLAG(IS_ANDROID) && BUILDFLAG(USE_KERBEROS)
  708. ,
  709. base::BindRepeating(&CreateAuthSystem, network_context)
  710. #endif
  711. );
  712. }
  713. void NetworkService::InitMockNetworkChangeNotifierForTesting() {
  714. mock_network_change_notifier_ =
  715. net::NetworkChangeNotifier::CreateMockIfNeeded();
  716. }
  717. void NetworkService::DestroyNetworkContexts() {
  718. owned_network_contexts_.clear();
  719. }
  720. void NetworkService::OnNetworkContextConnectionClosed(
  721. NetworkContext* network_context) {
  722. auto it = owned_network_contexts_.find(network_context);
  723. DCHECK(it != owned_network_contexts_.end());
  724. owned_network_contexts_.erase(it);
  725. }
  726. void NetworkService::Bind(
  727. mojo::PendingReceiver<mojom::NetworkService> receiver) {
  728. DCHECK(!receiver_.is_bound());
  729. receiver_.Bind(std::move(receiver));
  730. }
  731. mojom::URLLoaderNetworkServiceObserver*
  732. NetworkService::GetDefaultURLLoaderNetworkServiceObserver() {
  733. if (default_url_loader_network_service_observer_)
  734. return default_url_loader_network_service_observer_.get();
  735. return nullptr;
  736. }
  737. // static
  738. NetworkService* NetworkService::GetNetworkServiceForTesting() {
  739. return g_network_service;
  740. }
  741. } // namespace network