File: https_upgrades_navigation_throttle.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: 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 (307 lines) | stat: -rw-r--r-- 13,821 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
// Copyright 2022 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/ssl/https_upgrades_navigation_throttle.h"

#include <utility>

#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ssl/https_first_mode_settings_tracker.h"
#include "chrome/browser/ssl/https_only_mode_tab_helper.h"
#include "chrome/browser/ssl/https_upgrades_navigation_throttle.h"
#include "chrome/browser/ssl/https_upgrades_util.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/security_interstitials/core/https_only_mode_metrics.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/web_contents.h"
#include "net/base/net_errors.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "ui/base/page_transition_types.h"

using security_interstitials::https_only_mode::Event;

namespace {

// Time that the throttle will wait before canceling the upgraded navigation and
// showing the HTTPS-First Mode interstitial.
base::TimeDelta g_fallback_delay = base::Seconds(3);

}  // namespace

// static
void HttpsUpgradesNavigationThrottle::MaybeCreateAndAdd(
    content::NavigationThrottleRegistry& registry,
    std::unique_ptr<SecurityBlockingPageFactory> blocking_page_factory,
    Profile* profile) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  // HTTPS-First Mode is only relevant for primary main-frame HTTP(S)
  // navigations.
  content::NavigationHandle& handle = registry.GetNavigationHandle();
  if (!handle.GetURL().SchemeIsHTTPOrHTTPS() ||
      !handle.IsInPrimaryMainFrame() || handle.IsSameDocument()) {
    return;
  }

  PrefService* prefs = profile->GetPrefs();
  security_interstitials::https_only_mode::HttpInterstitialState
      interstitial_state;
  interstitial_state.enabled_by_pref =
      prefs && prefs->GetBoolean(prefs::kHttpsOnlyModeEnabled);

  if (base::FeatureList::IsEnabled(features::kHttpsFirstModeIncognito)) {
    if (profile->IsIncognitoProfile() && prefs &&
        prefs->GetBoolean(prefs::kHttpsFirstModeIncognito)) {
      interstitial_state.enabled_by_incognito = true;
    }
  }

  StatefulSSLHostStateDelegate* state =
      static_cast<StatefulSSLHostStateDelegate*>(
          profile->GetSSLHostStateDelegate());

  if (IsBalancedModeEnabled(prefs) && state &&
      !state->HttpsFirstBalancedModeSuppressedForTesting()) {
    interstitial_state.enabled_in_balanced_mode = true;
  }

  auto* storage_partition =
      handle.GetWebContents()->GetPrimaryMainFrame()->GetStoragePartition();

  HttpsFirstModeService* hfm_service =
      HttpsFirstModeServiceFactory::GetForProfile(profile);
  if (hfm_service) {
    // Can be null in some cases, e.g. when using Ash sign-in profile.
    hfm_service->IncrementRecentNavigationCount();
    interstitial_state.enabled_by_typically_secure_browsing =
        hfm_service->IsInterstitialEnabledByTypicallySecureUserHeuristic();
  }

  // StatefulSSLHostStateDelegate can be null during tests.
  if (state &&
      state->IsHttpsEnforcedForUrl(handle.GetURL(), storage_partition) &&
      !MustDisableSiteEngagementHeuristic(profile)) {
    interstitial_state.enabled_by_engagement_heuristic = true;
  }

  bool https_upgrades_enabled =
      interstitial_state.enabled_by_pref ||
      base::FeatureList::IsEnabled(features::kHttpsUpgrades);
  if (!https_upgrades_enabled) {
    return;
  }

  // Ensure that the HttpsOnlyModeTabHelper has been created (this does nothing
  // if it has already been created for the WebContents). There are cases where
  // the tab helper won't get created by the initialization in
  // chrome/browser/ui/tab_helpers.cc but the criteria for adding the throttle
  // are still met (see crbug.com/1233889 for one example).
  HttpsOnlyModeTabHelper::CreateForWebContents(handle.GetWebContents());

  registry.AddThrottle(std::make_unique<HttpsUpgradesNavigationThrottle>(
      registry, profile, std::move(blocking_page_factory), interstitial_state));
}

HttpsUpgradesNavigationThrottle::HttpsUpgradesNavigationThrottle(
    content::NavigationThrottleRegistry& registry,
    Profile* profile,
    std::unique_ptr<SecurityBlockingPageFactory> blocking_page_factory,
    security_interstitials::https_only_mode::HttpInterstitialState
        interstitial_state)
    : content::NavigationThrottle(registry),
      profile_(profile),
      blocking_page_factory_(std::move(blocking_page_factory)),
      interstitial_state_(interstitial_state) {}

