File: ip_protection_proxy_delegate.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (315 lines) | stat: -rw-r--r-- 11,978 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/ip_protection/common/ip_protection_proxy_delegate.h"

#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>

#include "base/check.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/memory/raw_ref.h"
#include "components/ip_protection/common/ip_protection_core.h"
#include "components/ip_protection/common/ip_protection_data_types.h"
#include "components/ip_protection/common/ip_protection_proxy_config_manager_impl.h"
#include "components/ip_protection/common/ip_protection_telemetry.h"
#include "components/ip_protection/common/ip_protection_token_manager_impl.h"
#include "net/base/features.h"
#include "net/base/net_errors.h"
#include "net/base/proxy_chain.h"
#include "net/base/proxy_server.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/schemeful_site.h"
#include "net/base/url_util.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "net/http/structured_headers.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/proxy_resolution/proxy_resolution_service.h"
#include "net/proxy_resolution/proxy_retry_info.h"

namespace ip_protection {

IpProtectionProxyDelegate::IpProtectionProxyDelegate(
    IpProtectionCore* ip_protection_core)
    : ip_protection_core_(
          raw_ref<IpProtectionCore>::from_ptr(ip_protection_core)) {}

IpProtectionProxyDelegate::~IpProtectionProxyDelegate() = default;

ProxyResolutionResult IpProtectionProxyDelegate::ClassifyRequest(
    const GURL& url,
    const net::NetworkAnonymizationKey& network_anonymization_key,
    net::ProxyInfo* result) {
  auto vlog = [&](std::string message) {
    std::optional<net::SchemefulSite> top_frame_site =
        network_anonymization_key.GetTopFrameSite();
    VLOG(3) << "IPPD::ClassifyRequest(" << url << ", "
            << (top_frame_site.has_value() ? top_frame_site.value()
                                           : net::SchemefulSite())
            << ") - " << message;
  };

  // Check eligibility of this request.
  if (!ip_protection_core_->IsMdlPopulated()) {
    vlog("proxy allow list not populated");
    return ProxyResolutionResult::kMdlNotPopulated;
  } else if (!ip_protection_core_->RequestShouldBeProxied(
                 url, network_anonymization_key)) {
    vlog("proxy allow list did not match");
    return ProxyResolutionResult::kNoMdlMatch;
  } else {
    vlog("proxy allow list matched");
  }

  result->set_is_mdl_match(true);

  // Check availability. We do not proxy requests if:
  // - The allow list has not been populated.
  // - The request doesn't match the allow list.
  // - The token cache is not available.
  // - The token cache does not have tokens.
  // - No proxy list is available.
  // - `is_ip_protection_enabled_` is `false` (in other words, the user has
  //   disabled IP Protection via user settings or enterprise policy).
  // - `kIpPrivacyDirectOnly` is `true`.
  if (!ip_protection_core_->IsIpProtectionEnabled()) {
    vlog("ip protection proxy is not currently enabled");
    return ProxyResolutionResult::kSettingDisabled;
  }
  const bool were_token_caches_ever_filled =
      ip_protection_core_->WereTokenCachesEverFilled();
  const bool auth_tokens_are_available =
      ip_protection_core_->AreAuthTokensAvailable();
  const bool proxy_list_is_available =
      ip_protection_core_->IsProxyListAvailable();

  if (!proxy_list_is_available) {
    vlog("no proxy list available from cache");
    return ProxyResolutionResult::kProxyListNotAvailable;
  } else if (!were_token_caches_ever_filled) {
    vlog("token caches have never been filled");
    return ProxyResolutionResult::kTokensNeverAvailable;
  } else if (!auth_tokens_are_available) {
    vlog("no auth token available from cache");
    return ProxyResolutionResult::kTokensExhausted;
  }

  // Check if the protection has been disabled via User Bypass.
  if (net::features::kIpPrivacyEnableUserBypass.Get() &&
      ip_protection_core_->HasTrackingProtectionException(
          network_anonymization_key.GetTopFrameSite()->GetURL())) {
    return ProxyResolutionResult::kHasSiteException;
  }

  return ProxyResolutionResult::kAttemptProxy;
}

void IpProtectionProxyDelegate::OnResolveProxy(
    const GURL& url,
    const net::NetworkAnonymizationKey& network_anonymization_key,
    const std::string& method,
    const net::ProxyRetryInfoMap& proxy_retry_info,
    net::ProxyInfo* result) {
  ProxyResolutionResult resolution_result =
      ClassifyRequest(url, network_anonymization_key, result);
  Telemetry().ProxyResolution(resolution_result);

  const std::optional<net::SchemefulSite>& top_frame_site =
      network_anonymization_key.GetTopFrameSite();
  if (bool is_prt_eligible =
          resolution_result == ProxyResolutionResult::kAttemptProxy ||
          net::features::kEnableProbabilisticRevealTokensForNonProxiedRequests
              .Get();
      is_prt_eligible &&
      !net::features::kProbabilisticRevealTokenFetchOnly.Get() &&
      top_frame_site.has_value()) {
    result->set_prt_header_value(
        GetPRTHeaderValue(url, top_frame_site.value()));
  } else {
    result->set_prt_header_value(std::nullopt);
  }

  if (resolution_result != ProxyResolutionResult::kAttemptProxy) {
    return;
  }

  net::ProxyList proxy_list;
  if (!net::features::kIpPrivacyDirectOnly.Get()) {
    const std::vector<net::ProxyChain>& proxy_chain_list =
        ip_protection_core_->GetProxyChainList();
    for (const auto& proxy_chain : proxy_chain_list) {
      // Proxying HTTP traffic over HTTPS/SPDY proxies requires multi-proxy
      // chains.
      CHECK(proxy_chain.is_multi_proxy());

      proxy_list.AddProxyChain(std::move(proxy_chain));
    }
  }

  if (net::features::kIpPrivacyFallbackToDirect.Get()) {
    // Final fallback is to DIRECT.
    auto direct_proxy_chain = net::ProxyChain::ForIpProtection({});
    proxy_list.AddProxyChain(std::move(direct_proxy_chain));
  }

  if (VLOG_IS_ON(3)) {
    VLOG(3) << "IPPD::OnResolveProxy(" << url << ", "
            << (top_frame_site.has_value() ? top_frame_site.value()
                                           : net::SchemefulSite())
            << ") - setting proxy list (before deprioritization) to "
            << proxy_list.ToDebugString();
  }
  result->OverrideProxyList(MergeProxyRules(result->proxy_list(), proxy_list));
  result->DeprioritizeBadProxyChains(proxy_retry_info);
  return;
}

void IpProtectionProxyDelegate::OnSuccessfulRequestAfterFailures(
    const net::ProxyRetryInfoMap& proxy_retry_info) {
  // A request was successful, but one or more proxies failed. If _only_ QUIC
  // proxies failed, then we assume this is because QUIC is not working on
  // this network, and stop injecting QUIC proxies into the proxy list.
  bool seen_quic = false;
  for (const auto& chain_and_info : proxy_retry_info) {
    const net::ProxyChain& proxy_chain = chain_and_info.first;
    if (!proxy_chain.is_for_ip_protection()) {
      continue;
    }
    const net::ProxyServer& proxy_server = proxy_chain.First();
    if (proxy_server.is_quic()) {
      seen_quic = true;
    } else {
      // A non-QUIC chain has failed.
      return;
    }
  }

  if (seen_quic) {
    // Only QUIC chains failed.
    ip_protection_core_->QuicProxiesFailed();
  }
}

void IpProtectionProxyDelegate::OnFallback(const net::ProxyChain& bad_chain,
                                           int net_error) {
  // If the bad proxy was an IP Protection proxy, refresh the list of IP
  // protection proxies immediately.
  if (bad_chain.is_for_ip_protection()) {
    Telemetry().ProxyChainFallback(bad_chain.ip_protection_chain_id());
    ip_protection_core_->RequestRefreshProxyList();
  }
}

net::Error IpProtectionProxyDelegate::OnBeforeTunnelRequest(
    const net::ProxyChain& proxy_chain,
    size_t chain_index,
    net::HttpRequestHeaders* extra_headers) {
  auto vlog = [](std::string message) {
    VLOG(2) << "NSPD::OnBeforeTunnelRequest() - " << message;
  };
  if (proxy_chain.is_for_ip_protection()) {
    std::optional<BlindSignedAuthToken> token =
        ip_protection_core_->GetAuthToken(chain_index);
    if (token) {
      vlog("adding auth token");
      // The token value we have here is the full Authorization header value,
      // so we can add it verbatim.
      extra_headers->SetHeader(net::HttpRequestHeaders::kAuthorization,
                               std::move(token->token));
    } else {
      vlog("no token available");
      // This is an unexpected circumstance, but does happen in the wild.
      // Rather than send the request to the proxy, which will reply with an
      // error, mark the connection as failed immediately.
      return net::ERR_TUNNEL_CONNECTION_FAILED;
    }
  } else {
    vlog("not for IP protection");
  }
  int experiment_arm = net::features::kIpPrivacyDebugExperimentArm.Get();
  if (experiment_arm != 0) {
    extra_headers->SetHeader("Ip-Protection-Debug-Experiment-Arm",
                             base::NumberToString(experiment_arm));
  }
  return net::OK;
}

net::Error IpProtectionProxyDelegate::OnTunnelHeadersReceived(
    const net::ProxyChain& proxy_chain,
    size_t chain_index,
    const net::HttpResponseHeaders& response_headers) {
  return net::OK;
}

void IpProtectionProxyDelegate::SetProxyResolutionService(
    net::ProxyResolutionService* proxy_resolution_service) {}

bool IpProtectionProxyDelegate::AliasRequiresProxyOverride(
    const std::string scheme,
    const std::vector<std::string>& dns_aliases,
    const net::NetworkAnonymizationKey& network_anonymization_key) {
  // TODO(crbug.com/383134117): Iterate through aliases and invoke mdl manager
  // to check if any match a 3p resource.
  return false;
}

// static
net::ProxyList IpProtectionProxyDelegate::MergeProxyRules(
    const net::ProxyList& existing_proxy_list,
    const net::ProxyList& custom_proxy_list) {
  net::ProxyList merged_proxy_list;
  for (const auto& existing_chain : existing_proxy_list.AllChains()) {
    if (existing_chain.is_direct()) {
      // Replace direct option with all proxies in the custom proxy list
      for (const auto& custom_chain : custom_proxy_list.AllChains()) {
        merged_proxy_list.AddProxyChain(custom_chain);
      }
    } else {
      merged_proxy_list.AddProxyChain(existing_chain);
    }
  }

  return merged_proxy_list;
}

/*
  Sec-Probabilistic-Reveal-Token header is a structured header of type Byte
  Sequence (rfc8941 section 3.3.5) and holds a serialized PRT.

  `GetPRTHeaderValue()` will return nullopt if destination is not
  registered for PRTs or there is no PRTs in the manager.
*/
std::optional<std::string> IpProtectionProxyDelegate::GetPRTHeaderValue(
    const GURL& url,
    const net::SchemefulSite& top_frame_site) const {
  if (!ip_protection_core_->IsProbabilisticRevealTokenAvailable() ||
      !ip_protection_core_->ShouldRequestIncludeProbabilisticRevealToken(url)) {
    return std::nullopt;
  }
  const std::string top_level =
      net::registry_controlled_domains::GetDomainAndRegistry(
          top_frame_site.GetURL(),
          net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
  const std::string third_party =
      net::registry_controlled_domains::GetDomainAndRegistry(
          url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
  const std::optional<std::string> prt =
      ip_protection_core_->GetProbabilisticRevealToken(top_level, third_party);
  if (!prt.has_value()) {
    return std::nullopt;
  }
  auto item = net::structured_headers::Item(
      std::move(prt).value(),
      net::structured_headers::Item::ItemType::kByteSequenceType);
  return net::structured_headers::SerializeItem(item);
}

}  // namespace ip_protection