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 #include "nsAboutProtocolUtils.h"
9 #include "nsContentSecurityManager.h"
10 #include "nsContentSecurityUtils.h"
11 #include "nsContentPolicyUtils.h"
13 #include "nsDataHandler.h"
14 #include "nsIChannel.h"
15 #include "nsIContentPolicy.h"
16 #include "nsIHttpChannelInternal.h"
18 #include "nsIStreamListener.h"
19 #include "nsILoadInfo.h"
20 #include "nsIMIMEService.h"
21 #include "nsIOService.h"
22 #include "nsContentUtils.h"
23 #include "nsCORSListenerProxy.h"
24 #include "nsIParentChannel.h"
25 #include "nsIRedirectHistoryEntry.h"
26 #include "nsIXULRuntime.h"
27 #include "nsNetUtil.h"
28 #include "nsReadableUtils.h"
29 #include "nsSandboxFlags.h"
30 #include "nsIXPConnect.h"
32 #include "mozilla/BasePrincipal.h"
33 #include "mozilla/ClearOnShutdown.h"
34 #include "mozilla/CmdLineAndEnvUtils.h"
35 #include "mozilla/dom/Element.h"
36 #include "mozilla/dom/nsMixedContentBlocker.h"
37 #include "mozilla/dom/BrowserChild.h"
38 #include "mozilla/dom/ContentChild.h"
39 #include "mozilla/dom/ContentParent.h"
40 #include "mozilla/dom/Document.h"
41 #include "mozilla/extensions/WebExtensionPolicy.h"
42 #include "mozilla/Components.h"
43 #include "mozilla/ExtensionPolicyService.h"
44 #include "mozilla/Logging.h"
45 #include "mozilla/Maybe.h"
46 #include "mozilla/Preferences.h"
47 #include "mozilla/StaticPrefs_dom.h"
48 #include "mozilla/StaticPrefs_security.h"
49 #include "mozilla/Telemetry.h"
50 #include "mozilla/TelemetryComms.h"
51 #include "xpcpublic.h"
52 #include "nsMimeTypes.h"
55 #include "js/RegExp.h"
57 using namespace mozilla
;
58 using namespace mozilla::dom
;
59 using namespace mozilla::Telemetry
;
61 NS_IMPL_ISUPPORTS(nsContentSecurityManager
, nsIContentSecurityManager
,
64 mozilla::LazyLogModule
sCSMLog("CSMLog");
66 // These first two are used for off-the-main-thread checks of
67 // general.config.filename
68 // (which can't be checked off-main-thread).
69 Atomic
<bool, mozilla::Relaxed
> sJSHacksChecked(false);
70 Atomic
<bool, mozilla::Relaxed
> sJSHacksPresent(false);
71 Atomic
<bool, mozilla::Relaxed
> sCSSHacksChecked(false);
72 Atomic
<bool, mozilla::Relaxed
> sCSSHacksPresent(false);
73 Atomic
<bool, mozilla::Relaxed
> sTelemetryEventEnabled(false);
76 bool nsContentSecurityManager::AllowTopLevelNavigationToDataURI(
77 nsIChannel
* aChannel
) {
78 // Let's block all toplevel document navigations to a data: URI.
79 // In all cases where the toplevel document is navigated to a
80 // data: URI the triggeringPrincipal is a contentPrincipal, or
81 // a NullPrincipal. In other cases, e.g. typing a data: URL into
82 // the URL-Bar, the triggeringPrincipal is a SystemPrincipal;
83 // we don't want to block those loads. Only exception, loads coming
84 // from an external applicaton (e.g. Thunderbird) don't load
85 // using a contentPrincipal, but we want to block those loads.
86 if (!StaticPrefs::security_data_uri_block_toplevel_data_uri_navigations()) {
89 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
90 if (loadInfo
->GetExternalContentPolicyType() !=
91 ExtContentPolicy::TYPE_DOCUMENT
) {
94 if (loadInfo
->GetForceAllowDataURI()) {
95 // if the loadinfo explicitly allows the data URI navigation, let's allow it
100 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
101 NS_ENSURE_SUCCESS(rv
, true);
102 bool isDataURI
= uri
->SchemeIs("data");
108 rv
= uri
->GetSpec(spec
);
109 NS_ENSURE_SUCCESS(rv
, true);
110 nsAutoCString contentType
;
112 rv
= nsDataHandler::ParseURI(spec
, contentType
, nullptr, base64
, nullptr);
113 NS_ENSURE_SUCCESS(rv
, true);
115 // Allow data: images as long as they are not SVGs
116 if (StringBeginsWith(contentType
, "image/"_ns
) &&
117 !contentType
.EqualsLiteral("image/svg+xml")) {
120 // Allow all data: PDFs. or JSON documents
121 if (contentType
.EqualsLiteral(APPLICATION_JSON
) ||
122 contentType
.EqualsLiteral(TEXT_JSON
) ||
123 contentType
.EqualsLiteral(APPLICATION_PDF
)) {
126 // Redirecting to a toplevel data: URI is not allowed, hence we make
127 // sure the RedirectChain is empty.
128 if (!loadInfo
->GetLoadTriggeredFromExternal() &&
129 loadInfo
->TriggeringPrincipal()->IsSystemPrincipal() &&
130 loadInfo
->RedirectChain().IsEmpty()) {
134 ReportBlockedDataURI(uri
, loadInfo
);
139 void nsContentSecurityManager::ReportBlockedDataURI(nsIURI
* aURI
,
140 nsILoadInfo
* aLoadInfo
,
142 // We're going to block the request, construct the localized error message to
143 // report to the console.
144 nsAutoCString dataSpec
;
145 aURI
->GetSpec(dataSpec
);
146 if (dataSpec
.Length() > 50) {
147 dataSpec
.Truncate(50);
148 dataSpec
.AppendLiteral("...");
150 AutoTArray
<nsString
, 1> params
;
151 CopyUTF8toUTF16(NS_UnescapeURL(dataSpec
), *params
.AppendElement());
152 nsAutoString errorText
;
153 const char* stringID
=
154 aIsRedirect
? "BlockRedirectToDataURI" : "BlockTopLevelDataURINavigation";
155 nsresult rv
= nsContentUtils::FormatLocalizedString(
156 nsContentUtils::eSECURITY_PROPERTIES
, stringID
, params
, errorText
);
161 // Report the localized error message to the console for the loading
162 // BrowsingContext's current inner window.
163 RefPtr
<BrowsingContext
> target
= aLoadInfo
->GetBrowsingContext();
164 nsContentUtils::ReportToConsoleByWindowID(
165 errorText
, nsIScriptError::warningFlag
, "DATA_URI_BLOCKED"_ns
,
166 target
? target
->GetCurrentInnerWindowId() : 0);
170 bool nsContentSecurityManager::AllowInsecureRedirectToDataURI(
171 nsIChannel
* aNewChannel
) {
172 nsCOMPtr
<nsILoadInfo
> loadInfo
= aNewChannel
->LoadInfo();
173 if (loadInfo
->GetExternalContentPolicyType() !=
174 ExtContentPolicy::TYPE_SCRIPT
) {
177 nsCOMPtr
<nsIURI
> newURI
;
178 nsresult rv
= NS_GetFinalChannelURI(aNewChannel
, getter_AddRefs(newURI
));
179 if (NS_FAILED(rv
) || !newURI
) {
182 bool isDataURI
= newURI
->SchemeIs("data");
187 // Web Extensions are exempt from that restriction and are allowed to redirect
188 // a channel to a data: URI. When a web extension redirects a channel, we set
189 // a flag on the loadInfo which allows us to identify such redirects here.
190 if (loadInfo
->GetAllowInsecureRedirectToDataURI()) {
194 ReportBlockedDataURI(newURI
, loadInfo
, true);
199 static nsresult
ValidateSecurityFlags(nsILoadInfo
* aLoadInfo
) {
200 nsSecurityFlags securityMode
= aLoadInfo
->GetSecurityMode();
202 // We should never perform a security check on a loadInfo that uses the flag
203 // SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, because that is only used for
204 // temporary loadInfos used for explicit nsIContentPolicy checks, but never be
205 // set as a security flag on an actual channel.
207 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
&&
208 securityMode
!= nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
&&
210 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
&&
211 securityMode
!= nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
&&
212 securityMode
!= nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
) {
215 "need one securityflag from nsILoadInfo to perform security checks");
216 return NS_ERROR_FAILURE
;
219 // all good, found the right security flags
223 static already_AddRefed
<nsIPrincipal
> GetExtensionSandboxPrincipal(
224 nsILoadInfo
* aLoadInfo
) {
225 // An extension is allowed to load resources from itself when its pages are
226 // loaded into a sandboxed frame. Extension resources in a sandbox have
227 // a null principal and no access to extension APIs. See "sandbox" in
228 // MDN extension docs for more information.
229 if (!aLoadInfo
->TriggeringPrincipal()->GetIsNullPrincipal()) {
232 RefPtr
<Document
> doc
;
233 aLoadInfo
->GetLoadingDocument(getter_AddRefs(doc
));
234 if (!doc
|| !(doc
->GetSandboxFlags() & SANDBOXED_ORIGIN
)) {
238 // node principal is also a null principal here, so we need to
239 // create a principal using documentURI, which is the moz-extension
240 // uri for the page if this is an extension sandboxed page.
241 nsCOMPtr
<nsIPrincipal
> docPrincipal
= BasePrincipal::CreateContentPrincipal(
242 doc
->GetDocumentURI(), doc
->NodePrincipal()->OriginAttributesRef());
244 if (!BasePrincipal::Cast(docPrincipal
)->AddonPolicy()) {
247 return docPrincipal
.forget();
250 static bool IsImageLoadInEditorAppType(nsILoadInfo
* aLoadInfo
) {
251 // Editor apps get special treatment here, editors can load images
252 // from anywhere. This allows editor to insert images from file://
253 // into documents that are being edited.
254 nsContentPolicyType type
= aLoadInfo
->InternalContentPolicyType();
255 if (type
!= nsIContentPolicy::TYPE_INTERNAL_IMAGE
&&
256 type
!= nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD
&&
257 type
!= nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON
&&
258 type
!= nsIContentPolicy::TYPE_IMAGESET
) {
262 auto appType
= nsIDocShell::APP_TYPE_UNKNOWN
;
263 nsINode
* node
= aLoadInfo
->LoadingNode();
267 Document
* doc
= node
->OwnerDoc();
272 nsCOMPtr
<nsIDocShellTreeItem
> docShellTreeItem
= doc
->GetDocShell();
273 if (!docShellTreeItem
) {
277 nsCOMPtr
<nsIDocShellTreeItem
> root
;
278 docShellTreeItem
->GetInProcessRootTreeItem(getter_AddRefs(root
));
279 nsCOMPtr
<nsIDocShell
> docShell(do_QueryInterface(root
));
281 appType
= docShell
->GetAppType();
284 return appType
== nsIDocShell::APP_TYPE_EDITOR
;
287 static nsresult
DoCheckLoadURIChecks(nsIURI
* aURI
, nsILoadInfo
* aLoadInfo
) {
288 // In practice, these DTDs are just used for localization, so applying the
289 // same principal check as Fluent.
290 if (aLoadInfo
->InternalContentPolicyType() ==
291 nsIContentPolicy::TYPE_INTERNAL_DTD
) {
292 RefPtr
<Document
> doc
;
293 aLoadInfo
->GetLoadingDocument(getter_AddRefs(doc
));
294 bool allowed
= false;
295 aLoadInfo
->TriggeringPrincipal()->IsL10nAllowed(
296 doc
? doc
->GetDocumentURI() : nullptr, &allowed
);
298 return allowed
? NS_OK
: NS_ERROR_DOM_BAD_URI
;
301 // This is used in order to allow a privileged DOMParser to parse documents
302 // that need to access localization DTDs. We just allow through
303 // TYPE_INTERNAL_FORCE_ALLOWED_DTD no matter what the triggering principal is.
304 if (aLoadInfo
->InternalContentPolicyType() ==
305 nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD
) {
309 if (IsImageLoadInEditorAppType(aLoadInfo
)) {
313 nsCOMPtr
<nsIPrincipal
> triggeringPrincipal
= aLoadInfo
->TriggeringPrincipal();
314 nsCOMPtr
<nsIPrincipal
> addonPrincipal
=
315 GetExtensionSandboxPrincipal(aLoadInfo
);
316 if (addonPrincipal
) {
317 // call CheckLoadURIWithPrincipal() as below to continue other checks, but
318 // with the addon principal.
319 triggeringPrincipal
= addonPrincipal
;
322 // Only call CheckLoadURIWithPrincipal() using the TriggeringPrincipal and not
323 // the LoadingPrincipal when SEC_ALLOW_CROSS_ORIGIN_* security flags are set,
324 // to allow, e.g. user stylesheets to load chrome:// URIs.
325 return nsContentUtils::GetSecurityManager()->CheckLoadURIWithPrincipal(
326 triggeringPrincipal
, aURI
, aLoadInfo
->CheckLoadURIFlags(),
327 aLoadInfo
->GetInnerWindowID());
330 static bool URIHasFlags(nsIURI
* aURI
, uint32_t aURIFlags
) {
332 nsresult rv
= NS_URIChainHasFlags(aURI
, aURIFlags
, &hasFlags
);
333 NS_ENSURE_SUCCESS(rv
, false);
338 static nsresult
DoSOPChecks(nsIURI
* aURI
, nsILoadInfo
* aLoadInfo
,
339 nsIChannel
* aChannel
) {
340 if (aLoadInfo
->GetAllowChrome() &&
341 (URIHasFlags(aURI
, nsIProtocolHandler::URI_IS_UI_RESOURCE
) ||
342 nsContentUtils::SchemeIs(aURI
, "moz-safe-about"))) {
343 // UI resources are allowed.
344 return DoCheckLoadURIChecks(aURI
, aLoadInfo
);
347 if (NS_HasBeenCrossOrigin(aChannel
, true)) {
348 NS_SetRequestBlockingReason(aLoadInfo
,
349 nsILoadInfo::BLOCKING_REASON_NOT_SAME_ORIGIN
);
350 return NS_ERROR_DOM_BAD_URI
;
356 static nsresult
DoCORSChecks(nsIChannel
* aChannel
, nsILoadInfo
* aLoadInfo
,
357 nsCOMPtr
<nsIStreamListener
>& aInAndOutListener
) {
358 MOZ_RELEASE_ASSERT(aInAndOutListener
,
359 "can not perform CORS checks without a listener");
361 // No need to set up CORS if TriggeringPrincipal is the SystemPrincipal.
362 if (aLoadInfo
->TriggeringPrincipal()->IsSystemPrincipal()) {
366 // We use the triggering principal here, rather than the loading principal
367 // to ensure that anonymous CORS content in the browser resources and in
368 // WebExtensions is allowed to load.
369 nsIPrincipal
* principal
= aLoadInfo
->TriggeringPrincipal();
370 RefPtr
<nsCORSListenerProxy
> corsListener
= new nsCORSListenerProxy(
371 aInAndOutListener
, principal
,
372 aLoadInfo
->GetCookiePolicy() == nsILoadInfo::SEC_COOKIES_INCLUDE
);
373 // XXX: @arg: DataURIHandling::Allow
374 // lets use DataURIHandling::Allow for now and then decide on callsite basis.
376 // http://mxr.mozilla.org/mozilla-central/source/dom/security/nsCORSListenerProxy.h#33
377 nsresult rv
= corsListener
->Init(aChannel
, DataURIHandling::Allow
);
378 NS_ENSURE_SUCCESS(rv
, rv
);
379 aInAndOutListener
= corsListener
;
383 static nsresult
DoContentSecurityChecks(nsIChannel
* aChannel
,
384 nsILoadInfo
* aLoadInfo
) {
385 ExtContentPolicyType contentPolicyType
=
386 aLoadInfo
->GetExternalContentPolicyType();
388 nsCOMPtr
<nsIURI
> uri
;
389 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
390 NS_ENSURE_SUCCESS(rv
, rv
);
392 switch (contentPolicyType
) {
393 case ExtContentPolicy::TYPE_XMLHTTPREQUEST
: {
396 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
397 MOZ_ASSERT(!node
|| node
->NodeType() == nsINode::DOCUMENT_NODE
,
398 "type_xml requires requestingContext of type Document");
404 case ExtContentPolicy::TYPE_OBJECT_SUBREQUEST
: {
407 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
409 !node
|| node
->NodeType() == nsINode::ELEMENT_NODE
,
410 "type_subrequest requires requestingContext of type Element");
416 case ExtContentPolicy::TYPE_DTD
: {
419 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
420 MOZ_ASSERT(!node
|| node
->NodeType() == nsINode::DOCUMENT_NODE
,
421 "type_dtd requires requestingContext of type Document");
427 case ExtContentPolicy::TYPE_MEDIA
: {
430 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
431 MOZ_ASSERT(!node
|| node
->NodeType() == nsINode::ELEMENT_NODE
,
432 "type_media requires requestingContext of type Element");
438 case ExtContentPolicy::TYPE_WEBSOCKET
: {
439 // Websockets have to use the proxied URI:
440 // ws:// instead of http:// for CSP checks
441 nsCOMPtr
<nsIHttpChannelInternal
> httpChannelInternal
=
442 do_QueryInterface(aChannel
);
443 MOZ_ASSERT(httpChannelInternal
);
444 if (httpChannelInternal
) {
445 rv
= httpChannelInternal
->GetProxyURI(getter_AddRefs(uri
));
446 MOZ_ASSERT(NS_SUCCEEDED(rv
));
451 case ExtContentPolicy::TYPE_XSLT
: {
454 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
455 MOZ_ASSERT(!node
|| node
->NodeType() == nsINode::DOCUMENT_NODE
,
456 "type_xslt requires requestingContext of type Document");
462 case ExtContentPolicy::TYPE_BEACON
: {
465 nsCOMPtr
<nsINode
> node
= aLoadInfo
->LoadingNode();
466 MOZ_ASSERT(!node
|| node
->NodeType() == nsINode::DOCUMENT_NODE
,
467 "type_beacon requires requestingContext of type Document");
473 case ExtContentPolicy::TYPE_OTHER
:
474 case ExtContentPolicy::TYPE_SCRIPT
:
475 case ExtContentPolicy::TYPE_IMAGE
:
476 case ExtContentPolicy::TYPE_STYLESHEET
:
477 case ExtContentPolicy::TYPE_OBJECT
:
478 case ExtContentPolicy::TYPE_DOCUMENT
:
479 case ExtContentPolicy::TYPE_SUBDOCUMENT
:
480 case ExtContentPolicy::TYPE_PING
:
481 case ExtContentPolicy::TYPE_FONT
:
482 case ExtContentPolicy::TYPE_UA_FONT
:
483 case ExtContentPolicy::TYPE_CSP_REPORT
:
484 case ExtContentPolicy::TYPE_WEB_MANIFEST
:
485 case ExtContentPolicy::TYPE_FETCH
:
486 case ExtContentPolicy::TYPE_IMAGESET
:
487 case ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD
:
488 case ExtContentPolicy::TYPE_SPECULATIVE
:
489 case ExtContentPolicy::TYPE_PROXIED_WEBRTC_MEDIA
:
490 case ExtContentPolicy::TYPE_WEB_TRANSPORT
:
491 case ExtContentPolicy::TYPE_WEB_IDENTITY
:
494 case ExtContentPolicy::TYPE_INVALID
:
496 "can not perform security check without a valid contentType");
497 // Do not add default: so that compilers can catch the missing case.
500 int16_t shouldLoad
= nsIContentPolicy::ACCEPT
;
501 rv
= NS_CheckContentLoadPolicy(uri
, aLoadInfo
, &shouldLoad
,
502 nsContentUtils::GetContentPolicy());
504 if (NS_FAILED(rv
) || NS_CP_REJECTED(shouldLoad
)) {
505 NS_SetRequestBlockingReasonIfNull(
506 aLoadInfo
, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_GENERAL
);
508 if (NS_SUCCEEDED(rv
) &&
509 (contentPolicyType
== ExtContentPolicy::TYPE_DOCUMENT
||
510 contentPolicyType
== ExtContentPolicy::TYPE_SUBDOCUMENT
)) {
511 if (shouldLoad
== nsIContentPolicy::REJECT_TYPE
) {
512 // for docshell loads we might have to return SHOW_ALT.
513 return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT
;
515 if (shouldLoad
== nsIContentPolicy::REJECT_POLICY
) {
516 return NS_ERROR_BLOCKED_BY_POLICY
;
519 return NS_ERROR_CONTENT_BLOCKED
;
525 static void LogHTTPSOnlyInfo(nsILoadInfo
* aLoadInfo
) {
526 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" httpsOnlyFirstStatus:"));
527 uint32_t httpsOnlyStatus
= aLoadInfo
->GetHttpsOnlyStatus();
529 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_UNINITIALIZED
) {
530 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" - HTTPS_ONLY_UNINITIALIZED"));
532 if (httpsOnlyStatus
&
533 nsILoadInfo::HTTPS_ONLY_UPGRADED_LISTENER_NOT_REGISTERED
) {
534 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
535 (" - HTTPS_ONLY_UPGRADED_LISTENER_NOT_REGISTERED"));
537 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_UPGRADED_LISTENER_REGISTERED
) {
538 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
539 (" - HTTPS_ONLY_UPGRADED_LISTENER_REGISTERED"));
541 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_EXEMPT
) {
542 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" - HTTPS_ONLY_EXEMPT"));
544 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_TOP_LEVEL_LOAD_IN_PROGRESS
) {
545 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
546 (" - HTTPS_ONLY_TOP_LEVEL_LOAD_IN_PROGRESS"));
548 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_DOWNLOAD_IN_PROGRESS
) {
549 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
550 (" - HTTPS_ONLY_DOWNLOAD_IN_PROGRESS"));
552 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_DO_NOT_LOG_TO_CONSOLE
) {
553 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
554 (" - HTTPS_ONLY_DO_NOT_LOG_TO_CONSOLE"));
556 if (httpsOnlyStatus
& nsILoadInfo::HTTPS_ONLY_UPGRADED_HTTPS_FIRST
) {
557 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
558 (" - HTTPS_ONLY_UPGRADED_HTTPS_FIRST"));
562 static void LogPrincipal(nsIPrincipal
* aPrincipal
,
563 const nsAString
& aPrincipalName
,
564 const uint8_t& aNestingLevel
) {
565 nsPrintfCString
aIndentationString("%*s", aNestingLevel
* 2, "");
567 if (aPrincipal
&& aPrincipal
->IsSystemPrincipal()) {
568 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
569 ("%s%s: SystemPrincipal\n", aIndentationString
.get(),
570 NS_ConvertUTF16toUTF8(aPrincipalName
).get()));
574 if (aPrincipal
->GetIsNullPrincipal()) {
575 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
576 ("%s%s: NullPrincipal\n", aIndentationString
.get(),
577 NS_ConvertUTF16toUTF8(aPrincipalName
).get()));
580 if (aPrincipal
->GetIsExpandedPrincipal()) {
581 nsCOMPtr
<nsIExpandedPrincipal
> expanded(do_QueryInterface(aPrincipal
));
582 nsAutoCString origin
;
583 origin
.AssignLiteral("[Expanded Principal [");
585 StringJoinAppend(origin
, ", "_ns
, expanded
->AllowList(),
586 [](nsACString
& dest
, nsIPrincipal
* principal
) {
587 nsAutoCString subOrigin
;
588 DebugOnly
<nsresult
> rv
=
589 principal
->GetOrigin(subOrigin
);
590 MOZ_ASSERT(NS_SUCCEEDED(rv
));
591 dest
.Append(subOrigin
);
594 origin
.AppendLiteral("]]");
596 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
597 ("%s%s: %s\n", aIndentationString
.get(),
598 NS_ConvertUTF16toUTF8(aPrincipalName
).get(), origin
.get()));
601 nsAutoCString principalSpec
;
602 aPrincipal
->GetAsciiSpec(principalSpec
);
603 if (aPrincipalName
.IsEmpty()) {
604 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
605 ("%s - \"%s\"\n", aIndentationString
.get(), principalSpec
.get()));
608 sCSMLog
, LogLevel::Debug
,
609 ("%s%s: \"%s\"\n", aIndentationString
.get(),
610 NS_ConvertUTF16toUTF8(aPrincipalName
).get(), principalSpec
.get()));
614 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
615 ("%s%s: nullptr\n", aIndentationString
.get(),
616 NS_ConvertUTF16toUTF8(aPrincipalName
).get()));
619 static void LogSecurityFlags(nsSecurityFlags securityFlags
) {
620 struct DebugSecFlagType
{
621 unsigned long secFlag
;
622 char secTypeStr
[128];
624 static const DebugSecFlagType secTypes
[] = {
625 {nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK
,
626 "SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK"},
627 {nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
,
628 "SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT"},
629 {nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
,
630 "SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED"},
631 {nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
,
632 "SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT"},
633 {nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
,
634 "SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL"},
635 {nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
,
636 "SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT"},
637 {nsILoadInfo::SEC_COOKIES_DEFAULT
, "SEC_COOKIES_DEFAULT"},
638 {nsILoadInfo::SEC_COOKIES_INCLUDE
, "SEC_COOKIES_INCLUDE"},
639 {nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
, "SEC_COOKIES_SAME_ORIGIN"},
640 {nsILoadInfo::SEC_COOKIES_OMIT
, "SEC_COOKIES_OMIT"},
641 {nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL
, "SEC_FORCE_INHERIT_PRINCIPAL"},
642 {nsILoadInfo::SEC_ABOUT_BLANK_INHERITS
, "SEC_ABOUT_BLANK_INHERITS"},
643 {nsILoadInfo::SEC_ALLOW_CHROME
, "SEC_ALLOW_CHROME"},
644 {nsILoadInfo::SEC_DISALLOW_SCRIPT
, "SEC_DISALLOW_SCRIPT"},
645 {nsILoadInfo::SEC_DONT_FOLLOW_REDIRECTS
, "SEC_DONT_FOLLOW_REDIRECTS"},
646 {nsILoadInfo::SEC_LOAD_ERROR_PAGE
, "SEC_LOAD_ERROR_PAGE"},
647 {nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER
,
648 "SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER"}};
650 for (const DebugSecFlagType
& flag
: secTypes
) {
651 if (securityFlags
& flag
.secFlag
) {
652 // the logging level should be in sync with the logging level in
653 // DebugDoContentSecurityCheck()
654 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" - %s\n", flag
.secTypeStr
));
658 static void DebugDoContentSecurityCheck(nsIChannel
* aChannel
,
659 nsILoadInfo
* aLoadInfo
) {
660 nsCOMPtr
<nsIHttpChannel
> httpChannel(do_QueryInterface(aChannel
));
662 MOZ_LOG(sCSMLog
, LogLevel::Debug
, ("\n#DebugDoContentSecurityCheck Begin\n"));
664 // we only log http channels, unless loglevel is 5.
665 if (httpChannel
|| MOZ_LOG_TEST(sCSMLog
, LogLevel::Verbose
)) {
666 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, ("doContentSecurityCheck:\n"));
668 nsAutoCString remoteType
;
669 if (XRE_IsParentProcess()) {
670 nsCOMPtr
<nsIParentChannel
> parentChannel
;
671 NS_QueryNotificationCallbacks(aChannel
, parentChannel
);
673 parentChannel
->GetRemoteType(remoteType
);
677 mozilla::dom::ContentChild::GetSingleton()->GetRemoteType());
679 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
680 (" processType: \"%s\"\n", remoteType
.get()));
682 nsCOMPtr
<nsIURI
> channelURI
;
683 nsAutoCString channelSpec
;
684 nsAutoCString channelMethod
;
685 NS_GetFinalChannelURI(aChannel
, getter_AddRefs(channelURI
));
687 channelURI
->GetSpec(channelSpec
);
689 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
690 (" channelURI: \"%s\"\n", channelSpec
.get()));
692 // Log HTTP-specific things
695 rv
= httpChannel
->GetRequestMethod(channelMethod
);
696 if (!NS_FAILED(rv
)) {
697 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
698 (" httpMethod: %s\n", channelMethod
.get()));
703 nsCOMPtr
<nsIPrincipal
> requestPrincipal
= aLoadInfo
->TriggeringPrincipal();
704 LogPrincipal(aLoadInfo
->GetLoadingPrincipal(), u
"loadingPrincipal"_ns
, 1);
705 LogPrincipal(requestPrincipal
, u
"triggeringPrincipal"_ns
, 1);
706 LogPrincipal(aLoadInfo
->PrincipalToInherit(), u
"principalToInherit"_ns
, 1);
708 // Log Redirect Chain
709 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" redirectChain:\n"));
710 for (nsIRedirectHistoryEntry
* redirectHistoryEntry
:
711 aLoadInfo
->RedirectChain()) {
712 nsCOMPtr
<nsIPrincipal
> principal
;
713 redirectHistoryEntry
->GetPrincipal(getter_AddRefs(principal
));
714 LogPrincipal(principal
, u
""_ns
, 2);
717 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
718 (" internalContentPolicyType: %s\n",
719 NS_CP_ContentTypeName(aLoadInfo
->InternalContentPolicyType())));
720 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
721 (" externalContentPolicyType: %s\n",
722 NS_CP_ContentTypeName(aLoadInfo
->GetExternalContentPolicyType())));
723 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
724 (" upgradeInsecureRequests: %s\n",
725 aLoadInfo
->GetUpgradeInsecureRequests() ? "true" : "false"));
726 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
727 (" initialSecurityChecksDone: %s\n",
728 aLoadInfo
->GetInitialSecurityCheckDone() ? "true" : "false"));
729 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
730 (" allowDeprecatedSystemRequests: %s\n",
731 aLoadInfo
->GetAllowDeprecatedSystemRequests() ? "true" : "false"));
732 MOZ_LOG(sCSMLog
, LogLevel::Verbose
,
733 (" wasSchemeless: %s\n",
734 aLoadInfo
->GetWasSchemelessInput() ? "true" : "false"));
736 // Log CSPrequestPrincipal
737 nsCOMPtr
<nsIContentSecurityPolicy
> csp
= aLoadInfo
->GetCsp();
738 MOZ_LOG(sCSMLog
, LogLevel::Debug
, (" CSP:"));
740 nsAutoString parsedPolicyStr
;
742 csp
->GetPolicyCount(&count
);
743 for (uint32_t i
= 0; i
< count
; ++i
) {
744 csp
->GetPolicyString(i
, parsedPolicyStr
);
745 // we need to add quotation marks, as otherwise yaml parsers may fail
746 // with CSP directives
747 // no need to escape quote marks in the parsed policy string, as URLs in
748 // there are already encoded
749 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
750 (" - \"%s\"\n", NS_ConvertUTF16toUTF8(parsedPolicyStr
).get()));
755 MOZ_LOG(sCSMLog
, LogLevel::Verbose
, (" securityFlags:"));
756 LogSecurityFlags(aLoadInfo
->GetSecurityFlags());
758 LogHTTPSOnlyInfo(aLoadInfo
);
760 MOZ_LOG(sCSMLog
, LogLevel::Debug
, ("\n#DebugDoContentSecurityCheck End\n"));
765 void nsContentSecurityManager::MeasureUnexpectedPrivilegedLoads(
766 nsILoadInfo
* aLoadInfo
, nsIURI
* aFinalURI
, const nsACString
& aRemoteType
) {
767 if (!StaticPrefs::dom_security_unexpected_system_load_telemetry_enabled()) {
770 nsContentSecurityUtils::DetectJsHacks();
771 nsContentSecurityUtils::DetectCssHacks();
772 // The detection only work on the main-thread.
773 // To avoid races and early reports, we need to ensure the checks actually
775 if (MOZ_UNLIKELY(sJSHacksPresent
|| !sJSHacksChecked
|| sCSSHacksPresent
||
776 !sCSSHacksChecked
)) {
780 ExtContentPolicyType contentPolicyType
=
781 aLoadInfo
->GetExternalContentPolicyType();
782 // restricting reported types to script, styles and documents
783 // to be continued in follow-ups of bug 1697163.
784 if (contentPolicyType
!= ExtContentPolicyType::TYPE_SCRIPT
&&
785 contentPolicyType
!= ExtContentPolicyType::TYPE_STYLESHEET
&&
786 contentPolicyType
!= ExtContentPolicyType::TYPE_DOCUMENT
) {
790 // Gather redirected schemes in string
791 nsAutoCString loggedRedirects
;
792 const nsTArray
<nsCOMPtr
<nsIRedirectHistoryEntry
>>& redirects
=
793 aLoadInfo
->RedirectChain();
794 if (!redirects
.IsEmpty()) {
795 nsCOMPtr
<nsIRedirectHistoryEntry
> end
= redirects
.LastElement();
796 for (nsIRedirectHistoryEntry
* entry
: redirects
) {
797 nsCOMPtr
<nsIPrincipal
> principal
;
798 entry
->GetPrincipal(getter_AddRefs(principal
));
800 nsAutoCString scheme
;
801 principal
->GetScheme(scheme
);
802 loggedRedirects
.Append(scheme
);
804 loggedRedirects
.AppendLiteral(", ");
810 nsAutoCString uriString
;
812 aFinalURI
->GetAsciiSpec(uriString
);
814 uriString
.AssignLiteral("");
816 FilenameTypeAndDetails fileNameTypeAndDetails
=
817 nsContentSecurityUtils::FilenameToFilenameType(
818 NS_ConvertUTF8toUTF16(uriString
), true);
820 nsCString loggedFileDetails
= "unknown"_ns
;
821 if (fileNameTypeAndDetails
.second
.isSome()) {
822 loggedFileDetails
.Assign(
823 NS_ConvertUTF16toUTF8(fileNameTypeAndDetails
.second
.value()));
825 // sanitize remoteType because it may contain sensitive
826 // info, like URLs. e.g. `webIsolated=https://example.com`
827 nsAutoCString
loggedRemoteType(dom::RemoteTypePrefix(aRemoteType
));
828 nsAutoCString
loggedContentType(NS_CP_ContentTypeName(contentPolicyType
));
830 MOZ_LOG(sCSMLog
, LogLevel::Debug
, ("UnexpectedPrivilegedLoadTelemetry:\n"));
831 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
832 ("- contentType: %s\n", loggedContentType
.get()));
833 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
834 ("- URL (not to be reported): %s\n", uriString
.get()));
835 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
836 ("- remoteType: %s\n", loggedRemoteType
.get()));
837 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
838 ("- fileInfo: %s\n", fileNameTypeAndDetails
.first
.get()));
839 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
840 ("- fileDetails: %s\n", loggedFileDetails
.get()));
841 MOZ_LOG(sCSMLog
, LogLevel::Debug
,
842 ("- redirects: %s\n\n", loggedRedirects
.get()));
845 auto extra
= Some
<nsTArray
<EventExtraEntry
>>(
846 {EventExtraEntry
{"contenttype"_ns
, loggedContentType
},
847 EventExtraEntry
{"remotetype"_ns
, loggedRemoteType
},
848 EventExtraEntry
{"filedetails"_ns
, loggedFileDetails
},
849 EventExtraEntry
{"redirects"_ns
, loggedRedirects
}});
851 if (!sTelemetryEventEnabled
.exchange(true)) {
852 Telemetry::SetEventRecordingEnabled("security"_ns
, true);
855 Telemetry::EventID eventType
=
856 Telemetry::EventID::Security_Unexpectedload_Systemprincipal
;
857 Telemetry::RecordEvent(eventType
, mozilla::Some(fileNameTypeAndDetails
.first
),
862 nsSecurityFlags
nsContentSecurityManager::ComputeSecurityFlags(
863 mozilla::CORSMode aCORSMode
, CORSSecurityMapping aCORSSecurityMapping
) {
864 if (aCORSSecurityMapping
== CORSSecurityMapping::DISABLE_CORS_CHECKS
) {
865 return nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
;
870 if (aCORSSecurityMapping
== CORSSecurityMapping::REQUIRE_CORS_CHECKS
) {
871 // CORS_NONE gets treated like CORS_ANONYMOUS in this mode
872 return nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
|
873 nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
;
874 } else if (aCORSSecurityMapping
==
875 CORSSecurityMapping::CORS_NONE_MAPS_TO_INHERITED_CONTEXT
) {
876 // CORS_NONE inherits
877 return nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
;
879 // CORS_NONE_MAPS_TO_DISABLED_CORS_CHECKS, the only remaining enum
880 // variant. CORSSecurityMapping::DISABLE_CORS_CHECKS returned early.
881 MOZ_ASSERT(aCORSSecurityMapping
==
882 CORSSecurityMapping::CORS_NONE_MAPS_TO_DISABLED_CORS_CHECKS
);
883 return nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
;
886 return nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
|
887 nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
;
888 case CORS_USE_CREDENTIALS
:
889 return nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
|
890 nsILoadInfo::SEC_COOKIES_INCLUDE
;
893 MOZ_ASSERT_UNREACHABLE("Invalid aCORSMode enum value");
894 return nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
|
895 nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
;
900 nsresult
nsContentSecurityManager::CheckAllowLoadInSystemPrivilegedContext(
901 nsIChannel
* aChannel
) {
902 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
903 nsCOMPtr
<nsIPrincipal
> inspectedPrincipal
= loadInfo
->GetLoadingPrincipal();
904 if (!inspectedPrincipal
) {
907 // Check if we are actually dealing with a privileged request
908 if (!inspectedPrincipal
->IsSystemPrincipal()) {
911 // loads with the allow flag are waived through
912 // until refactored (e.g., Shavar, OCSP)
913 if (loadInfo
->GetAllowDeprecatedSystemRequests()) {
916 ExtContentPolicyType contentPolicyType
=
917 loadInfo
->GetExternalContentPolicyType();
918 // For now, let's not inspect top-level document loads
919 if (contentPolicyType
== ExtContentPolicy::TYPE_DOCUMENT
) {
923 // allowing some fetches due to their lowered risk
924 // i.e., data & downloads fetches do limited parsing, no rendering
925 // remote images are too widely used (favicons, about:addons etc.)
926 if ((contentPolicyType
== ExtContentPolicy::TYPE_FETCH
) ||
927 (contentPolicyType
== ExtContentPolicy::TYPE_XMLHTTPREQUEST
) ||
928 (contentPolicyType
== ExtContentPolicy::TYPE_WEBSOCKET
) ||
929 (contentPolicyType
== ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD
) ||
930 (contentPolicyType
== ExtContentPolicy::TYPE_IMAGE
)) {
934 // Allow the user interface (e.g., schemes like chrome, resource)
935 nsCOMPtr
<nsIURI
> finalURI
;
936 NS_GetFinalChannelURI(aChannel
, getter_AddRefs(finalURI
));
937 bool isUiResource
= false;
938 if (NS_SUCCEEDED(NS_URIChainHasFlags(
939 finalURI
, nsIProtocolHandler::URI_IS_UI_RESOURCE
, &isUiResource
)) &&
943 // For about: and extension-based URIs, which don't get
944 // URI_IS_UI_RESOURCE, first remove layers of view-source:, if present.
945 nsCOMPtr
<nsIURI
> innerURI
= NS_GetInnermostURI(finalURI
);
947 nsAutoCString remoteType
;
948 if (XRE_IsParentProcess()) {
949 nsCOMPtr
<nsIParentChannel
> parentChannel
;
950 NS_QueryNotificationCallbacks(aChannel
, parentChannel
);
952 parentChannel
->GetRemoteType(remoteType
);
956 mozilla::dom::ContentChild::GetSingleton()->GetRemoteType());
959 // GetInnerURI can return null for malformed nested URIs like moz-icon:trash
961 MeasureUnexpectedPrivilegedLoads(loadInfo
, innerURI
, remoteType
);
962 if (StaticPrefs::security_disallow_privileged_no_finaluri_loads()) {
963 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
964 return NS_ERROR_CONTENT_BLOCKED
;
968 // loads of userContent.css during startup and tests that show up as file:
969 if (innerURI
->SchemeIs("file")) {
970 if ((contentPolicyType
== ExtContentPolicy::TYPE_STYLESHEET
) ||
971 (contentPolicyType
== ExtContentPolicy::TYPE_OTHER
)) {
975 // (1) loads from within omni.ja and system add-ons use jar:
976 // this is safe to allow, because we do not support remote jar.
977 // (2) about: resources are always allowed: they are part of the build.
978 // (3) extensions are signed or the user has made bad decisions.
979 if (innerURI
->SchemeIs("jar") || innerURI
->SchemeIs("about") ||
980 innerURI
->SchemeIs("moz-extension")) {
984 nsAutoCString requestedURL
;
985 innerURI
->GetAsciiSpec(requestedURL
);
986 MOZ_LOG(sCSMLog
, LogLevel::Warning
,
987 ("SystemPrincipal should not load remote resources. URL: %s, type %d",
988 requestedURL
.get(), int(contentPolicyType
)));
990 // The load types that we want to disallow, will extend over time and
991 // prioritized by risk. The most risky/dangerous are load-types are documents,
992 // subdocuments, scripts and styles in that order. The most dangerous URL
993 // schemes to cover are HTTP, HTTPS, data, blob in that order. Meta bug
994 // 1725112 will track upcoming restrictions
996 // Telemetry for unexpected privileged loads.
997 // pref check & data sanitization happens in the called function
998 MeasureUnexpectedPrivilegedLoads(loadInfo
, innerURI
, remoteType
);
1000 // Relaxing restrictions for our test suites:
1001 // (1) AreNonLocalConnectionsDisabled() disables network, so
1002 // http://mochitest is actually local and allowed. (2) The marionette test
1003 // framework uses injections and data URLs to execute scripts, checking for
1004 // the environment variable breaks the attack but not the tests.
1005 if (xpc::AreNonLocalConnectionsDisabled() ||
1006 mozilla::EnvHasValue("MOZ_MARIONETTE")) {
1007 bool disallowSystemPrincipalRemoteDocuments
= Preferences::GetBool(
1008 "security.disallow_non_local_systemprincipal_in_tests");
1009 if (disallowSystemPrincipalRemoteDocuments
) {
1010 // our own mochitest needs NS_ASSERTION instead of MOZ_ASSERT
1011 NS_ASSERTION(false, "SystemPrincipal must not load remote documents.");
1012 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1013 return NS_ERROR_CONTENT_BLOCKED
;
1015 // but other mochitest are exempt from this
1019 if (contentPolicyType
== ExtContentPolicy::TYPE_SUBDOCUMENT
) {
1020 if (StaticPrefs::security_disallow_privileged_https_subdocuments_loads() &&
1021 (innerURI
->SchemeIs("http") || innerURI
->SchemeIs("https"))) {
1024 "Disallowing SystemPrincipal load of subdocuments on HTTP(S).");
1025 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1026 return NS_ERROR_CONTENT_BLOCKED
;
1028 if ((StaticPrefs::security_disallow_privileged_data_subdocuments_loads()) &&
1029 (innerURI
->SchemeIs("data"))) {
1032 "Disallowing SystemPrincipal load of subdocuments on data URL.");
1033 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1034 return NS_ERROR_CONTENT_BLOCKED
;
1037 if (contentPolicyType
== ExtContentPolicy::TYPE_SCRIPT
) {
1038 if ((StaticPrefs::security_disallow_privileged_https_script_loads()) &&
1039 (innerURI
->SchemeIs("http") || innerURI
->SchemeIs("https"))) {
1041 "Disallowing SystemPrincipal load of scripts on HTTP(S).");
1042 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1043 return NS_ERROR_CONTENT_BLOCKED
;
1046 if (contentPolicyType
== ExtContentPolicy::TYPE_STYLESHEET
) {
1047 if (StaticPrefs::security_disallow_privileged_https_stylesheet_loads() &&
1048 (innerURI
->SchemeIs("http") || innerURI
->SchemeIs("https"))) {
1050 "Disallowing SystemPrincipal load of stylesheets on HTTP(S).");
1051 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1052 return NS_ERROR_CONTENT_BLOCKED
;
1059 * Disallow about pages in the privilegedaboutcontext (e.g., password manager,
1060 * newtab etc.) to load remote scripts. Regardless of whether this is coming
1061 * from the contentprincipal or the systemprincipal.
1064 nsresult
nsContentSecurityManager::CheckAllowLoadInPrivilegedAboutContext(
1065 nsIChannel
* aChannel
) {
1066 // bail out if check is disabled
1067 if (StaticPrefs::security_disallow_privilegedabout_remote_script_loads()) {
1071 nsAutoCString remoteType
;
1072 if (XRE_IsParentProcess()) {
1073 nsCOMPtr
<nsIParentChannel
> parentChannel
;
1074 NS_QueryNotificationCallbacks(aChannel
, parentChannel
);
1075 if (parentChannel
) {
1076 parentChannel
->GetRemoteType(remoteType
);
1080 mozilla::dom::ContentChild::GetSingleton()->GetRemoteType());
1083 // only perform check for privileged about process
1084 if (!remoteType
.Equals(PRIVILEGEDABOUT_REMOTE_TYPE
)) {
1088 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1089 ExtContentPolicyType contentPolicyType
=
1090 loadInfo
->GetExternalContentPolicyType();
1091 // only check for script loads
1092 if (contentPolicyType
!= ExtContentPolicy::TYPE_SCRIPT
) {
1096 nsCOMPtr
<nsIURI
> finalURI
;
1097 NS_GetFinalChannelURI(aChannel
, getter_AddRefs(finalURI
));
1098 nsCOMPtr
<nsIURI
> innerURI
= NS_GetInnermostURI(finalURI
);
1101 NS_URIChainHasFlags(innerURI
, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
,
1103 // We allow URLs that are URI_IS_LOCAL (but that includes `data`
1104 // and `blob` which are also undesirable.
1105 if ((isLocal
) && (!innerURI
->SchemeIs("data")) &&
1106 (!innerURI
->SchemeIs("blob"))) {
1111 "Disallowing privileged about process to load scripts on HTTP(S).");
1112 aChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1113 return NS_ERROR_CONTENT_BLOCKED
;
1117 * Every protocol handler must set one of the six security flags
1118 * defined in nsIProtocolHandler - if not - deny the load.
1120 nsresult
nsContentSecurityManager::CheckChannelHasProtocolSecurityFlag(
1121 nsIChannel
* aChannel
) {
1122 nsCOMPtr
<nsIURI
> uri
;
1123 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
1124 NS_ENSURE_SUCCESS(rv
, rv
);
1126 nsCOMPtr
<nsIIOService
> ios
= do_GetIOService(&rv
);
1127 NS_ENSURE_SUCCESS(rv
, rv
);
1130 rv
= ios
->GetDynamicProtocolFlags(uri
, &flags
);
1131 NS_ENSURE_SUCCESS(rv
, rv
);
1133 uint32_t securityFlagsSet
= 0;
1134 if (flags
& nsIProtocolHandler::WEBEXT_URI_WEB_ACCESSIBLE
) {
1135 securityFlagsSet
+= 1;
1137 if (flags
& nsIProtocolHandler::URI_LOADABLE_BY_ANYONE
) {
1138 securityFlagsSet
+= 1;
1140 if (flags
& nsIProtocolHandler::URI_DANGEROUS_TO_LOAD
) {
1141 securityFlagsSet
+= 1;
1143 if (flags
& nsIProtocolHandler::URI_IS_UI_RESOURCE
) {
1144 securityFlagsSet
+= 1;
1146 if (flags
& nsIProtocolHandler::URI_IS_LOCAL_FILE
) {
1147 securityFlagsSet
+= 1;
1149 if (flags
& nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
) {
1150 securityFlagsSet
+= 1;
1153 // Ensure that only "1" valid security flags is set.
1154 if (securityFlagsSet
== 1) {
1158 MOZ_ASSERT(false, "protocol must use one valid security flag");
1159 return NS_ERROR_CONTENT_BLOCKED
;
1162 // We should not allow loading non-JavaScript files as scripts using
1164 static nsresult
CheckAllowFileProtocolScriptLoad(nsIChannel
* aChannel
) {
1165 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1166 ExtContentPolicyType type
= loadInfo
->GetExternalContentPolicyType();
1168 // Only check script loads.
1169 if (type
!= ExtContentPolicy::TYPE_SCRIPT
) {
1173 if (!StaticPrefs::security_block_fileuri_script_with_wrong_mime()) {
1177 nsCOMPtr
<nsIURI
> uri
;
1178 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
1179 NS_ENSURE_SUCCESS(rv
, rv
);
1180 if (!uri
|| !uri
->SchemeIs("file")) {
1184 nsCOMPtr
<nsIMIMEService
> mime
= do_GetService("@mozilla.org/mime;1", &rv
);
1185 NS_ENSURE_SUCCESS(rv
, rv
);
1187 // GetTypeFromURI fails for missing or unknown file-extensions.
1188 nsAutoCString contentType
;
1189 rv
= mime
->GetTypeFromURI(uri
, contentType
);
1190 if (NS_FAILED(rv
) || !nsContentUtils::IsJavascriptMIMEType(
1191 NS_ConvertUTF8toUTF16(contentType
))) {
1192 nsCOMPtr
<Document
> doc
;
1193 if (nsINode
* node
= loadInfo
->LoadingNode()) {
1194 doc
= node
->OwnerDoc();
1200 AutoTArray
<nsString
, 1> params
;
1201 CopyUTF8toUTF16(NS_UnescapeURL(spec
), *params
.AppendElement());
1202 CopyUTF8toUTF16(NS_UnescapeURL(contentType
), *params
.AppendElement());
1204 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag
,
1205 "FILE_SCRIPT_BLOCKED"_ns
, doc
,
1206 nsContentUtils::eSECURITY_PROPERTIES
,
1207 "BlockFileScriptWithWrongMimeType", params
);
1209 return NS_ERROR_CONTENT_BLOCKED
;
1215 // We should not allow loading non-JavaScript files as scripts using
1216 // a moz-extension:// URL.
1217 static nsresult
CheckAllowExtensionProtocolScriptLoad(nsIChannel
* aChannel
) {
1218 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1219 ExtContentPolicyType type
= loadInfo
->GetExternalContentPolicyType();
1221 // Only check script loads.
1222 if (type
!= ExtContentPolicy::TYPE_SCRIPT
) {
1226 nsCOMPtr
<nsIURI
> uri
;
1227 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
1228 NS_ENSURE_SUCCESS(rv
, rv
);
1229 if (!uri
|| !uri
->SchemeIs("moz-extension")) {
1233 // We expect this code to never be hit off-the-main-thread (even worker
1234 // scripts are currently hitting only on the main thread, see
1235 // WorkerScriptLoader::DispatchLoadScript calling NS_DispatchToMainThread
1236 // internally), this diagnostic assertion is meant to let us notice if that
1237 // isn't the case anymore.
1238 MOZ_DIAGNOSTIC_ASSERT(NS_IsMainThread(),
1239 "Unexpected off-the-main-thread call to "
1240 "CheckAllowFileProtocolScriptLoad");
1243 rv
= uri
->GetHost(host
);
1244 NS_ENSURE_SUCCESS(rv
, rv
);
1246 RefPtr
<extensions::WebExtensionPolicyCore
> targetPolicy
=
1247 ExtensionPolicyService::GetCoreByHost(host
);
1249 if (NS_WARN_IF(!targetPolicy
) || targetPolicy
->ManifestVersion() < 3) {
1253 nsCOMPtr
<nsIMIMEService
> mime
= do_GetService("@mozilla.org/mime;1", &rv
);
1254 NS_ENSURE_SUCCESS(rv
, rv
);
1256 // GetDefaultTypeFromExtension fails for missing or unknown file-extensions.
1257 nsAutoCString contentType
;
1258 rv
= mime
->GetDefaultTypeFromURI(uri
, contentType
);
1259 if (NS_FAILED(rv
) || !nsContentUtils::IsJavascriptMIMEType(
1260 NS_ConvertUTF8toUTF16(contentType
))) {
1261 nsCOMPtr
<Document
> doc
;
1262 if (nsINode
* node
= loadInfo
->LoadingNode()) {
1263 doc
= node
->OwnerDoc();
1269 AutoTArray
<nsString
, 1> params
;
1270 CopyUTF8toUTF16(NS_UnescapeURL(spec
), *params
.AppendElement());
1272 nsContentUtils::ReportToConsole(nsIScriptError::warningFlag
,
1273 "EXTENSION_SCRIPT_BLOCKED"_ns
, doc
,
1274 nsContentUtils::eSECURITY_PROPERTIES
,
1275 "BlockExtensionScriptWithWrongExt", params
);
1277 return NS_ERROR_CONTENT_BLOCKED
;
1283 // Validate that a load should be allowed based on its remote type. This
1284 // intentionally prevents some loads from occuring even using the system
1285 // principal, if they were started in a content process.
1286 static nsresult
CheckAllowLoadByTriggeringRemoteType(nsIChannel
* aChannel
) {
1287 MOZ_ASSERT(aChannel
);
1289 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1291 // For now, only restrict loads for documents. We currently have no
1292 // interesting subresource checks for protocols which are are not fully
1293 // handled within the content process.
1294 ExtContentPolicy contentPolicyType
= loadInfo
->GetExternalContentPolicyType();
1295 if (contentPolicyType
!= ExtContentPolicy::TYPE_DOCUMENT
&&
1296 contentPolicyType
!= ExtContentPolicy::TYPE_SUBDOCUMENT
&&
1297 contentPolicyType
!= ExtContentPolicy::TYPE_OBJECT
) {
1301 MOZ_DIAGNOSTIC_ASSERT(NS_IsMainThread(),
1302 "Unexpected off-the-main-thread call to "
1303 "CheckAllowLoadByTriggeringRemoteType");
1305 // Due to the way that session history is handled without SHIP, we cannot run
1306 // these checks when SHIP is disabled.
1307 if (!mozilla::SessionHistoryInParent()) {
1311 nsAutoCString triggeringRemoteType
;
1312 nsresult rv
= loadInfo
->GetTriggeringRemoteType(triggeringRemoteType
);
1313 NS_ENSURE_SUCCESS(rv
, rv
);
1315 // For now, only restrict loads coming from web remote types. In the future we
1316 // may want to expand this a bit.
1317 if (!StringBeginsWith(triggeringRemoteType
, WEB_REMOTE_TYPE
)) {
1321 nsCOMPtr
<nsIURI
> finalURI
;
1322 rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(finalURI
));
1323 NS_ENSURE_SUCCESS(rv
, rv
);
1325 // Don't allow web content processes to load non-remote about pages.
1326 // NOTE: URIs with a `moz-safe-about:` inner scheme are safe to link to, so
1327 // it's OK we miss them here.
1328 nsCOMPtr
<nsIURI
> innermostURI
= NS_GetInnermostURI(finalURI
);
1329 if (innermostURI
->SchemeIs("about")) {
1330 nsCOMPtr
<nsIAboutModule
> aboutModule
;
1331 rv
= NS_GetAboutModule(innermostURI
, getter_AddRefs(aboutModule
));
1332 NS_ENSURE_SUCCESS(rv
, rv
);
1334 uint32_t aboutModuleFlags
= 0;
1335 rv
= aboutModule
->GetURIFlags(innermostURI
, &aboutModuleFlags
);
1336 NS_ENSURE_SUCCESS(rv
, rv
);
1338 if (!(aboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) &&
1339 !(aboutModuleFlags
& nsIAboutModule::URI_CAN_LOAD_IN_CHILD
) &&
1340 !(aboutModuleFlags
& nsIAboutModule::URI_MUST_LOAD_IN_CHILD
)) {
1341 NS_WARNING(nsPrintfCString("Blocking load of about URI (%s) which cannot "
1342 "be linked to in web content process",
1343 finalURI
->GetSpecOrDefault().get())
1345 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1347 loadInfo
->TriggeringPrincipal()->CheckMayLoad(finalURI
, true))) {
1348 nsAutoCString aboutModuleName
;
1349 MOZ_ALWAYS_SUCCEEDS(
1350 NS_GetAboutModuleName(innermostURI
, aboutModuleName
));
1351 MOZ_CRASH_UNSAFE_PRINTF(
1352 "Blocking load of about uri by content process which may have "
1353 "otherwise succeeded [aboutModule=%s, isSystemPrincipal=%d]",
1354 aboutModuleName
.get(),
1355 loadInfo
->TriggeringPrincipal()->IsSystemPrincipal());
1358 return NS_ERROR_CONTENT_BLOCKED
;
1363 // Don't allow web content processes to load file documents. Loads of file
1364 // URIs as subresources will be handled by the sandbox, and may be allowed in
1366 bool localFile
= false;
1367 rv
= NS_URIChainHasFlags(finalURI
, nsIProtocolHandler::URI_IS_LOCAL_FILE
,
1369 NS_ENSURE_SUCCESS(rv
, rv
);
1373 "Blocking document load of file URI (%s) from web content process",
1374 innermostURI
->GetSpecOrDefault().get())
1376 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1378 loadInfo
->TriggeringPrincipal()->CheckMayLoad(finalURI
, true))) {
1379 MOZ_CRASH_UNSAFE_PRINTF(
1380 "Blocking document load of file URI by content process which may "
1381 "have otherwise succeeded [isSystemPrincipal=%d]",
1382 loadInfo
->TriggeringPrincipal()->IsSystemPrincipal());
1385 return NS_ERROR_CONTENT_BLOCKED
;
1392 * Based on the security flags provided in the loadInfo of the channel,
1393 * doContentSecurityCheck() performs the following content security checks
1394 * before opening the channel:
1396 * (1) Same Origin Policy Check (if applicable)
1397 * (2) Allow Cross Origin but perform sanity checks whether a principal
1398 * is allowed to access the following URL.
1399 * (3) Perform CORS check (if applicable)
1400 * (4) ContentPolicy checks (Content-Security-Policy, Mixed Content, ...)
1403 * The channel to perform the security checks on.
1404 * @param aInAndOutListener
1405 * The streamListener that is passed to channel->AsyncOpen() that is now
1406 * potentially wrappend within nsCORSListenerProxy() and becomes the
1407 * corsListener that now needs to be set as new streamListener on the channel.
1409 nsresult
nsContentSecurityManager::doContentSecurityCheck(
1410 nsIChannel
* aChannel
, nsCOMPtr
<nsIStreamListener
>& aInAndOutListener
) {
1411 NS_ENSURE_ARG(aChannel
);
1412 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1413 if (MOZ_UNLIKELY(MOZ_LOG_TEST(sCSMLog
, LogLevel::Verbose
))) {
1414 DebugDoContentSecurityCheck(aChannel
, loadInfo
);
1417 nsresult rv
= CheckAllowLoadInSystemPrivilegedContext(aChannel
);
1418 NS_ENSURE_SUCCESS(rv
, rv
);
1420 rv
= CheckAllowLoadInPrivilegedAboutContext(aChannel
);
1421 NS_ENSURE_SUCCESS(rv
, rv
);
1423 // We want to also check redirected requests to ensure
1424 // the target maintains the proper javascript file extensions.
1425 rv
= CheckAllowExtensionProtocolScriptLoad(aChannel
);
1426 NS_ENSURE_SUCCESS(rv
, rv
);
1428 rv
= CheckChannelHasProtocolSecurityFlag(aChannel
);
1429 NS_ENSURE_SUCCESS(rv
, rv
);
1431 rv
= CheckAllowLoadByTriggeringRemoteType(aChannel
);
1432 NS_ENSURE_SUCCESS(rv
, rv
);
1434 // if dealing with a redirected channel then we have already installed
1435 // streamlistener and redirect proxies and so we are done.
1436 if (loadInfo
->GetInitialSecurityCheckDone()) {
1440 // make sure that only one of the five security flags is set in the loadinfo
1441 // e.g. do not require same origin and allow cross origin at the same time
1442 rv
= ValidateSecurityFlags(loadInfo
);
1443 NS_ENSURE_SUCCESS(rv
, rv
);
1445 if (loadInfo
->GetSecurityMode() ==
1446 nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
) {
1447 rv
= DoCORSChecks(aChannel
, loadInfo
, aInAndOutListener
);
1448 NS_ENSURE_SUCCESS(rv
, rv
);
1451 rv
= CheckChannel(aChannel
);
1452 NS_ENSURE_SUCCESS(rv
, rv
);
1454 // Perform all ContentPolicy checks (MixedContent, CSP, ...)
1455 rv
= DoContentSecurityChecks(aChannel
, loadInfo
);
1456 NS_ENSURE_SUCCESS(rv
, rv
);
1458 rv
= CheckAllowFileProtocolScriptLoad(aChannel
);
1459 NS_ENSURE_SUCCESS(rv
, rv
);
1461 // now lets set the initialSecurityFlag for subsequent calls
1462 loadInfo
->SetInitialSecurityCheckDone(true);
1464 // all security checks passed - lets allow the load
1469 nsContentSecurityManager::AsyncOnChannelRedirect(
1470 nsIChannel
* aOldChannel
, nsIChannel
* aNewChannel
, uint32_t aRedirFlags
,
1471 nsIAsyncVerifyRedirectCallback
* aCb
) {
1472 // Since we compare the principal from the loadInfo to the URI's
1473 // princicpal, it's possible that the checks fail when doing an internal
1474 // redirect. We can just return early instead, since we should never
1475 // need to block an internal redirect.
1476 if (aRedirFlags
& nsIChannelEventSink::REDIRECT_INTERNAL
) {
1477 aCb
->OnRedirectVerifyCallback(NS_OK
);
1481 nsCOMPtr
<nsILoadInfo
> loadInfo
= aOldChannel
->LoadInfo();
1482 nsresult rv
= CheckChannel(aNewChannel
);
1483 if (NS_FAILED(rv
)) {
1484 aOldChannel
->Cancel(rv
);
1488 // Also verify that the redirecting server is allowed to redirect to the
1490 nsCOMPtr
<nsIPrincipal
> oldPrincipal
;
1491 nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
1492 aOldChannel
, getter_AddRefs(oldPrincipal
));
1494 nsCOMPtr
<nsIURI
> newURI
;
1495 Unused
<< NS_GetFinalChannelURI(aNewChannel
, getter_AddRefs(newURI
));
1496 NS_ENSURE_STATE(oldPrincipal
&& newURI
);
1498 // Do not allow insecure redirects to data: URIs
1499 if (!AllowInsecureRedirectToDataURI(aNewChannel
)) {
1500 // cancel the old channel and return an error
1501 aOldChannel
->Cancel(NS_ERROR_CONTENT_BLOCKED
);
1502 return NS_ERROR_CONTENT_BLOCKED
;
1505 const uint32_t flags
=
1506 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
|
1507 nsIScriptSecurityManager::DISALLOW_SCRIPT
;
1508 rv
= nsContentUtils::GetSecurityManager()->CheckLoadURIWithPrincipal(
1509 oldPrincipal
, newURI
, flags
, loadInfo
->GetInnerWindowID());
1510 NS_ENSURE_SUCCESS(rv
, rv
);
1512 aCb
->OnRedirectVerifyCallback(NS_OK
);
1516 static void AddLoadFlags(nsIRequest
* aRequest
, nsLoadFlags aNewFlags
) {
1518 aRequest
->GetLoadFlags(&flags
);
1520 aRequest
->SetLoadFlags(flags
);
1524 * Check that this channel passes all security checks. Returns an error code
1525 * if this requesst should not be permitted.
1527 nsresult
nsContentSecurityManager::CheckChannel(nsIChannel
* aChannel
) {
1528 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1529 nsCOMPtr
<nsIURI
> uri
;
1530 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
1531 NS_ENSURE_SUCCESS(rv
, rv
);
1533 // Handle cookie policies
1534 uint32_t cookiePolicy
= loadInfo
->GetCookiePolicy();
1535 if (cookiePolicy
== nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
) {
1536 // We shouldn't have the SEC_COOKIES_SAME_ORIGIN flag for top level loads
1537 MOZ_ASSERT(loadInfo
->GetExternalContentPolicyType() !=
1538 ExtContentPolicy::TYPE_DOCUMENT
);
1539 nsIPrincipal
* loadingPrincipal
= loadInfo
->GetLoadingPrincipal();
1541 // It doesn't matter what we pass for the second, data-inherits, argument.
1542 // Any protocol which inherits won't pay attention to cookies anyway.
1543 rv
= loadingPrincipal
->CheckMayLoad(uri
, false);
1544 if (NS_FAILED(rv
)) {
1545 AddLoadFlags(aChannel
, nsIRequest::LOAD_ANONYMOUS
);
1547 } else if (cookiePolicy
== nsILoadInfo::SEC_COOKIES_OMIT
) {
1548 AddLoadFlags(aChannel
, nsIRequest::LOAD_ANONYMOUS
);
1551 if (!CrossOriginEmbedderPolicyAllowsCredentials(aChannel
)) {
1552 AddLoadFlags(aChannel
, nsIRequest::LOAD_ANONYMOUS
);
1555 nsSecurityFlags securityMode
= loadInfo
->GetSecurityMode();
1557 // CORS mode is handled by nsCORSListenerProxy
1558 if (securityMode
== nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
) {
1559 if (NS_HasBeenCrossOrigin(aChannel
)) {
1560 loadInfo
->MaybeIncreaseTainting(LoadTainting::CORS
);
1565 // Allow subresource loads if TriggeringPrincipal is the SystemPrincipal.
1566 if (loadInfo
->TriggeringPrincipal()->IsSystemPrincipal() &&
1567 loadInfo
->GetExternalContentPolicyType() !=
1568 ExtContentPolicy::TYPE_DOCUMENT
&&
1569 loadInfo
->GetExternalContentPolicyType() !=
1570 ExtContentPolicy::TYPE_SUBDOCUMENT
) {
1574 // if none of the REQUIRE_SAME_ORIGIN flags are set, then SOP does not apply
1575 if ((securityMode
==
1576 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
) ||
1577 (securityMode
== nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
)) {
1578 rv
= DoSOPChecks(uri
, loadInfo
, aChannel
);
1579 NS_ENSURE_SUCCESS(rv
, rv
);
1582 if ((securityMode
==
1583 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
) ||
1585 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
)) {
1586 if (NS_HasBeenCrossOrigin(aChannel
)) {
1587 NS_ENSURE_FALSE(loadInfo
->GetDontFollowRedirects(), NS_ERROR_DOM_BAD_URI
);
1588 loadInfo
->MaybeIncreaseTainting(LoadTainting::Opaque
);
1590 // Please note that DoCheckLoadURIChecks should only be enforced for
1591 // cross origin requests. If the flag SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
1592 // is set within the loadInfo, then CheckLoadURIWithPrincipal is performed
1593 // within nsCorsListenerProxy
1594 rv
= DoCheckLoadURIChecks(uri
, loadInfo
);
1595 NS_ENSURE_SUCCESS(rv
, rv
);
1596 // TODO: Bug 1371237
1597 // consider calling SetBlockedRequest in
1598 // nsContentSecurityManager::CheckChannel
1604 // https://fetch.spec.whatwg.org/#ref-for-cross-origin-embedder-policy-allows-credentials
1605 bool nsContentSecurityManager::CrossOriginEmbedderPolicyAllowsCredentials(
1606 nsIChannel
* aChannel
) {
1607 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
1609 // 1. If request’s mode is not "no-cors", then return true.
1611 // `no-cors` check applies to document navigation such that if it is
1612 // an document navigation, this check should return true to allow
1614 if (loadInfo
->GetExternalContentPolicyType() ==
1615 ExtContentPolicy::TYPE_DOCUMENT
||
1616 loadInfo
->GetExternalContentPolicyType() ==
1617 ExtContentPolicy::TYPE_SUBDOCUMENT
||
1618 loadInfo
->GetExternalContentPolicyType() ==
1619 ExtContentPolicy::TYPE_WEBSOCKET
) {
1623 if (loadInfo
->GetSecurityMode() !=
1624 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL
&&
1625 loadInfo
->GetSecurityMode() !=
1626 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
) {
1630 // If request’s client’s policy container’s embedder policy’s value is not
1631 // "credentialless", then return true.
1632 if (loadInfo
->GetLoadingEmbedderPolicy() !=
1633 nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS
) {
1637 // If request’s origin is same origin with request’s current URL’s origin and
1638 // request does not have a redirect-tainted origin, then return true.
1639 nsIScriptSecurityManager
* ssm
= nsContentUtils::GetSecurityManager();
1640 nsCOMPtr
<nsIPrincipal
> resourcePrincipal
;
1641 ssm
->GetChannelURIPrincipal(aChannel
, getter_AddRefs(resourcePrincipal
));
1643 bool sameOrigin
= resourcePrincipal
->Equals(loadInfo
->TriggeringPrincipal());
1644 nsAutoCString serializedOrigin
;
1645 GetSerializedOrigin(loadInfo
->TriggeringPrincipal(), resourcePrincipal
,
1646 serializedOrigin
, loadInfo
);
1647 if (sameOrigin
&& !serializedOrigin
.IsEmpty()) {
1654 // https://fetch.spec.whatwg.org/#serializing-a-request-origin
1655 void nsContentSecurityManager::GetSerializedOrigin(
1656 nsIPrincipal
* aOrigin
, nsIPrincipal
* aResourceOrigin
,
1657 nsACString
& aSerializedOrigin
, nsILoadInfo
* aLoadInfo
) {
1658 // The following for loop performs the
1659 // https://fetch.spec.whatwg.org/#ref-for-concept-request-tainted-origin
1660 nsCOMPtr
<nsIPrincipal
> lastOrigin
;
1661 for (nsIRedirectHistoryEntry
* entry
: aLoadInfo
->RedirectChain()) {
1663 entry
->GetPrincipal(getter_AddRefs(lastOrigin
));
1667 nsCOMPtr
<nsIPrincipal
> currentOrigin
;
1668 entry
->GetPrincipal(getter_AddRefs(currentOrigin
));
1670 if (!currentOrigin
->Equals(lastOrigin
) && !lastOrigin
->Equals(aOrigin
)) {
1671 aSerializedOrigin
.AssignLiteral("null");
1674 lastOrigin
= currentOrigin
;
1677 // When the redirectChain is empty, it means this is the first redirect.
1678 // So according to the #serializing-a-request-origin spec, we don't
1679 // have a redirect-tainted origin, so we return the origin of the request
1682 aOrigin
->GetWebExposedOriginSerialization(aSerializedOrigin
);
1686 // Same as above, redirectChain doesn't contain the current redirect,
1687 // so we have to do the check one last time here.
1688 if (!lastOrigin
->Equals(aResourceOrigin
) && !lastOrigin
->Equals(aOrigin
)) {
1689 aSerializedOrigin
.AssignLiteral("null");
1693 aOrigin
->GetWebExposedOriginSerialization(aSerializedOrigin
);
1696 // https://html.spec.whatwg.org/multipage/browsers.html#compatible-with-cross-origin-isolation
1697 bool nsContentSecurityManager::IsCompatibleWithCrossOriginIsolation(
1698 nsILoadInfo::CrossOriginEmbedderPolicy aPolicy
) {
1699 return aPolicy
== nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS
||
1700 aPolicy
== nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP
;
1703 // ==== nsIContentSecurityManager implementation =====
1706 nsContentSecurityManager::PerformSecurityCheck(
1707 nsIChannel
* aChannel
, nsIStreamListener
* aStreamListener
,
1708 nsIStreamListener
** outStreamListener
) {
1709 nsCOMPtr
<nsIStreamListener
> inAndOutListener
= aStreamListener
;
1710 nsresult rv
= doContentSecurityCheck(aChannel
, inAndOutListener
);
1711 NS_ENSURE_SUCCESS(rv
, rv
);
1713 inAndOutListener
.forget(outStreamListener
);