File: bruschetta_network_context.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (298 lines) | stat: -rw-r--r-- 11,906 bytes parent folder | download | duplicates (3)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/bruschetta/bruschetta_network_context.h"

#include <stdint.h>

#include <memory>
#include <optional>
#include <vector>

#include "base/functional/bind.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/unguessable_token.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/util/managed_browser_utils.h"
#include "chrome/browser/extensions/cws_info_service.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/proxy_config_monitor.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/auth.h"
#include "net/base/net_errors.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/ssl/client_cert_store.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_private_key.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/shared_storage.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/public/mojom/url_loader_network_service_observer.mojom.h"
#include "url/gurl.h"

namespace bruschetta {

// Wraps a net::SSLPrivateKey and turns it into a network::mojom::SSLPrivateKey.
class SSLPrivateKeyBridge : public network::mojom::SSLPrivateKey {
 public:
  explicit SSLPrivateKeyBridge(
      scoped_refptr<net::SSLPrivateKey> ssl_private_key)
      : ssl_private_key_(std::move(ssl_private_key)) {}

  SSLPrivateKeyBridge(const SSLPrivateKeyBridge&) = delete;
  SSLPrivateKeyBridge& operator=(const SSLPrivateKeyBridge&) = delete;

  ~SSLPrivateKeyBridge() override = default;