HttpsUpgradesNavigationThrottle::~HttpsUpgradesNavigationThrottle() = default;

content::NavigationThrottle::ThrottleCheckResult
HttpsUpgradesNavigationThrottle::WillStartRequest() {
  // If the navigation is fallback to HTTP, trigger the HTTP interstitial (if
  // enabled). The interceptor creates a redirect for the fallback navigation,
  // which will trigger MaybeCreateLoader() in the interceptor for the redirect
  // but *doesn't* trigger WillStartRequest() because it's all part of the same
  // request. Here, we skip directly to showing the HTTP interstitial if this
  // is:
  //   (1) a back/forward navigation, and
  //   (2) the URL already failed upgrades before.
  // This lets us avoid triggering the Interceptor during a back/forward
  // navigation (which breaks history state) and acts like the browser
  // "remembering" the state of the tab as being on the interstitial for that
  // URL.
  //
  // Other cases for starting a navigation to a URL that previously failed
  // to be upgraded should go through the full upgrade flow -- better to assume
  // that something may have changed in the time since. For example: a user
  // reloading the tab showing the interstitial should re-try the upgrade.
  auto* handle = navigation_handle();
  auto* contents = handle->GetWebContents();
  auto* tab_helper = HttpsOnlyModeTabHelper::FromWebContents(contents);

  if ((handle->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK &&
       tab_helper->has_failed_upgrade(handle->GetURL())) &&
      !handle->GetURL().SchemeIsCryptographic()) {
    if (IsInterstitialEnabled(interstitial_state_)) {
      security_interstitials::https_only_mode::RecordInterstitialReason(
          interstitial_state_);

      // Mark this as a fallback HTTP navigation and trigger the interstitial.
      tab_helper->set_is_navigation_fallback(true);

      ukm::SourceId source_id =
          ukm::ConvertToSourceId(navigation_handle()->GetNavigationId(),
                                 ukm::SourceIdType::NAVIGATION_ID);
      std::unique_ptr<security_interstitials::HttpsOnlyModeBlockingPage>
          blocking_page =
              blocking_page_factory_->CreateHttpsOnlyModeBlockingPage(
                  contents, handle->GetURL(), interstitial_state_,
                  /*url_type_param=*/std::nullopt,
                  base::BindRepeating(&RecordHttpsFirstModeUKM, source_id));
      std::string interstitial_html = blocking_page->GetHTMLContents();
      security_interstitials::SecurityInterstitialTabHelper::
          AssociateBlockingPage(handle, std::move(blocking_page));
      return content::NavigationThrottle::ThrottleCheckResult(
          content::NavigationThrottle::CANCEL, net::ERR_BLOCKED_BY_CLIENT,
          std::move(interstitial_html));
    }

    // Otherwise, just record metrics and continue.
    // TODO(crbug.com/40904694): Record a separate histogram for Site Engagement
    // heuristic.
  }

  // TODO(crbug.com/40064769): There are some cases where the navigation may
  // "restart", such as if we encounter an exempted transient network error on
  // the upgraded HTTPS URL, show a net error page, and then reload the tab. In
  // these cases the navigation will proceed with the upgrade/fallback logic,
  // but the navigation timeout will no longer be set. Currently, re-starting
  // the timer here would trigger a DCHECK in NavigationRequest.

  // Navigation is HTTPS or an initial HTTP navigation (which will get
  // upgraded by the interceptor). Fallback HTTP navigations are handled in
  // WillRedirectRequest().
  return content::NavigationThrottle::ThrottleAction::PROCEED;
}

content::NavigationThrottle::ThrottleCheckResult
HttpsUpgradesNavigationThrottle::WillFailRequest() {
  // Fallback to HTTP on navigation failure is handled by
  // HttpsUpgradesInterceptor::MaybeCreateLoaderForResponse().
  return content::NavigationThrottle::PROCEED;
}

