Backed out changeset f594e6f00208 (bug 1940883) for causing crashes in bug 1941164.
[gecko.git] / dom / security / nsHTTPSOnlyUtils.h
blobcbd7cf74217e4c628e40f6879af6022768e1d1c3
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef nsHTTPSOnlyUtils_h___
8 #define nsHTTPSOnlyUtils_h___
10 #include "nsIScriptError.h"
11 #include "nsISupports.h"
12 #include "mozilla/net/DocumentLoadListener.h"
14 class nsHTTPSOnlyUtils {
15 public:
16 /**
17 * Returns if HTTPS-Only Mode preference is enabled
18 * @param aFromPrivateWindow true if executing in private browsing mode
19 * @return true if HTTPS-Only Mode is enabled
21 static bool IsHttpsOnlyModeEnabled(bool aFromPrivateWindow);
23 /**
24 * Returns if HTTPS-First Mode preference is enabled
25 * @param aFromPrivateWindow true if executing in private browsing mode
26 * @return true if HTTPS-First Mode is enabled
28 static bool IsHttpsFirstModeEnabled(bool aFromPrivateWindow);
30 /**
31 * Potentially fires an http request for a top-level load (provided by
32 * aDocumentLoadListener) in the background to avoid long timeouts in case
33 * the upgraded https top-level load most likely will result in timeout.
34 * @param aDocumentLoadListener The Document listener associated with
35 * the original top-level channel.
37 static void PotentiallyFireHttpRequestToShortenTimout(
38 mozilla::net::DocumentLoadListener* aDocumentLoadListener);
40 /**
41 * Determines if a request should get upgraded because of the HTTPS-Only mode.
42 * If true, the httpsOnlyStatus flag in LoadInfo gets updated and a message is
43 * logged in the console.
44 * @param aURI nsIURI of request
45 * @param aLoadInfo nsILoadInfo of request
46 * @return true if request should get upgraded
48 static bool ShouldUpgradeRequest(nsIURI* aURI, nsILoadInfo* aLoadInfo);
50 /**
51 * Determines if a request should get upgraded because of the HTTPS-Only mode.
52 * If true, a message is logged in the console.
53 * @param aURI nsIURI of request
54 * @param aLoadInfo nsILoadInfo of request
55 * @return true if request should get upgraded
57 static bool ShouldUpgradeWebSocket(nsIURI* aURI, nsILoadInfo* aLoadInfo);
59 /**
60 * Determines if we might get stuck in an upgrade-downgrade-endless loop
61 * where https-only upgrades the request to https and the website downgrades
62 * the scheme to http again causing an endless upgrade downgrade loop. E.g.
63 * https-only upgrades to https and the website answers with a meta-refresh
64 * to downgrade to same-origin http version. Similarly this method breaks
65 * the endless cycle for JS based redirects and 302 based redirects.
66 * Note this function is also used when we got an HTTPS RR for the website.
67 * @param aURI nsIURI of request
68 * @param aLoadInfo nsILoadInfo of request
69 * @param aOptions an options object indicating if the function
70 * should be consulted for https-only or https-first mode or
71 * the case that an HTTPS RR is presented.
72 * @return true if an endless loop is detected
74 enum class UpgradeDowngradeEndlessLoopOptions {
75 EnforceForHTTPSOnlyMode,
76 EnforceForHTTPSFirstMode,
77 EnforceForHTTPSRR,
79 static bool IsUpgradeDowngradeEndlessLoop(
80 nsIURI* aOldURI, nsIURI* aNewURI, nsILoadInfo* aLoadInfo,
81 const mozilla::EnumSet<UpgradeDowngradeEndlessLoopOptions>& aOptions =
82 {});
84 /**
85 * Determines if a request should get upgraded because of the HTTPS-First
86 * mode. If true, the httpsOnlyStatus in LoadInfo gets updated and a message
87 * is logged in the console.
88 * @param aURI nsIURI of request
89 * @param aLoadInfo nsILoadInfo of request
90 * @return true if request should get upgraded
92 static bool ShouldUpgradeHttpsFirstRequest(nsIURI* aURI,
93 nsILoadInfo* aLoadInfo);
95 /**
96 * Determines if the request was previously upgraded with HTTPS-First, creates
97 * a downgraded URI and logs to console.
98 * @param aStatus Status code
99 * @param aDocumentLoadListener Failed document load listener
100 * @return URI with http-scheme or nullptr
102 static already_AddRefed<nsIURI> PotentiallyDowngradeHttpsFirstRequest(
103 mozilla::net::DocumentLoadListener* aDocumentLoadListener,
104 nsresult aStatus);
107 * Checks if the error code is on a block-list of codes that are probably
108 * not related to a HTTPS-Only Mode upgrade.
109 * @param aChannel The failed Channel.
110 * @param aError Error Code from Request
111 * @return false if error is not related to upgrade
113 static bool CouldBeHttpsOnlyError(nsIChannel* aChannel, nsresult aError);
116 * Logs localized message to either content console or browser console
117 * @param aName Localization key
118 * @param aParams Localization parameters
119 * @param aFlags Logging Flag (see nsIScriptError)
120 * @param aLoadInfo The loadinfo of the request.
121 * @param [aURI] Optional: URI to log
122 * @param [aUseHttpsFirst] Optional: Log using HTTPS-First (vs. HTTPS-Only)
124 static void LogLocalizedString(const char* aName,
125 const nsTArray<nsString>& aParams,
126 uint32_t aFlags, nsILoadInfo* aLoadInfo,
127 nsIURI* aURI = nullptr,
128 bool aUseHttpsFirst = false);
131 * Tests if the HTTPS-Only upgrade exception is set for a given principal.
132 * @param aPrincipal The principal for whom the exception should be checked
133 * @return True if exempt
135 static bool TestIfPrincipalIsExempt(nsIPrincipal* aPrincipal,
136 bool aCheckForHTTPSFirst = false);
139 * Tests if the HTTPS-Only Mode upgrade exception is set for channel result
140 * principal and sets or removes the httpsOnlyStatus-flag on the loadinfo
141 * accordingly.
142 * Note: This function only adds an exemption for loads of TYPE_DOCUMENT.
143 * @param aChannel The channel to be checked
145 static void TestSitePermissionAndPotentiallyAddExemption(
146 nsIChannel* aChannel);
149 * Checks whether CORS or mixed content requests are safe because they'll get
150 * upgraded to HTTPS
151 * @param aLoadInfo nsILoadInfo of request
152 * @return true if it's safe to accept
154 static bool IsSafeToAcceptCORSOrMixedContent(nsILoadInfo* aLoadInfo);
157 * Checks if https only or https first mode is enabled for this load
158 * @param aLoadInfo nsILoadInfo of the request
160 static bool ShouldUpgradeConnection(nsILoadInfo* aLoadInfo);
163 * Checks if two URIs are same origin modulo the difference that
164 * aToURI scheme is downgraded to http from https aFromURI.
165 * @param aFromURI nsIURI using scheme of https
166 * @param aToURI nsIURI using scheme of http
167 * @return true, if URIs are equal except scheme and ref
169 static bool IsHttpDowngrade(nsIURI* aFromURI, nsIURI* aToURI);
172 * Will add a special temporary HTTPS-Only exception that only applies to
173 * HTTPS-First, and is not exposed in the UI.
174 * @param aURI The URL for whose HTTP principal the exception should be
175 * added
176 * @param aLoadInfo The loadinfo of the request triggering this exception to
177 * be added (needs to match aURI)
179 static nsresult AddHTTPSFirstException(nsCOMPtr<nsIURI> aURI,
180 nsILoadInfo* const aLoadInfo);
183 * Determines which HTTPS-Only status flags should get propagated to
184 * sub-resources or sub-documents. As sub-resources and sub-documents are
185 * exempt when the top-level document is exempt, we need to copy the "exempt"
186 * flag. The HTTPS-First "upgraded" flag should not be copied to prevent a
187 * unwanted downgrade (Bug 1885949).
188 * @param aHttpsOnlyStatus The HTTPS-Only status of the top-level document.
189 * @return The HTTPS-Only status that the sub-resource/document should
190 * receive.
192 static uint32_t GetStatusForSubresourceLoad(uint32_t aHttpsOnlyStatus);
195 * When a downgrade is happening because of HTTPS-First, this function will
196 * update the load state for the new load accordingly. This includes
197 * information about the downgrade for later telemetry use.
198 * @param aDocumentLoadListener The calling document load listener.
199 * @param aLoadState The load state to be updated
201 static void UpdateLoadStateAfterHTTPSFirstDowngrade(
202 mozilla::net::DocumentLoadListener* aDocumentLoadListener,
203 nsDocShellLoadState* aLoadState);
206 * When a load is successful, this should be called by the document load
207 * listener. In two cases, telemetry is then recorded:
208 * a) If downgrade data has been passed, the passed load is a successful
209 * downgrade, which means telemetry based on the downgrade data will be
210 * submitted.
211 * b) If the passed load info indicates that this load has been upgraded by
212 * HTTPS-First, this means the upgrade was successful, which will be
213 * recorded to telemetry.
215 static void SubmitHTTPSFirstTelemetry(
216 nsCOMPtr<nsILoadInfo> const& aLoadInfo,
217 RefPtr<HTTPSFirstDowngradeData> const& aHttpsFirstDowngradeData);
219 private:
221 * Checks if it can be ruled out that the error has something
222 * to do with an HTTPS upgrade.
223 * @param aError error code
224 * @return true if error is unrelated to the upgrade
226 static bool HttpsUpgradeUnrelatedErrorCode(nsresult aError);
228 * Logs localized message to either content console or browser console
229 * @param aMessage Message to log
230 * @param aFlags Logging Flag (see nsIScriptError)
231 * @param aLoadInfo The loadinfo of the request.
232 * @param [aURI] Optional: URI to log
233 * @param [aUseHttpsFirst] Optional: Log using HTTPS-First (vs. HTTPS-Only)
235 static void LogMessage(const nsAString& aMessage, uint32_t aFlags,
236 nsILoadInfo* aLoadInfo, nsIURI* aURI = nullptr,
237 bool aUseHttpsFirst = false);
240 * Checks whether the URI ends with .onion
241 * @param aURI URI object
242 * @return true if the URI is an Onion URI
244 static bool OnionException(nsIURI* aURI);
247 * Checks whether the URI is a loopback- or local-IP
248 * @param aURI URI object
249 * @return true if the URI is either loopback or local
251 static bool LoopbackOrLocalException(nsIURI* aURI);
254 * Checks whether the host of the URI ends with a suffix that is not in the
255 * public suffix list.
256 * @param aURI URI object
257 * @return true if the host of the URI ends with a unknown suffix
259 static bool UnknownPublicSuffixException(nsIURI* aURI);
263 * Helper class to perform an http request with a N milliseconds
264 * delay. If that http request is 'receiving data' before the
265 * upgraded https request, then it's a strong indicator that
266 * the https request will result in a timeout and hence we
267 * cancel the https request which will result in displaying
268 * the exception page.
270 class TestHTTPAnswerRunnable final : public mozilla::Runnable,
271 public nsIStreamListener,
272 public nsIInterfaceRequestor,
273 public nsITimerCallback {
274 public:
275 // TestHTTPAnswerRunnable needs to implement all these channel related
276 // interfaces because otherwise our Necko code is not happy, but we
277 // really only care about ::OnStartRequest.
278 NS_DECL_ISUPPORTS_INHERITED
279 NS_DECL_NSIRUNNABLE
280 NS_DECL_NSIREQUESTOBSERVER
281 NS_DECL_NSISTREAMLISTENER
282 NS_DECL_NSIINTERFACEREQUESTOR
283 NS_DECL_NSITIMERCALLBACK
285 explicit TestHTTPAnswerRunnable(
286 nsIURI* aURI, mozilla::net::DocumentLoadListener* aDocumentLoadListener);
288 protected:
289 ~TestHTTPAnswerRunnable() = default;
291 private:
293 * Checks whether the HTTP background request results in a redirect
294 * to the same upgraded top-level HTTPS URL
295 * @param aChannel a nsIHttpChannel object
296 * @return true if the backgroundchannel is redirected
298 static bool IsBackgroundRequestRedirected(nsIHttpChannel* aChannel);
300 RefPtr<nsIURI> mURI;
301 // We're keeping a reference to DocumentLoadListener instead of a specific
302 // channel, because the current top-level channel can change (for example
303 // through redirects)
304 RefPtr<mozilla::net::DocumentLoadListener> mDocumentLoadListener;
305 RefPtr<nsITimer> mTimer;
309 * Data about a HTTPS-First downgrade used for Telemetry. We need to store this
310 * instead of directly submitting it when deciding to downgrade, because it is
311 * only interesting for us if the downgraded load is actually succesful.
313 struct HTTPSFirstDowngradeData
314 : public mozilla::RefCounted<HTTPSFirstDowngradeData> {
315 MOZ_DECLARE_REFCOUNTED_TYPENAME(HTTPSFirstDowngradeData)
316 mozilla::TimeDuration downgradeTime;
317 bool isOnTimer = false;
318 bool isSchemeless = false;
321 #endif /* nsHTTPSOnlyUtils_h___ */