  // network::mojom::SSLPrivateKey:
  void Sign(uint16_t algorithm,
            const std::vector<uint8_t>& input,
            network::mojom::SSLPrivateKey::SignCallback callback) override {
    base::span<const uint8_t> input_span(input);
    ssl_private_key_->Sign(
        algorithm, input_span,
        base::BindOnce(&SSLPrivateKeyBridge::Callback,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

 private:
  void Callback(network::mojom::SSLPrivateKey::SignCallback callback,
                net::Error net_error,
                const std::vector<uint8_t>& signature) {
    std::move(callback).Run(static_cast<int32_t>(net_error), signature);
  }

  scoped_refptr<net::SSLPrivateKey> ssl_private_key_;
  base::WeakPtrFactory<SSLPrivateKeyBridge> weak_ptr_factory_{this};
};

BruschettaNetworkContext::BruschettaNetworkContext(Profile* profile,
                                                   PrefService& local_state)
    : profile_(profile), proxy_config_monitor_(&local_state) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

BruschettaNetworkContext::~BruschettaNetworkContext() = default;

network::mojom::URLLoaderFactory*
BruschettaNetworkContext::GetURLLoaderFactory() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!url_loader_factory_ || !url_loader_factory_.is_connected()) {
    EnsureNetworkContextExists();

    url_loader_observers_.Clear();
    network::mojom::URLLoaderFactoryParamsPtr url_loader_factory_params =
        network::mojom::URLLoaderFactoryParams::New();
    url_loader_factory_params->process_id = network::mojom::kBrowserProcessId;
    url_loader_factory_params->is_orb_enabled = false;
    url_loader_factory_params->is_trusted = true;
    url_loader_observers_.Add(
        this, url_loader_factory_params->url_loader_network_observer
                  .InitWithNewPipeAndPassReceiver());
    url_loader_factory_.reset();
    network_context_->CreateURLLoaderFactory(
        url_loader_factory_.BindNewPipeAndPassReceiver(),
        std::move(url_loader_factory_params));
  }
  return url_loader_factory_.get();
}

void BruschettaNetworkContext::EnsureNetworkContextExists() {
  if (network_context_ && network_context_.is_connected()) {
    return;
  }
  CreateNetworkContext();
}

void BruschettaNetworkContext::CreateNetworkContext() {
  network::mojom::NetworkContextParamsPtr network_context_params =
      g_browser_process->system_network_context_manager()
          ->CreateDefaultNetworkContextParams();
  network_context_params->http_cache_enabled = false;

  proxy_config_monitor_.AddToNetworkContextParams(network_context_params.get());

  network_context_.reset();
  content::CreateNetworkContextInNetworkService(
      network_context_.BindNewPipeAndPassReceiver(),
      std::move(network_context_params));
}

void BruschettaNetworkContext::OnSSLCertificateError(
    const GURL& url,
    int net_error,
    const net::SSLInfo& ssl_info,
    bool fatal,
    OnSSLCertificateErrorCallback response) {
  std::move(response).Run(net::ERR_INSECURE_RESPONSE);
}

void BruschettaNetworkContext::OnCertificateRequested(
    const std::optional<base::UnguessableToken>& window_id,
    const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
    mojo::PendingRemote<network::mojom::ClientCertificateResponder>
        cert_responder_remote) {
  if (!cert_store_ &&
      !(cert_store_ =
            ProfileNetworkContextServiceFactory::GetForContext(profile_)
                ->CreateClientCertStore())) {
    OnGotClientCerts(cert_info, std::move(cert_responder_remote), /*certs=*/{});
    return;
  }
  cert_store_->GetClientCerts(
      cert_info, base::BindOnce(&BruschettaNetworkContext::OnGotClientCerts,
                                weak_ptr_factory_.GetWeakPtr(), cert_info,
                                std::move(cert_responder_remote)));
}

void BruschettaNetworkContext::OnGotClientCerts(
    const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
    mojo::PendingRemote<network::mojom::ClientCertificateResponder>
        cert_responder_remote,
    net::ClientCertIdentityList certs) {
  GURL requesting_url =
      enterprise_util::GetRequestingUrl(cert_info->host_and_port);
  net::ClientCertIdentityList matching_certificates, nonmatching_certificates;
  // Bruschetta is an enterprise feature with the URL set in policy. So if they
  // pick a URL which requires an SSL cert they should also provide the cert via
  // policy. We don't have a WebContents so can't show UI.
  enterprise_util::AutoSelectCertificates(
      profile_, requesting_url, std::move(certs), &matching_certificates,
      &nonmatching_certificates);

  if (matching_certificates.size() == 0) {
    LOG(ERROR) << "No matching certificate, continuing without any (this will "
                  "probably fail)";
    mojo::Remote<network::mojom::ClientCertificateResponder> cert_responder(
        std::move(cert_responder_remote));
    cert_responder->ContinueWithoutCertificate();
    return;
  }

  // We're called from views code which doesn't have a WebContents with which
  // to prompt the user to pick a cert, so always take the first matching cert
  // even if there are multiple.
  std::unique_ptr<net::ClientCertIdentity> auto_selected_identity =
      std::move(matching_certificates[0]);

  scoped_refptr<net::X509Certificate> cert =
      auto_selected_identity->certificate();
  net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
      std::move(auto_selected_identity),
      base::BindOnce(&BruschettaNetworkContext::ContinueWithCertificate,
                     weak_ptr_factory_.GetWeakPtr(),
                     std::move(cert_responder_remote), std::move(cert)));
}

void BruschettaNetworkContext::ContinueWithCertificate(
    mojo::PendingRemote<network::mojom::ClientCertificateResponder>
        cert_responder_remote,
    scoped_refptr<net::X509Certificate> cert,
    scoped_refptr<net::SSLPrivateKey> private_key) {
  mojo::PendingRemote<network::mojom::SSLPrivateKey> ssl_private_key;
  mojo::Remote<network::mojom::ClientCertificateResponder> cert_responder(
      std::move(cert_responder_remote));

  mojo::MakeSelfOwnedReceiver(
      std::make_unique<SSLPrivateKeyBridge>(private_key),
      ssl_private_key.InitWithNewPipeAndPassReceiver());
  cert_responder->ContinueWithCertificate(
      cert, private_key->GetProviderName(),
      private_key->GetAlgorithmPreferences(), std::move(ssl_private_key));
}

void BruschettaNetworkContext::OnAuthRequired(
    const std::optional<base::UnguessableToken>& window_id,
    int32_t request_id,
    const GURL& url,
    bool first_auth_attempt,
    const net::AuthChallengeInfo& auth_info,
    const scoped_refptr<net::HttpResponseHeaders>& head_headers,
    mojo::PendingRemote<network::mojom::AuthChallengeResponder>
        auth_challenge_responder) {
  mojo::Remote<network::mojom::AuthChallengeResponder>
      auth_challenge_responder_remote(std::move(auth_challenge_responder));
  auth_challenge_responder_remote->OnAuthCredentials(std::nullopt);
}

void BruschettaNetworkContext::OnPrivateNetworkAccessPermissionRequired(
    const GURL& url,
    const net::IPAddress& ip_address,
    const std::optional<std::string>& private_network_device_id,
    const std::optional<std::string>& private_network_device_name,
    OnPrivateNetworkAccessPermissionRequiredCallback callback) {
  std::move(callback).Run(false);
}

void BruschettaNetworkContext::OnLocalNetworkAccessPermissionRequired(
    OnLocalNetworkAccessPermissionRequiredCallback callback) {
  std::move(callback).Run(false);
}

void BruschettaNetworkContext::OnClearSiteData(
    const GURL& url,
    const std::string& header_value,
    int32_t load_flags,
    const std::optional<net::CookiePartitionKey>& cookie_partition_key,
    bool partitioned_state_allowed_only,
    OnClearSiteDataCallback callback) {
  std::move(callback).Run();
}

void BruschettaNetworkContext::OnLoadingStateUpdate(
    network::mojom::LoadInfoPtr info,
    OnLoadingStateUpdateCallback callback) {
  std::move(callback).Run();
}

void BruschettaNetworkContext::OnDataUseUpdate(
    int32_t network_traffic_annotation_id_hash,
    int64_t recv_bytes,
    int64_t sent_bytes) {}

void BruschettaNetworkContext::OnSharedStorageHeaderReceived(
    const url::Origin& request_origin,
    std::vector<network::mojom::SharedStorageModifierMethodWithOptionsPtr>
        methods_with_options,
    const std::optional<std::string>& with_lock,
    OnSharedStorageHeaderReceivedCallback callback) {
  std::move(callback).Run();
}

void BruschettaNetworkContext::OnAdAuctionEventRecordHeaderReceived(
    network::AdAuctionEventRecord event_record,
    const std::optional<url::Origin>& top_frame_origin) {}

void BruschettaNetworkContext::Clone(
    mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver>
        observer) {
  url_loader_observers_.Add(this, std::move(observer));
}

void BruschettaNetworkContext::OnWebSocketConnectedToPrivateNetwork(
    network::mojom::IPAddressSpace ip_address_space) {}

void BruschettaNetworkContext::OnUrlLoaderConnectedToPrivateNetwork(
    const GURL& request_url,
    network::mojom::IPAddressSpace response_address_space,
    network::mojom::IPAddressSpace client_address_space,
    network::mojom::IPAddressSpace target_address_space) {}

}  // namespace bruschetta