content::NavigationThrottle::ThrottleCheckResult
HttpsUpgradesNavigationThrottle::WillRedirectRequest() {
  // If the navigation is doing a fallback redirect to HTTP, trigger the HTTP
  // interstitial (if enabled). The interceptor creates a redirect for the
  // fallback navigation, which will trigger MaybeCreateLoader() in the
  // interceptor for the redirect but *doesn't* trigger WillStartRequest()
  // because it's all part of the same request.
  auto* handle = navigation_handle();
  auto* contents = handle->GetWebContents();
  auto* tab_helper = HttpsOnlyModeTabHelper::FromWebContents(contents);

  // Slow loading fallback URLs should be handled by the net stack.
  if (tab_helper->is_navigation_fallback()) {
    handle->CancelNavigationTimeout();
  }

  ukm::SourceId source_id = ukm::ConvertToSourceId(
      navigation_handle()->GetNavigationId(), ukm::SourceIdType::NAVIGATION_ID);
  if (tab_helper->is_navigation_fallback() &&
      !handle->GetURL().SchemeIsCryptographic() &&
      IsInterstitialEnabled(interstitial_state_)) {
    security_interstitials::https_only_mode::RecordInterstitialReason(
        interstitial_state_);

    std::unique_ptr<security_interstitials::HttpsOnlyModeBlockingPage>
        blocking_page = blocking_page_factory_->CreateHttpsOnlyModeBlockingPage(
            contents, handle->GetURL(), interstitial_state_,
            /*url_type_param=*/std::nullopt,
            base::BindRepeating(&RecordHttpsFirstModeUKM, source_id));
    std::string interstitial_html = blocking_page->GetHTMLContents();
    security_interstitials::SecurityInterstitialTabHelper::
        AssociateBlockingPage(handle, std::move(blocking_page));
    return content::NavigationThrottle::ThrottleCheckResult(
        content::NavigationThrottle::CANCEL, net::ERR_BLOCKED_BY_CLIENT,
        std::move(interstitial_html));
  }

  // Otherwise, just record metrics and continue.
  // TODO(crbug.com/40904694): Record a separate histogram for Site Engagement
  // heuristic.

  // If the navigation was upgraded by the Interceptor, then the Throttle's
  // WillRedirectRequest() will get triggered by the artificial redirect to
  // HTTPS. The HTTPS upgrade will always happen after the Throttle's
  // WillStartRequest() (which only checks for fallback HTTP), so tracking
  // upgraded requests is deferred to WillRedirectRequest() here. Which
  // navigations to upgrade is determined by the Interceptor, not the Throttle.
  //
  // The navigation may get upgraded at various points during redirects:
  //   1. The Interceptor serves an artificial redirect to HTTPS if the
  //      navigation is upgraded. This means the Throttle will see the upgraded
  //      navigation state for the first time here in WillRedirectRequest().
  //   2. HTTPS->HTTP downgrades can occur later in the lifecycle of a
  //      navigation, and will also result in the Interceptor serving an
  //      artificial redirect to upgrade the navigation.
  //
  // The Interceptor logs the URLs that it sees and triggers fallback if it
  // encounters a redirect loop. Any cases that might not be caught by the
  // Interceptor should result in net::ERR_TOO_MANY_REDIRECTS, but in general
  // redirect loops should hit the cache and not cost too much. If they go too
  // long, the fallback timer will kick in. ERR_TOO_MANY_REDIRECTS should result
  // in the request failing and triggering fallback.
  if (tab_helper->is_navigation_upgraded()) {
    // Check if the timer is already started, as there may be additional
    // redirects on the navigation after the artificial upgrade redirect.
    bool timer_started =
        navigation_handle()->SetNavigationTimeout(g_fallback_delay);
    if (timer_started) {
      RecordHttpsFirstModeNavigation(Event::kUpgradeAttempted,
                                     interstitial_state_);
    }
  }

  return content::NavigationThrottle::PROCEED;
}

content::NavigationThrottle::ThrottleCheckResult
HttpsUpgradesNavigationThrottle::WillProcessResponse() {
  // Clear the status for this navigation as it will successfully commit.
  auto* tab_helper = HttpsOnlyModeTabHelper::FromWebContents(
      navigation_handle()->GetWebContents());
  if (tab_helper->is_navigation_upgraded()) {
    RecordHttpsFirstModeNavigation(Event::kUpgradeSucceeded,
                                   interstitial_state_);
    tab_helper->set_is_navigation_upgraded(false);
  }

  // Clear the fallback flag, if set.
  tab_helper->set_is_navigation_fallback(false);

  return content::NavigationThrottle::PROCEED;
}

const char* HttpsUpgradesNavigationThrottle::GetNameForLogging() {
  return "HttpsUpgradesNavigationThrottle";
}

// static
void HttpsUpgradesNavigationThrottle::set_timeout_for_testing(
    base::TimeDelta timeout) {
  g_fallback_delay = timeout;
}