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 "nsScriptSecurityManager.h"
9 #include "mozilla/ArrayUtils.h"
10 #include "mozilla/StaticPrefs_extensions.h"
11 #include "mozilla/StaticPrefs_security.h"
12 #include "mozilla/StoragePrincipalHelper.h"
14 #include "xpcpublic.h"
15 #include "XPCWrapper.h"
16 #include "nsILoadContext.h"
17 #include "nsIScriptObjectPrincipal.h"
18 #include "nsIScriptContext.h"
19 #include "nsIScriptError.h"
20 #include "nsINestedURI.h"
22 #include "nsJSPrincipals.h"
23 #include "mozilla/BasePrincipal.h"
24 #include "mozilla/ContentPrincipal.h"
25 #include "ExpandedPrincipal.h"
26 #include "SystemPrincipal.h"
27 #include "DomainPolicy.h"
30 #include "nsCRTGlue.h"
31 #include "nsContentSecurityUtils.h"
32 #include "nsDocShell.h"
34 #include "nsGlobalWindowInner.h"
36 #include "nsTextFormatter.h"
37 #include "nsIStringBundle.h"
38 #include "nsNetUtil.h"
39 #include "nsIEffectiveTLDService.h"
40 #include "nsDirectoryServiceDefs.h"
41 #include "nsIScriptGlobalObject.h"
42 #include "nsPIDOMWindow.h"
43 #include "nsIDocShell.h"
44 #include "nsIConsoleService.h"
45 #include "nsIOService.h"
46 #include "nsIContent.h"
47 #include "nsDOMJSUtils.h"
48 #include "nsAboutProtocolUtils.h"
49 #include "nsIClassInfo.h"
50 #include "nsIURIFixup.h"
51 #include "nsIURIMutator.h"
52 #include "nsIChromeRegistry.h"
53 #include "nsIResProtocolHandler.h"
54 #include "nsIContentSecurityPolicy.h"
55 #include "mozilla/Components.h"
56 #include "mozilla/Preferences.h"
57 #include "mozilla/dom/BindingUtils.h"
58 #include "mozilla/NullPrincipal.h"
60 #include "mozilla/dom/ContentChild.h"
61 #include "mozilla/dom/ContentParent.h"
62 #include "mozilla/dom/Exceptions.h"
63 #include "mozilla/dom/nsCSPContext.h"
64 #include "mozilla/dom/ScriptSettings.h"
65 #include "mozilla/ClearOnShutdown.h"
66 #include "mozilla/ExtensionPolicyService.h"
67 #include "mozilla/ResultExtensions.h"
68 #include "mozilla/StaticPtr.h"
69 #include "mozilla/dom/WorkerCommon.h"
70 #include "mozilla/dom/WorkerPrivate.h"
71 #include "nsContentUtils.h"
72 #include "nsJSUtils.h"
73 #include "nsILoadInfo.h"
74 #include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin
76 // This should be probably defined on some other place... but I couldn't find it
77 #define WEBAPPS_PERM_NAME "webapps-manage"
79 using namespace mozilla
;
80 using namespace mozilla::dom
;
82 StaticRefPtr
<nsIIOService
> nsScriptSecurityManager::sIOService
;
83 std::atomic
<bool> nsScriptSecurityManager::sStrictFileOriginPolicy
= true;
89 NS_INLINE_DECL_REFCOUNTING(BundleHelper
)
91 static nsIStringBundle
* GetOrCreate() {
92 MOZ_ASSERT(!sShutdown
);
94 // Already shutting down. Nothing should require the use of the string
95 // bundle when shutting down.
101 sSelf
= new BundleHelper();
104 return sSelf
->GetOrCreateInternal();
107 static void Shutdown() {
113 ~BundleHelper() = default;
115 nsIStringBundle
* GetOrCreateInternal() {
117 nsCOMPtr
<nsIStringBundleService
> bundleService
=
118 mozilla::components::StringBundle::Service();
119 if (NS_WARN_IF(!bundleService
)) {
123 nsresult rv
= bundleService
->CreateBundle(
124 "chrome://global/locale/security/caps.properties",
125 getter_AddRefs(mBundle
));
126 if (NS_WARN_IF(NS_FAILED(rv
))) {
134 nsCOMPtr
<nsIStringBundle
> mBundle
;
136 static StaticRefPtr
<BundleHelper
> sSelf
;
137 static bool sShutdown
;
140 StaticRefPtr
<BundleHelper
> BundleHelper::sSelf
;
141 bool BundleHelper::sShutdown
= false;
145 ///////////////////////////
146 // Convenience Functions //
147 ///////////////////////////
149 class nsAutoInPrincipalDomainOriginSetter
{
151 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin
; }
152 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin
; }
153 static uint32_t sInPrincipalDomainOrigin
;
155 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
;
157 static nsresult
GetOriginFromURI(nsIURI
* aURI
, nsACString
& aOrigin
) {
159 return NS_ERROR_NULL_POINTER
;
161 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
> 1) {
162 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
163 // might be happening on a different principal from the first call. But
164 // after that, cut off the recursion; it just indicates that something
165 // we're doing in this method causes us to reenter a security check here.
166 return NS_ERROR_NOT_AVAILABLE
;
169 nsAutoInPrincipalDomainOriginSetter autoSetter
;
171 nsCOMPtr
<nsIURI
> uri
= NS_GetInnermostURI(aURI
);
172 NS_ENSURE_TRUE(uri
, NS_ERROR_UNEXPECTED
);
174 nsAutoCString hostPort
;
176 nsresult rv
= uri
->GetHostPort(hostPort
);
177 if (NS_SUCCEEDED(rv
)) {
178 nsAutoCString scheme
;
179 rv
= uri
->GetScheme(scheme
);
180 NS_ENSURE_SUCCESS(rv
, rv
);
181 aOrigin
= scheme
+ "://"_ns
+ hostPort
;
183 // Some URIs (e.g., nsSimpleURI) don't support host. Just
184 // get the full spec.
185 rv
= uri
->GetSpec(aOrigin
);
186 NS_ENSURE_SUCCESS(rv
, rv
);
192 static nsresult
GetPrincipalDomainOrigin(nsIPrincipal
* aPrincipal
,
193 nsACString
& aOrigin
) {
195 nsCOMPtr
<nsIURI
> uri
;
196 aPrincipal
->GetDomain(getter_AddRefs(uri
));
197 nsresult rv
= GetOriginFromURI(uri
, aOrigin
);
198 if (NS_SUCCEEDED(rv
)) {
201 // If there is no Domain fallback to the Principals Origin
202 return aPrincipal
->GetOriginNoSuffix(aOrigin
);
205 inline void SetPendingExceptionASCII(JSContext
* cx
, const char* aMsg
) {
206 JS_ReportErrorASCII(cx
, "%s", aMsg
);
209 inline void SetPendingException(JSContext
* cx
, const char16_t
* aMsg
) {
210 NS_ConvertUTF16toUTF8
msg(aMsg
);
211 JS_ReportErrorUTF8(cx
, "%s", msg
.get());
215 bool nsScriptSecurityManager::SecurityCompareURIs(nsIURI
* aSourceURI
,
216 nsIURI
* aTargetURI
) {
217 return NS_SecurityCompareURIs(aSourceURI
, aTargetURI
,
218 sStrictFileOriginPolicy
);
221 // SecurityHashURI is consistent with SecurityCompareURIs because
222 // NS_SecurityHashURI is consistent with NS_SecurityCompareURIs. See
224 uint32_t nsScriptSecurityManager::SecurityHashURI(nsIURI
* aURI
) {
225 return NS_SecurityHashURI(aURI
);
228 bool nsScriptSecurityManager::IsHttpOrHttpsAndCrossOrigin(nsIURI
* aUriA
,
230 if (!aUriA
|| (!net::SchemeIsHTTP(aUriA
) && !net::SchemeIsHTTPS(aUriA
)) ||
231 !aUriB
|| (!net::SchemeIsHTTP(aUriB
) && !net::SchemeIsHTTPS(aUriB
))) {
234 if (!SecurityCompareURIs(aUriA
, aUriB
)) {
241 * GetChannelResultPrincipal will return the principal that the resource
242 * returned by this channel will use. For example, if the resource is in
243 * a sandbox, it will return the nullprincipal. If the resource is forced
244 * to inherit principal, it will return the principal of its parent. If
245 * the load doesn't require sandboxing or inheriting, it will return the same
246 * principal as GetChannelURIPrincipal. Namely the principal of the URI
247 * that is being loaded.
250 nsScriptSecurityManager::GetChannelResultPrincipal(nsIChannel
* aChannel
,
251 nsIPrincipal
** aPrincipal
) {
252 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
253 /*aIgnoreSandboxing*/ false);
256 nsresult
nsScriptSecurityManager::GetChannelResultPrincipalIfNotSandboxed(
257 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
258 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
259 /*aIgnoreSandboxing*/ true);
263 nsScriptSecurityManager::GetChannelResultStoragePrincipal(
264 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
265 nsCOMPtr
<nsIPrincipal
> principal
;
266 nsresult rv
= GetChannelResultPrincipal(aChannel
, getter_AddRefs(principal
),
267 /*aIgnoreSandboxing*/ false);
268 if (NS_WARN_IF(NS_FAILED(rv
) || !principal
)) {
272 if (!(principal
->GetIsContentPrincipal())) {
273 // If for some reason we don't have a content principal here, just reuse our
274 // principal for the storage principal too, since attempting to create a
275 // storage principal would fail anyway.
276 principal
.forget(aPrincipal
);
280 return StoragePrincipalHelper::Create(
281 aChannel
, principal
, /* aForceIsolation */ false, aPrincipal
);
285 nsScriptSecurityManager::GetChannelResultPrincipals(
286 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
,
287 nsIPrincipal
** aPartitionedPrincipal
) {
288 nsresult rv
= GetChannelResultPrincipal(aChannel
, aPrincipal
,
289 /*aIgnoreSandboxing*/ false);
290 if (NS_WARN_IF(NS_FAILED(rv
))) {
294 if (!(*aPrincipal
)->GetIsContentPrincipal()) {
295 // If for some reason we don't have a content principal here, just reuse our
296 // principal for the storage principal too, since attempting to create a
297 // storage principal would fail anyway.
298 nsCOMPtr
<nsIPrincipal
> copy
= *aPrincipal
;
299 copy
.forget(aPartitionedPrincipal
);
303 return StoragePrincipalHelper::Create(
304 aChannel
, *aPrincipal
, /* aForceIsolation */ true, aPartitionedPrincipal
);
307 nsresult
nsScriptSecurityManager::GetChannelResultPrincipal(
308 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
, bool aIgnoreSandboxing
) {
309 MOZ_ASSERT(aChannel
, "Must have channel!");
311 // Check whether we have an nsILoadInfo that says what we should do.
312 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
313 if (loadInfo
->GetForceInheritPrincipalOverruleOwner()) {
314 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
315 loadInfo
->FindPrincipalToInherit(aChannel
);
316 principalToInherit
.forget(aPrincipal
);
320 nsCOMPtr
<nsISupports
> owner
;
321 aChannel
->GetOwner(getter_AddRefs(owner
));
323 CallQueryInterface(owner
, aPrincipal
);
329 if (!aIgnoreSandboxing
&& loadInfo
->GetLoadingSandboxed()) {
330 // Determine the unsandboxed result principal to use as this null
331 // principal's precursor. Ignore errors here, as the precursor isn't
333 nsCOMPtr
<nsIPrincipal
> precursor
;
334 GetChannelResultPrincipal(aChannel
, getter_AddRefs(precursor
),
335 /*aIgnoreSandboxing*/ true);
337 // Construct a deterministic null principal URI from the precursor and the
338 // loadinfo's nullPrincipalID.
339 nsCOMPtr
<nsIURI
> nullPrincipalURI
= NullPrincipal::CreateURI(
340 precursor
, &loadInfo
->GetSandboxedNullPrincipalID());
342 // Use the URI to construct the sandboxed result principal.
343 OriginAttributes attrs
;
344 loadInfo
->GetOriginAttributes(&attrs
);
345 nsCOMPtr
<nsIPrincipal
> sandboxedPrincipal
=
346 NullPrincipal::Create(attrs
, nullPrincipalURI
);
347 sandboxedPrincipal
.forget(aPrincipal
);
351 bool forceInherit
= loadInfo
->GetForceInheritPrincipal();
352 if (aIgnoreSandboxing
&& !forceInherit
) {
353 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
355 if (loadInfo
->GetLoadingSandboxed() &&
356 loadInfo
->GetForceInheritPrincipalDropped()) {
361 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
362 loadInfo
->FindPrincipalToInherit(aChannel
);
363 principalToInherit
.forget(aPrincipal
);
367 auto securityMode
= loadInfo
->GetSecurityMode();
368 // The data: inheritance flags should only apply to the initial load,
369 // not to loads that it might have redirected to.
370 if (loadInfo
->RedirectChain().IsEmpty() &&
372 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
||
374 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
||
375 securityMode
== nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
)) {
376 nsCOMPtr
<nsIURI
> uri
;
377 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
378 NS_ENSURE_SUCCESS(rv
, rv
);
380 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
381 loadInfo
->FindPrincipalToInherit(aChannel
);
382 bool inheritForAboutBlank
= loadInfo
->GetAboutBlankInherits();
384 if (nsContentUtils::ChannelShouldInheritPrincipal(
385 principalToInherit
, uri
, inheritForAboutBlank
, false)) {
386 principalToInherit
.forget(aPrincipal
);
390 return GetChannelURIPrincipal(aChannel
, aPrincipal
);
393 /* The principal of the URI that this channel is loading. This is never
394 * affected by things like sandboxed loads, or loads where we forcefully
395 * inherit the principal. Think of this as the principal of the server
396 * which this channel is loading from. Most callers should use
397 * GetChannelResultPrincipal instead of GetChannelURIPrincipal. Only
398 * call GetChannelURIPrincipal if you are sure that you want the
399 * principal that matches the uri, even in cases when the load is
400 * sandboxed or when the load could be a blob or data uri (i.e even when
401 * you encounter loads that may or may not be sandboxed and loads
402 * that may or may not inherit)."
405 nsScriptSecurityManager::GetChannelURIPrincipal(nsIChannel
* aChannel
,
406 nsIPrincipal
** aPrincipal
) {
407 MOZ_ASSERT(aChannel
, "Must have channel!");
409 // Get the principal from the URI. Make sure this does the same thing
410 // as Document::Reset and PrototypeDocumentContentSink::Init.
411 nsCOMPtr
<nsIURI
> uri
;
412 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
413 NS_ENSURE_SUCCESS(rv
, rv
);
415 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
417 // Inherit the origin attributes from loadInfo.
418 // If this is a top-level document load, the origin attributes of the
419 // loadInfo will be set from nsDocShell::DoURILoad.
420 // For subresource loading, the origin attributes of the loadInfo is from
421 // its loadingPrincipal.
422 OriginAttributes attrs
= loadInfo
->GetOriginAttributes();
424 // If the URI is supposed to inherit the security context of whoever loads it,
425 // we shouldn't make a content principal for it, so instead return a null
427 bool inheritsPrincipal
= false;
428 rv
= NS_URIChainHasFlags(uri
,
429 nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT
,
431 if (NS_FAILED(rv
) || inheritsPrincipal
) {
432 // Find a precursor principal to credit for the load. This won't impact
433 // security checks, but makes tracking the source of related loads easier.
434 nsCOMPtr
<nsIPrincipal
> precursorPrincipal
=
435 loadInfo
->FindPrincipalToInherit(aChannel
);
436 nsCOMPtr
<nsIURI
> nullPrincipalURI
=
437 NullPrincipal::CreateURI(precursorPrincipal
);
438 *aPrincipal
= NullPrincipal::Create(attrs
, nullPrincipalURI
).take();
439 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
442 nsCOMPtr
<nsIPrincipal
> prin
=
443 BasePrincipal::CreateContentPrincipal(uri
, attrs
);
444 prin
.forget(aPrincipal
);
445 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
448 /////////////////////////////
449 // nsScriptSecurityManager //
450 /////////////////////////////
452 ////////////////////////////////////
453 // Methods implementing ISupports //
454 ////////////////////////////////////
455 NS_IMPL_ISUPPORTS(nsScriptSecurityManager
, nsIScriptSecurityManager
)
457 ///////////////////////////////////////////////////
458 // Methods implementing nsIScriptSecurityManager //
459 ///////////////////////////////////////////////////
461 ///////////////// Security Checks /////////////////
463 bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
464 JSContext
* cx
, JS::RuntimeCode aKind
, JS::Handle
<JSString
*> aCode
) {
465 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
467 nsCOMPtr
<nsIPrincipal
> subjectPrincipal
= nsContentUtils::SubjectPrincipal();
469 // Check if Eval is allowed per firefox hardening policy
470 bool contextForbidsEval
=
471 (subjectPrincipal
->IsSystemPrincipal() || XRE_IsE10sParentProcess());
473 contextForbidsEval
= false;
476 if (contextForbidsEval
) {
477 nsAutoJSString scriptSample
;
478 if (aKind
== JS::RuntimeCode::JS
&&
479 NS_WARN_IF(!scriptSample
.init(cx
, aCode
))) {
483 if (!nsContentSecurityUtils::IsEvalAllowed(
484 cx
, subjectPrincipal
->IsSystemPrincipal(), scriptSample
)) {
489 // Get the window, if any, corresponding to the current global
490 nsCOMPtr
<nsIContentSecurityPolicy
> csp
;
491 if (nsGlobalWindowInner
* win
= xpc::CurrentWindowOrNull(cx
)) {
496 // Get the CSP for addon sandboxes. If the principal is expanded and has a
497 // csp, we're probably in luck.
498 auto* basePrin
= BasePrincipal::Cast(subjectPrincipal
);
499 // ContentScriptAddonPolicy means it is also an expanded principal, thus
500 // this is in a sandbox used as a content script.
501 if (basePrin
->ContentScriptAddonPolicy()) {
502 basePrin
->As
<ExpandedPrincipal
>()->GetCsp(getter_AddRefs(csp
));
504 // don't do anything unless there's a CSP
510 nsCOMPtr
<nsICSPEventListener
> cspEventListener
;
511 if (!NS_IsMainThread()) {
512 WorkerPrivate
* workerPrivate
=
513 mozilla::dom::GetWorkerPrivateFromContext(cx
);
515 cspEventListener
= workerPrivate
->CSPEventListener();
520 bool reportViolation
= false;
521 if (aKind
== JS::RuntimeCode::JS
) {
522 nsresult rv
= csp
->GetAllowsEval(&reportViolation
, &evalOK
);
524 NS_WARNING("CSP: failed to get allowsEval");
525 return true; // fail open to not break sites.
528 if (NS_FAILED(csp
->GetAllowsWasmEval(&reportViolation
, &evalOK
))) {
532 // Historically, CSP did not block WebAssembly in Firefox, and some
533 // add-ons use wasm and a stricter CSP. To avoid breaking them, ignore
534 // 'wasm-unsafe-eval' violations for MV2 extensions.
535 // TODO bug 1770909: remove this exception.
536 auto* addonPolicy
= BasePrincipal::Cast(subjectPrincipal
)->AddonPolicy();
537 if (addonPolicy
&& addonPolicy
->ManifestVersion() == 2) {
538 reportViolation
= true;
544 if (reportViolation
) {
545 JS::AutoFilename scriptFilename
;
546 nsAutoString fileName
;
547 uint32_t lineNum
= 0;
548 JS::ColumnNumberOneOrigin columnNum
;
549 if (JS::DescribeScriptedCaller(cx
, &scriptFilename
, &lineNum
, &columnNum
)) {
550 if (const char* file
= scriptFilename
.get()) {
551 CopyUTF8toUTF16(nsDependentCString(file
), fileName
);
554 MOZ_ASSERT(!JS_IsExceptionPending(cx
));
557 nsAutoJSString scriptSample
;
558 if (aKind
== JS::RuntimeCode::JS
&&
559 NS_WARN_IF(!scriptSample
.init(cx
, aCode
))) {
560 JS_ClearPendingException(cx
);
563 uint16_t violationType
=
564 aKind
== JS::RuntimeCode::JS
565 ? nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL
566 : nsIContentSecurityPolicy::VIOLATION_TYPE_WASM_EVAL
;
567 csp
->LogViolationDetails(violationType
,
568 nullptr, // triggering element
569 cspEventListener
, fileName
, scriptSample
, lineNum
,
570 columnNum
.oneOriginValue(), u
""_ns
, u
""_ns
);
577 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals
* first
,
578 JSPrincipals
* second
) {
579 return nsJSPrincipals::get(first
)->Subsumes(nsJSPrincipals::get(second
));
583 nsScriptSecurityManager::CheckSameOriginURI(nsIURI
* aSourceURI
,
586 bool aFromPrivateWindow
) {
587 // Please note that aFromPrivateWindow is only 100% accurate if
588 // reportError is true.
589 if (!SecurityCompareURIs(aSourceURI
, aTargetURI
)) {
591 ReportError("CheckSameOriginError", aSourceURI
, aTargetURI
,
594 return NS_ERROR_DOM_BAD_URI
;
600 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext
* cx
, nsIURI
* aURI
) {
601 // Get principal of currently executing script.
602 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
603 nsIPrincipal
* principal
= nsContentUtils::SubjectPrincipal();
604 nsresult rv
= CheckLoadURIWithPrincipal(
605 // Passing 0 for the window ID here is OK, because we will report a
606 // script-visible exception anyway.
607 principal
, aURI
, nsIScriptSecurityManager::STANDARD
, 0);
608 if (NS_SUCCEEDED(rv
)) {
615 if (NS_FAILED(aURI
->GetAsciiSpec(spec
))) return NS_ERROR_FAILURE
;
616 nsAutoCString
msg("Access to '");
618 msg
.AppendLiteral("' from script denied");
619 SetPendingExceptionASCII(cx
, msg
.get());
620 return NS_ERROR_DOM_BAD_URI
;
624 * Helper method to handle cases where a flag passed to
625 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
626 * nsIProtocolHandler flags set.
627 * @return if success, access is allowed. Otherwise, deny access
629 static nsresult
DenyAccessIfURIHasFlags(nsIURI
* aURI
, uint32_t aURIFlags
) {
630 MOZ_ASSERT(aURI
, "Must have URI!");
633 nsresult rv
= NS_URIChainHasFlags(aURI
, aURIFlags
, &uriHasFlags
);
634 NS_ENSURE_SUCCESS(rv
, rv
);
637 return NS_ERROR_DOM_BAD_URI
;
643 static bool EqualOrSubdomain(nsIURI
* aProbeArg
, nsIURI
* aBase
) {
645 nsCOMPtr
<nsIURI
> probe
= aProbeArg
;
647 nsCOMPtr
<nsIEffectiveTLDService
> tldService
=
648 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID
);
649 NS_ENSURE_TRUE(tldService
, false);
651 if (nsScriptSecurityManager::SecurityCompareURIs(probe
, aBase
)) {
655 nsAutoCString host
, newHost
;
656 rv
= probe
->GetHost(host
);
657 NS_ENSURE_SUCCESS(rv
, false);
659 rv
= tldService
->GetNextSubDomain(host
, newHost
);
660 if (rv
== NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS
) {
663 NS_ENSURE_SUCCESS(rv
, false);
664 rv
= NS_MutateURI(probe
).SetHost(newHost
).Finalize(probe
);
665 NS_ENSURE_SUCCESS(rv
, false);
670 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal
* aPrincipal
,
673 uint64_t aInnerWindowID
) {
674 MOZ_ASSERT(aPrincipal
, "CheckLoadURIWithPrincipal must have a principal");
676 // If someone passes a flag that we don't understand, we should
677 // fail, because they may need a security check that we don't
681 ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
|
682 nsIScriptSecurityManager::ALLOW_CHROME
|
683 nsIScriptSecurityManager::DISALLOW_SCRIPT
|
684 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
|
685 nsIScriptSecurityManager::DONT_REPORT_ERRORS
),
686 NS_ERROR_UNEXPECTED
);
687 NS_ENSURE_ARG_POINTER(aPrincipal
);
688 NS_ENSURE_ARG_POINTER(aTargetURI
);
690 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
691 // would do such inheriting. That would be URIs that do not have their own
692 // security context. We do this even for the system principal.
693 if (aFlags
& nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
) {
694 nsresult rv
= DenyAccessIfURIHasFlags(
695 aTargetURI
, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT
);
696 NS_ENSURE_SUCCESS(rv
, rv
);
699 if (aPrincipal
== mSystemPrincipal
) {
704 nsCOMPtr
<nsIURI
> sourceURI
;
705 auto* basePrin
= BasePrincipal::Cast(aPrincipal
);
706 basePrin
->GetURI(getter_AddRefs(sourceURI
));
708 if (basePrin
->Is
<ExpandedPrincipal
>()) {
709 // If the target addon is MV3 or the pref is on we require extension
710 // resources loaded from content to be listed in web_accessible_resources.
712 ExtensionPolicyService::GetSingleton().GetByURL(aTargetURI
);
713 bool contentAccessRequired
=
715 (targetPolicy
->ManifestVersion() > 2 ||
716 StaticPrefs::extensions_content_web_accessible_enabled());
717 auto expanded
= basePrin
->As
<ExpandedPrincipal
>();
718 const auto& allowList
= expanded
->AllowList();
719 // Only report errors when all principals fail.
720 // With expanded principals, which are used by extension content scripts,
721 // we check only against non-extension principals for access to extension
722 // resource to enforce making those resources explicitly web accessible.
723 uint32_t flags
= aFlags
| nsIScriptSecurityManager::DONT_REPORT_ERRORS
;
724 for (size_t i
= 0; i
< allowList
.Length() - 1; i
++) {
725 if (contentAccessRequired
&&
726 BasePrincipal::Cast(allowList
[i
])->AddonPolicy()) {
729 nsresult rv
= CheckLoadURIWithPrincipal(allowList
[i
], aTargetURI
, flags
,
731 if (NS_SUCCEEDED(rv
)) {
732 // Allow access if it succeeded with one of the allowlisted principals
737 if (contentAccessRequired
&&
738 BasePrincipal::Cast(allowList
.LastElement())->AddonPolicy()) {
740 !(aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
);
742 ReportError("CheckLoadURI", sourceURI
, aTargetURI
,
743 allowList
.LastElement()
744 ->OriginAttributesRef()
745 .mPrivateBrowsingId
> 0,
748 return NS_ERROR_DOM_BAD_URI
;
750 // Report errors (if requested) for the last principal.
751 return CheckLoadURIWithPrincipal(allowList
.LastElement(), aTargetURI
,
752 aFlags
, aInnerWindowID
);
755 "Non-system principals or expanded principal passed to "
756 "CheckLoadURIWithPrincipal "
758 return NS_ERROR_UNEXPECTED
;
761 // Automatic loads are not allowed from certain protocols.
763 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
) {
764 nsresult rv
= DenyAccessIfURIHasFlags(
766 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT
);
767 NS_ENSURE_SUCCESS(rv
, rv
);
770 // If either URI is a nested URI, get the base URI
771 nsCOMPtr
<nsIURI
> sourceBaseURI
= NS_GetInnermostURI(sourceURI
);
772 nsCOMPtr
<nsIURI
> targetBaseURI
= NS_GetInnermostURI(aTargetURI
);
774 //-- get the target scheme
775 nsAutoCString targetScheme
;
776 nsresult rv
= targetBaseURI
->GetScheme(targetScheme
);
777 if (NS_FAILED(rv
)) return rv
;
779 //-- Some callers do not allow loading javascript:
780 if ((aFlags
& nsIScriptSecurityManager::DISALLOW_SCRIPT
) &&
781 targetScheme
.EqualsLiteral("javascript")) {
782 return NS_ERROR_DOM_BAD_URI
;
785 // Check for uris that are only loadable by principals that subsume them
786 bool targetURIIsLoadableBySubsumers
= false;
787 rv
= NS_URIChainHasFlags(targetBaseURI
,
788 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
789 &targetURIIsLoadableBySubsumers
);
790 NS_ENSURE_SUCCESS(rv
, rv
);
792 if (targetURIIsLoadableBySubsumers
) {
793 // check nothing else in the URI chain has flags that prevent
795 rv
= CheckLoadURIFlags(
796 sourceURI
, aTargetURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
797 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
799 NS_ENSURE_SUCCESS(rv
, rv
);
800 // Check the principal is allowed to load the target.
801 if (aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
) {
802 return aPrincipal
->CheckMayLoad(targetBaseURI
, false);
804 return aPrincipal
->CheckMayLoadWithReporting(targetBaseURI
, false,
808 //-- get the source scheme
809 nsAutoCString sourceScheme
;
810 rv
= sourceBaseURI
->GetScheme(sourceScheme
);
811 if (NS_FAILED(rv
)) return rv
;
813 if (sourceScheme
.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME
)) {
814 // A null principal can target its own URI.
815 if (sourceURI
== aTargetURI
) {
818 } else if (sourceScheme
.EqualsIgnoreCase("file") &&
819 targetScheme
.EqualsIgnoreCase("moz-icon")) {
820 // exception for file: linking to moz-icon://.ext?size=...
821 // Note that because targetScheme is the base (innermost) URI scheme,
822 // this does NOT allow file -> moz-icon:file:///... links.
823 // This is intentional.
827 // Check for webextension
828 bool targetURIIsLoadableByExtensions
= false;
829 rv
= NS_URIChainHasFlags(aTargetURI
,
830 nsIProtocolHandler::URI_LOADABLE_BY_EXTENSIONS
,
831 &targetURIIsLoadableByExtensions
);
832 NS_ENSURE_SUCCESS(rv
, rv
);
834 if (targetURIIsLoadableByExtensions
&&
835 BasePrincipal::Cast(aPrincipal
)->AddonPolicy()) {
839 // If we get here, check all the schemes can link to each other, from the top
841 nsCOMPtr
<nsIURI
> currentURI
= sourceURI
;
842 nsCOMPtr
<nsIURI
> currentOtherURI
= aTargetURI
;
844 bool denySameSchemeLinks
= false;
845 rv
= NS_URIChainHasFlags(aTargetURI
,
846 nsIProtocolHandler::URI_SCHEME_NOT_SELF_LINKABLE
,
847 &denySameSchemeLinks
);
848 if (NS_FAILED(rv
)) return rv
;
850 while (currentURI
&& currentOtherURI
) {
851 nsAutoCString scheme
, otherScheme
;
852 currentURI
->GetScheme(scheme
);
853 currentOtherURI
->GetScheme(otherScheme
);
856 scheme
.Equals(otherScheme
, nsCaseInsensitiveCStringComparator
);
857 bool isSamePage
= false;
858 bool isExtensionMismatch
= false;
859 // about: URIs are special snowflakes.
860 if (scheme
.EqualsLiteral("about") && schemesMatch
) {
861 nsAutoCString moduleName
, otherModuleName
;
862 // about: pages can always link to themselves:
864 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI
, moduleName
)) &&
866 NS_GetAboutModuleName(currentOtherURI
, otherModuleName
)) &&
867 moduleName
.Equals(otherModuleName
);
869 // We will have allowed the load earlier if the source page has
870 // system principal. So we know the source has a content
871 // principal, and it's trying to link to something else.
872 // Linkable about: pages are always reachable, even if we hit
873 // the CheckLoadURIFlags call below.
874 // We punch only 1 other hole: iff the source is unlinkable,
875 // we let them link to other pages explicitly marked SAFE
876 // for content. This avoids world-linkable about: pages linking
877 // to non-world-linkable about: pages.
878 nsCOMPtr
<nsIAboutModule
> module
, otherModule
;
879 bool knowBothModules
=
881 NS_GetAboutModule(currentURI
, getter_AddRefs(module
))) &&
882 NS_SUCCEEDED(NS_GetAboutModule(currentOtherURI
,
883 getter_AddRefs(otherModule
)));
884 uint32_t aboutModuleFlags
= 0;
885 uint32_t otherAboutModuleFlags
= 0;
888 NS_SUCCEEDED(module
->GetURIFlags(currentURI
, &aboutModuleFlags
)) &&
889 NS_SUCCEEDED(otherModule
->GetURIFlags(currentOtherURI
,
890 &otherAboutModuleFlags
));
891 if (knowBothModules
) {
892 isSamePage
= !(aboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) &&
893 (otherAboutModuleFlags
&
894 nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT
);
896 otherAboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) {
897 // XXXgijs: this is a hack. The target will be nested
898 // (with innerURI of moz-safe-about:whatever), and
899 // the source isn't, so we won't pass if we finish
900 // the loop. We *should* pass, though, so return here.
901 // This hack can go away when bug 1228118 is fixed.
906 } else if (schemesMatch
&& scheme
.EqualsLiteral("moz-extension")) {
907 // If it is not the same exension, we want to ensure we end up
908 // calling CheckLoadURIFlags
909 nsAutoCString host
, otherHost
;
910 currentURI
->GetHost(host
);
911 currentOtherURI
->GetHost(otherHost
);
912 isExtensionMismatch
= !host
.Equals(otherHost
);
914 bool equalExceptRef
= false;
915 rv
= currentURI
->EqualsExceptRef(currentOtherURI
, &equalExceptRef
);
916 isSamePage
= NS_SUCCEEDED(rv
) && equalExceptRef
;
919 // If schemes are not equal, or they're equal but the target URI
920 // is different from the source URI and doesn't always allow linking
921 // from the same scheme, or this is two different extensions, check
922 // if the URI flags of the current target URI allow the current
923 // source URI to link to it.
924 // The policy is specified by the protocol flags on both URIs.
925 if (!schemesMatch
|| (denySameSchemeLinks
&& !isSamePage
) ||
926 isExtensionMismatch
) {
927 return CheckLoadURIFlags(
928 currentURI
, currentOtherURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
929 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
932 // Otherwise... check if we can nest another level:
933 nsCOMPtr
<nsINestedURI
> nestedURI
= do_QueryInterface(currentURI
);
934 nsCOMPtr
<nsINestedURI
> nestedOtherURI
= do_QueryInterface(currentOtherURI
);
936 // If schemes match and neither URI is nested further, we're OK.
937 if (!nestedURI
&& !nestedOtherURI
) {
940 // If one is nested and the other isn't, something is wrong.
941 if (!nestedURI
!= !nestedOtherURI
) {
942 return NS_ERROR_DOM_BAD_URI
;
944 // Otherwise, both should be nested and we'll go through the loop again.
945 nestedURI
->GetInnerURI(getter_AddRefs(currentURI
));
946 nestedOtherURI
->GetInnerURI(getter_AddRefs(currentOtherURI
));
949 // We should never get here. We should always return from inside the loop.
950 return NS_ERROR_DOM_BAD_URI
;
954 * Helper method to check whether the target URI and its innermost ("base") URI
955 * has protocol flags that should stop it from being loaded by the source URI
956 * (and/or the source URI's innermost ("base") URI), taking into account any
957 * nsIScriptSecurityManager flags originally passed to
958 * CheckLoadURIWithPrincipal and friends.
960 * @return if success, access is allowed. Otherwise, deny access
962 nsresult
nsScriptSecurityManager::CheckLoadURIFlags(
963 nsIURI
* aSourceURI
, nsIURI
* aTargetURI
, nsIURI
* aSourceBaseURI
,
964 nsIURI
* aTargetBaseURI
, uint32_t aFlags
, bool aFromPrivateWindow
,
965 uint64_t aInnerWindowID
) {
966 // Note that the order of policy checks here is very important!
967 // We start from most restrictive and work our way down.
968 bool reportErrors
= !(aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
);
969 const char* errorTag
= "CheckLoadURIError";
971 nsAutoCString targetScheme
;
972 nsresult rv
= aTargetBaseURI
->GetScheme(targetScheme
);
973 if (NS_FAILED(rv
)) return rv
;
975 // Check for system target URI. Regular (non web accessible) extension
976 // URIs will also have URI_DANGEROUS_TO_LOAD.
977 rv
= DenyAccessIfURIHasFlags(aTargetURI
,
978 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD
);
980 // Deny access, since the origin principal is not system
982 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
988 // Used by ExtensionProtocolHandler to prevent loading extension resources
989 // in private contexts if the extension does not have permission.
990 if (aFromPrivateWindow
) {
991 rv
= DenyAccessIfURIHasFlags(
992 aTargetURI
, nsIProtocolHandler::URI_DISALLOW_IN_PRIVATE_CONTEXT
);
995 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1002 // If MV3 Extension uris are web accessible they have
1003 // WEBEXT_URI_WEB_ACCESSIBLE.
1004 bool maybeWebAccessible
= false;
1005 NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::WEBEXT_URI_WEB_ACCESSIBLE
,
1006 &maybeWebAccessible
);
1007 NS_ENSURE_SUCCESS(rv
, rv
);
1008 if (maybeWebAccessible
) {
1009 bool isWebAccessible
= false;
1010 rv
= ExtensionPolicyService::GetSingleton().SourceMayLoadExtensionURI(
1011 aSourceURI
, aTargetURI
, &isWebAccessible
);
1012 if (NS_SUCCEEDED(rv
) && isWebAccessible
) {
1016 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1019 return NS_ERROR_DOM_BAD_URI
;
1022 // Check for chrome target URI
1023 bool targetURIIsUIResource
= false;
1024 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_UI_RESOURCE
,
1025 &targetURIIsUIResource
);
1026 NS_ENSURE_SUCCESS(rv
, rv
);
1027 if (targetURIIsUIResource
) {
1028 // ALLOW_CHROME is a flag that we pass on all loads _except_ docshell
1029 // loads (since docshell loads run the loaded content with its origin
1030 // principal). We are effectively allowing resource:// and chrome://
1031 // URIs to load as long as they are content accessible and as long
1032 // they're not loading it as a document.
1033 if (aFlags
& nsIScriptSecurityManager::ALLOW_CHROME
) {
1034 bool sourceIsUIResource
= false;
1035 rv
= NS_URIChainHasFlags(aSourceBaseURI
,
1036 nsIProtocolHandler::URI_IS_UI_RESOURCE
,
1037 &sourceIsUIResource
);
1038 NS_ENSURE_SUCCESS(rv
, rv
);
1039 if (sourceIsUIResource
) {
1040 // Special case for moz-icon URIs loaded by a local resources like
1041 // e.g. chrome: or resource:
1042 if (targetScheme
.EqualsLiteral("moz-icon")) {
1047 if (targetScheme
.EqualsLiteral("resource")) {
1048 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
1052 nsCOMPtr
<nsIProtocolHandler
> ph
;
1053 rv
= sIOService
->GetProtocolHandler("resource", getter_AddRefs(ph
));
1054 NS_ENSURE_SUCCESS(rv
, rv
);
1056 return NS_ERROR_DOM_BAD_URI
;
1059 nsCOMPtr
<nsIResProtocolHandler
> rph
= do_QueryInterface(ph
);
1061 return NS_ERROR_DOM_BAD_URI
;
1064 bool accessAllowed
= false;
1065 rph
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
1066 if (accessAllowed
) {
1069 } else if (targetScheme
.EqualsLiteral("chrome")) {
1070 // Allow the load only if the chrome package is allowlisted.
1071 nsCOMPtr
<nsIXULChromeRegistry
> reg(
1072 do_GetService(NS_CHROMEREGISTRY_CONTRACTID
));
1074 bool accessAllowed
= false;
1075 reg
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
1076 if (accessAllowed
) {
1080 } else if (targetScheme
.EqualsLiteral("moz-page-thumb") ||
1081 targetScheme
.EqualsLiteral("page-icon")) {
1082 if (XRE_IsParentProcess()) {
1086 auto& remoteType
= dom::ContentChild::GetSingleton()->GetRemoteType();
1087 if (remoteType
== PRIVILEGEDABOUT_REMOTE_TYPE
) {
1094 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1097 return NS_ERROR_DOM_BAD_URI
;
1100 // Check for target URI pointing to a file
1101 bool targetURIIsLocalFile
= false;
1102 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_LOCAL_FILE
,
1103 &targetURIIsLocalFile
);
1104 NS_ENSURE_SUCCESS(rv
, rv
);
1105 if (targetURIIsLocalFile
) {
1106 // Allow domains that were allowlisted in the prefs. In 99.9% of cases,
1107 // this array is empty.
1109 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI
, &isAllowlisted
));
1110 if (isAllowlisted
) {
1115 if (aSourceBaseURI
->SchemeIs("chrome")) {
1121 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1124 return NS_ERROR_DOM_BAD_URI
;
1129 // Everyone is allowed to load this. The case URI_LOADABLE_BY_SUBSUMERS
1130 // is handled by the caller which is just delegating to us as a helper.
1131 bool hasSubsumersFlag
= false;
1132 NS_URIChainHasFlags(aTargetBaseURI
,
1133 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
1135 bool hasLoadableByAnyone
= false;
1136 NS_URIChainHasFlags(aTargetBaseURI
,
1137 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE
,
1138 &hasLoadableByAnyone
);
1139 MOZ_ASSERT(hasLoadableByAnyone
|| hasSubsumersFlag
,
1140 "why do we get here and do not have any of the two flags set?");
1147 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1148 const nsACString
& aSourceSpec
,
1149 const nsACString
& aTargetSpec
,
1150 bool aFromPrivateWindow
,
1151 uint64_t aInnerWindowID
) {
1152 if (aSourceSpec
.IsEmpty() || aTargetSpec
.IsEmpty()) {
1156 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1157 if (NS_WARN_IF(!bundle
)) {
1161 // Localize the error message
1162 nsAutoString message
;
1163 AutoTArray
<nsString
, 2> formatStrings
;
1164 CopyASCIItoUTF16(aSourceSpec
, *formatStrings
.AppendElement());
1165 CopyASCIItoUTF16(aTargetSpec
, *formatStrings
.AppendElement());
1167 bundle
->FormatStringFromName(aMessageTag
, formatStrings
, message
);
1168 NS_ENSURE_SUCCESS(rv
, rv
);
1170 nsCOMPtr
<nsIConsoleService
> console(
1171 do_GetService(NS_CONSOLESERVICE_CONTRACTID
));
1172 NS_ENSURE_TRUE(console
, NS_ERROR_FAILURE
);
1173 nsCOMPtr
<nsIScriptError
> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID
));
1174 NS_ENSURE_TRUE(error
, NS_ERROR_FAILURE
);
1176 // using category of "SOP" so we can link to MDN
1177 if (aInnerWindowID
!= 0) {
1178 rv
= error
->InitWithWindowID(
1179 message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
, "SOP"_ns
,
1180 aInnerWindowID
, true /* From chrome context */);
1182 rv
= error
->Init(message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
,
1183 "SOP"_ns
, aFromPrivateWindow
,
1184 true /* From chrome context */);
1186 NS_ENSURE_SUCCESS(rv
, rv
);
1187 console
->LogMessage(error
);
1191 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1192 nsIURI
* aSource
, nsIURI
* aTarget
,
1193 bool aFromPrivateWindow
,
1194 uint64_t aInnerWindowID
) {
1195 NS_ENSURE_TRUE(aSource
&& aTarget
, NS_ERROR_NULL_POINTER
);
1197 // Get the source URL spec
1198 nsAutoCString sourceSpec
;
1199 nsresult rv
= aSource
->GetAsciiSpec(sourceSpec
);
1200 NS_ENSURE_SUCCESS(rv
, rv
);
1202 // Get the target URL spec
1203 nsAutoCString targetSpec
;
1204 rv
= aTarget
->GetAsciiSpec(targetSpec
);
1205 NS_ENSURE_SUCCESS(rv
, rv
);
1207 return ReportError(aMessageTag
, sourceSpec
, targetSpec
, aFromPrivateWindow
,
1212 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1213 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
,
1216 nsCOMPtr
<nsIURI
> target
;
1217 rv
= NS_NewURI(getter_AddRefs(target
), aTargetURIStr
);
1218 NS_ENSURE_SUCCESS(rv
, rv
);
1220 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1221 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1222 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1226 NS_ENSURE_SUCCESS(rv
, rv
);
1228 // Now start testing fixup -- since aTargetURIStr is a string, not
1229 // an nsIURI, we may well end up fixing it up before loading.
1230 // Note: This needs to stay in sync with the nsIURIFixup api.
1231 nsCOMPtr
<nsIURIFixup
> fixup
= components::URIFixup::Service();
1236 // URIFixup's keyword and alternate flags can only fixup to http/https, so we
1237 // can skip testing them. This simplifies our life because this code can be
1238 // invoked from the content process where the search service would not be
1240 uint32_t flags
[] = {nsIURIFixup::FIXUP_FLAG_NONE
,
1241 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS
};
1242 for (uint32_t i
= 0; i
< ArrayLength(flags
); ++i
) {
1243 uint32_t fixupFlags
= flags
[i
];
1244 if (aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0) {
1245 fixupFlags
|= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT
;
1247 nsCOMPtr
<nsIURIFixupInfo
> fixupInfo
;
1248 rv
= fixup
->GetFixupURIInfo(aTargetURIStr
, fixupFlags
,
1249 getter_AddRefs(fixupInfo
));
1250 NS_ENSURE_SUCCESS(rv
, rv
);
1251 rv
= fixupInfo
->GetPreferredURI(getter_AddRefs(target
));
1252 NS_ENSURE_SUCCESS(rv
, rv
);
1254 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1255 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1256 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1260 NS_ENSURE_SUCCESS(rv
, rv
);
1267 nsScriptSecurityManager::CheckLoadURIWithPrincipalFromJS(
1268 nsIPrincipal
* aPrincipal
, nsIURI
* aTargetURI
, uint32_t aFlags
,
1269 uint64_t aInnerWindowID
, JSContext
* aCx
) {
1270 MOZ_ASSERT(aPrincipal
,
1271 "CheckLoadURIWithPrincipalFromJS must have a principal");
1272 NS_ENSURE_ARG_POINTER(aPrincipal
);
1273 NS_ENSURE_ARG_POINTER(aTargetURI
);
1276 CheckLoadURIWithPrincipal(aPrincipal
, aTargetURI
, aFlags
, aInnerWindowID
);
1277 if (NS_FAILED(rv
)) {
1278 nsAutoCString uriStr
;
1279 Unused
<< aTargetURI
->GetSpec(uriStr
);
1281 nsAutoCString
message("Load of ");
1282 message
.Append(uriStr
);
1284 nsAutoCString principalStr
;
1285 Unused
<< aPrincipal
->GetSpec(principalStr
);
1286 if (!principalStr
.IsEmpty()) {
1287 message
.AppendPrintf(" from %s", principalStr
.get());
1290 message
.Append(" denied");
1292 dom::Throw(aCx
, rv
, message
);
1299 nsScriptSecurityManager::CheckLoadURIStrWithPrincipalFromJS(
1300 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
, uint32_t aFlags
,
1302 nsCOMPtr
<nsIURI
> targetURI
;
1303 MOZ_TRY(NS_NewURI(getter_AddRefs(targetURI
), aTargetURIStr
));
1305 return CheckLoadURIWithPrincipalFromJS(aPrincipal
, targetURI
, aFlags
, 0, aCx
);
1309 nsScriptSecurityManager::InFileURIAllowlist(nsIURI
* aUri
, bool* aResult
) {
1311 MOZ_ASSERT(aResult
);
1314 for (nsIURI
* uri
: EnsureFileURIAllowlist()) {
1315 if (EqualOrSubdomain(aUri
, uri
)) {
1324 ///////////////// Principals ///////////////////////
1327 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal
** result
) {
1328 NS_ADDREF(*result
= mSystemPrincipal
);
1334 nsScriptSecurityManager::CreateContentPrincipal(
1335 nsIURI
* aURI
, JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1336 nsIPrincipal
** aPrincipal
) {
1337 OriginAttributes attrs
;
1338 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1339 return NS_ERROR_INVALID_ARG
;
1341 nsCOMPtr
<nsIPrincipal
> prin
=
1342 BasePrincipal::CreateContentPrincipal(aURI
, attrs
);
1343 prin
.forget(aPrincipal
);
1344 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1348 nsScriptSecurityManager::CreateContentPrincipalFromOrigin(
1349 const nsACString
& aOrigin
, nsIPrincipal
** aPrincipal
) {
1350 if (StringBeginsWith(aOrigin
, "["_ns
)) {
1351 return NS_ERROR_INVALID_ARG
;
1354 if (StringBeginsWith(aOrigin
,
1355 nsLiteralCString(NS_NULLPRINCIPAL_SCHEME
":"))) {
1356 return NS_ERROR_INVALID_ARG
;
1359 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(aOrigin
);
1360 prin
.forget(aPrincipal
);
1361 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1365 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal
* aPrincipal
,
1366 nsACString
& aJSON
) {
1369 return NS_ERROR_FAILURE
;
1372 BasePrincipal::Cast(aPrincipal
)->ToJSON(aJSON
);
1374 if (aJSON
.IsEmpty()) {
1375 return NS_ERROR_FAILURE
;
1382 nsScriptSecurityManager::JSONToPrincipal(const nsACString
& aJSON
,
1383 nsIPrincipal
** aPrincipal
) {
1384 if (aJSON
.IsEmpty()) {
1385 return NS_ERROR_FAILURE
;
1388 nsCOMPtr
<nsIPrincipal
> principal
= BasePrincipal::FromJSON(aJSON
);
1391 return NS_ERROR_FAILURE
;
1394 principal
.forget(aPrincipal
);
1399 nsScriptSecurityManager::CreateNullPrincipal(
1400 JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1401 nsIPrincipal
** aPrincipal
) {
1402 OriginAttributes attrs
;
1403 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1404 return NS_ERROR_INVALID_ARG
;
1406 nsCOMPtr
<nsIPrincipal
> prin
= NullPrincipal::Create(attrs
);
1407 prin
.forget(aPrincipal
);
1412 nsScriptSecurityManager::GetLoadContextContentPrincipal(
1413 nsIURI
* aURI
, nsILoadContext
* aLoadContext
, nsIPrincipal
** aPrincipal
) {
1414 NS_ENSURE_STATE(aLoadContext
);
1415 OriginAttributes docShellAttrs
;
1416 aLoadContext
->GetOriginAttributes(docShellAttrs
);
1418 nsCOMPtr
<nsIPrincipal
> prin
=
1419 BasePrincipal::CreateContentPrincipal(aURI
, docShellAttrs
);
1420 prin
.forget(aPrincipal
);
1421 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1425 nsScriptSecurityManager::GetDocShellContentPrincipal(
1426 nsIURI
* aURI
, nsIDocShell
* aDocShell
, nsIPrincipal
** aPrincipal
) {
1427 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(
1428 aURI
, nsDocShell::Cast(aDocShell
)->GetOriginAttributes());
1429 prin
.forget(aPrincipal
);
1430 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1434 nsScriptSecurityManager::PrincipalWithOA(
1435 nsIPrincipal
* aPrincipal
, JS::Handle
<JS::Value
> aOriginAttributes
,
1436 JSContext
* aCx
, nsIPrincipal
** aReturnPrincipal
) {
1440 if (aPrincipal
->GetIsContentPrincipal()) {
1441 OriginAttributes attrs
;
1442 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1443 return NS_ERROR_INVALID_ARG
;
1445 auto* contentPrincipal
= static_cast<ContentPrincipal
*>(aPrincipal
);
1446 RefPtr
<ContentPrincipal
> copy
=
1447 new ContentPrincipal(contentPrincipal
, attrs
);
1448 NS_ENSURE_TRUE(copy
, NS_ERROR_FAILURE
);
1449 copy
.forget(aReturnPrincipal
);
1451 // We do this for null principals, system principals (both fine)
1452 // ... and expanded principals, where we should probably do something
1453 // cleverer, but I also don't think we care too much.
1454 nsCOMPtr
<nsIPrincipal
> prin
= aPrincipal
;
1455 prin
.forget(aReturnPrincipal
);
1458 return *aReturnPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1462 nsScriptSecurityManager::CanCreateWrapper(JSContext
* cx
, const nsIID
& aIID
,
1464 nsIClassInfo
* aClassInfo
) {
1465 // XXX Special case for Exception ?
1467 // We give remote-XUL allowlisted domains a free pass here. See bug 932906.
1468 JS::Rooted
<JS::Realm
*> contextRealm(cx
, JS::GetCurrentRealmOrNull(cx
));
1469 MOZ_RELEASE_ASSERT(contextRealm
);
1470 if (!xpc::AllowContentXBLScope(contextRealm
)) {
1474 if (nsContentUtils::IsCallerChrome()) {
1478 //-- Access denied, report an error
1479 nsAutoCString originUTF8
;
1480 nsIPrincipal
* subjectPrincipal
= nsContentUtils::SubjectPrincipal();
1481 GetPrincipalDomainOrigin(subjectPrincipal
, originUTF8
);
1482 NS_ConvertUTF8toUTF16
originUTF16(originUTF8
);
1483 nsAutoCString classInfoNameUTF8
;
1485 aClassInfo
->GetClassDescription(classInfoNameUTF8
);
1487 if (classInfoNameUTF8
.IsEmpty()) {
1488 classInfoNameUTF8
.AssignLiteral("UnnamedClass");
1491 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1492 if (NS_WARN_IF(!bundle
)) {
1496 NS_ConvertUTF8toUTF16
classInfoUTF16(classInfoNameUTF8
);
1498 nsAutoString errorMsg
;
1499 if (originUTF16
.IsEmpty()) {
1500 AutoTArray
<nsString
, 1> formatStrings
= {classInfoUTF16
};
1501 rv
= bundle
->FormatStringFromName("CreateWrapperDenied", formatStrings
,
1504 AutoTArray
<nsString
, 2> formatStrings
= {classInfoUTF16
, originUTF16
};
1505 rv
= bundle
->FormatStringFromName("CreateWrapperDeniedForOrigin",
1506 formatStrings
, errorMsg
);
1508 NS_ENSURE_SUCCESS(rv
, rv
);
1510 SetPendingException(cx
, errorMsg
.get());
1511 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1515 nsScriptSecurityManager::CanCreateInstance(JSContext
* cx
, const nsCID
& aCID
) {
1516 if (nsContentUtils::IsCallerChrome()) {
1520 //-- Access denied, report an error
1521 nsAutoCString
errorMsg("Permission denied to create instance of class. CID=");
1522 char cidStr
[NSID_LENGTH
];
1523 aCID
.ToProvidedString(cidStr
);
1524 errorMsg
.Append(cidStr
);
1525 SetPendingExceptionASCII(cx
, errorMsg
.get());
1526 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1530 nsScriptSecurityManager::CanGetService(JSContext
* cx
, const nsCID
& aCID
) {
1531 if (nsContentUtils::IsCallerChrome()) {
1535 //-- Access denied, report an error
1536 nsAutoCString
errorMsg("Permission denied to get service. CID=");
1537 char cidStr
[NSID_LENGTH
];
1538 aCID
.ToProvidedString(cidStr
);
1539 errorMsg
.Append(cidStr
);
1540 SetPendingExceptionASCII(cx
, errorMsg
.get());
1541 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1544 const char sJSEnabledPrefName
[] = "javascript.enabled";
1545 const char sFileOriginPolicyPrefName
[] =
1546 "security.fileuri.strict_origin_policy";
1548 static const char* kObservedPrefs
[] = {sJSEnabledPrefName
,
1549 sFileOriginPolicyPrefName
,
1550 "capability.policy.", nullptr};
1552 /////////////////////////////////////////////
1553 // Constructor, Destructor, Initialization //
1554 /////////////////////////////////////////////
1555 nsScriptSecurityManager::nsScriptSecurityManager(void)
1556 : mPrefInitialized(false), mIsJavaScriptEnabled(false) {
1558 sizeof(intptr_t) == sizeof(void*),
1559 "intptr_t and void* have different lengths on this platform. "
1560 "This may cause a security failure with the SecurityLevel union.");
1563 nsresult
nsScriptSecurityManager::Init() {
1565 RefPtr
<nsIIOService
> io
= mozilla::components::IO::Service(&rv
);
1566 if (NS_FAILED(rv
)) {
1569 sIOService
= std::move(io
);
1572 // Create our system principal singleton
1573 mSystemPrincipal
= SystemPrincipal::Init();
1578 void nsScriptSecurityManager::InitJSCallbacks(JSContext
* aCx
) {
1579 //-- Register security check callback in the JS engine
1580 // Currently this is used to control access to function.caller
1582 static const JSSecurityCallbacks securityCallbacks
= {
1583 ContentSecurityPolicyPermitsJSAction
,
1584 JSPrincipalsSubsume
,
1587 MOZ_ASSERT(!JS_GetSecurityCallbacks(aCx
));
1588 JS_SetSecurityCallbacks(aCx
, &securityCallbacks
);
1589 JS_InitDestroyPrincipalsCallback(aCx
, nsJSPrincipals::Destroy
);
1591 JS_SetTrustedPrincipals(aCx
, BasePrincipal::Cast(mSystemPrincipal
));
1595 void nsScriptSecurityManager::ClearJSCallbacks(JSContext
* aCx
) {
1596 JS_SetSecurityCallbacks(aCx
, nullptr);
1597 JS_SetTrustedPrincipals(aCx
, nullptr);
1600 static StaticRefPtr
<nsScriptSecurityManager
> gScriptSecMan
;
1602 nsScriptSecurityManager::~nsScriptSecurityManager(void) {
1603 Preferences::UnregisterPrefixCallbacks(
1604 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1605 if (mDomainPolicy
) {
1606 mDomainPolicy
->Deactivate();
1608 // ContentChild might hold a reference to the domain policy,
1609 // and it might release it only after the security manager is
1610 // gone. But we can still assert this for the main process.
1611 MOZ_ASSERT_IF(XRE_IsParentProcess(), !mDomainPolicy
);
1614 void nsScriptSecurityManager::Shutdown() {
1615 sIOService
= nullptr;
1616 BundleHelper::Shutdown();
1617 SystemPrincipal::Shutdown();
1620 nsScriptSecurityManager
* nsScriptSecurityManager::GetScriptSecurityManager() {
1621 return gScriptSecMan
;
1625 void nsScriptSecurityManager::InitStatics() {
1626 RefPtr
<nsScriptSecurityManager
> ssManager
= new nsScriptSecurityManager();
1627 nsresult rv
= ssManager
->Init();
1628 if (NS_FAILED(rv
)) {
1629 MOZ_CRASH("ssManager->Init() failed");
1632 ClearOnShutdown(&gScriptSecMan
);
1633 gScriptSecMan
= ssManager
;
1636 // Currently this nsGenericFactory constructor is used only from FastLoad
1637 // (XPCOM object deserialization) code, when "creating" the system principal
1639 already_AddRefed
<SystemPrincipal
>
1640 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1642 return do_AddRef(gScriptSecMan
->mSystemPrincipal
)
1643 .downcast
<SystemPrincipal
>();
1647 struct IsWhitespace
{
1648 static bool Test(char aChar
) { return NS_IsAsciiWhitespace(aChar
); };
1650 struct IsWhitespaceOrComma
{
1651 static bool Test(char aChar
) {
1652 return aChar
== ',' || NS_IsAsciiWhitespace(aChar
);
1656 template <typename Predicate
>
1657 uint32_t SkipPast(const nsCString
& str
, uint32_t base
) {
1658 while (base
< str
.Length() && Predicate::Test(str
[base
])) {
1664 template <typename Predicate
>
1665 uint32_t SkipUntil(const nsCString
& str
, uint32_t base
) {
1666 while (base
< str
.Length() && !Predicate::Test(str
[base
])) {
1673 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref
,
1675 static_cast<nsScriptSecurityManager
*>(aSelf
)->ScriptSecurityPrefChanged(
1679 inline void nsScriptSecurityManager::ScriptSecurityPrefChanged(
1680 const char* aPref
) {
1681 MOZ_ASSERT(mPrefInitialized
);
1682 mIsJavaScriptEnabled
=
1683 Preferences::GetBool(sJSEnabledPrefName
, mIsJavaScriptEnabled
);
1684 sStrictFileOriginPolicy
=
1685 Preferences::GetBool(sFileOriginPolicyPrefName
, false);
1686 mFileURIAllowlist
.reset();
1689 void nsScriptSecurityManager::AddSitesToFileURIAllowlist(
1690 const nsCString
& aSiteList
) {
1691 for (uint32_t base
= SkipPast
<IsWhitespace
>(aSiteList
, 0), bound
= 0;
1692 base
< aSiteList
.Length();
1693 base
= SkipPast
<IsWhitespace
>(aSiteList
, bound
)) {
1694 // Grab the current site.
1695 bound
= SkipUntil
<IsWhitespace
>(aSiteList
, base
);
1696 nsAutoCString
site(Substring(aSiteList
, base
, bound
- base
));
1698 // Check if the URI is schemeless. If so, add both http and https.
1699 nsAutoCString unused
;
1700 if (NS_FAILED(sIOService
->ExtractScheme(site
, unused
))) {
1701 AddSitesToFileURIAllowlist("http://"_ns
+ site
);
1702 AddSitesToFileURIAllowlist("https://"_ns
+ site
);
1706 // Convert it to a URI and add it to our list.
1707 nsCOMPtr
<nsIURI
> uri
;
1708 nsresult rv
= NS_NewURI(getter_AddRefs(uri
), site
);
1709 if (NS_SUCCEEDED(rv
)) {
1710 mFileURIAllowlist
.ref().AppendElement(uri
);
1712 nsCOMPtr
<nsIConsoleService
> console(
1713 do_GetService("@mozilla.org/consoleservice;1"));
1716 u
"Unable to to add site to file:// URI allowlist: "_ns
+
1717 NS_ConvertASCIItoUTF16(site
);
1718 console
->LogStringMessage(msg
.get());
1724 nsresult
nsScriptSecurityManager::InitPrefs() {
1725 nsIPrefBranch
* branch
= Preferences::GetRootBranch();
1726 NS_ENSURE_TRUE(branch
, NS_ERROR_FAILURE
);
1728 mPrefInitialized
= true;
1730 // Set the initial value of the "javascript.enabled" prefs
1731 ScriptSecurityPrefChanged();
1733 // set observer callbacks in case the value of the prefs change
1734 Preferences::RegisterPrefixCallbacks(
1735 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1741 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv
) {
1742 *aRv
= !!mDomainPolicy
;
1747 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy
** aRv
) {
1748 if (!XRE_IsParentProcess()) {
1749 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1752 return ActivateDomainPolicyInternal(aRv
);
1756 nsScriptSecurityManager::ActivateDomainPolicyInternal(nsIDomainPolicy
** aRv
) {
1757 // We only allow one domain policy at a time. The holder of the previous
1758 // policy must explicitly deactivate it first.
1759 if (mDomainPolicy
) {
1760 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1763 mDomainPolicy
= new DomainPolicy();
1764 nsCOMPtr
<nsIDomainPolicy
> ptr
= mDomainPolicy
;
1769 // Intentionally non-scriptable. Script must have a reference to the
1770 // nsIDomainPolicy to deactivate it.
1771 void nsScriptSecurityManager::DeactivateDomainPolicy() {
1772 mDomainPolicy
= nullptr;
1775 void nsScriptSecurityManager::CloneDomainPolicy(DomainPolicyClone
* aClone
) {
1777 if (mDomainPolicy
) {
1778 mDomainPolicy
->CloneDomainPolicy(aClone
);
1780 aClone
->active() = false;
1785 nsScriptSecurityManager::PolicyAllowsScript(nsIURI
* aURI
, bool* aRv
) {
1788 // Compute our rule. If we don't have any domain policy set up that might
1789 // provide exceptions to this rule, we're done.
1790 *aRv
= mIsJavaScriptEnabled
;
1791 if (!mDomainPolicy
) {
1795 // We have a domain policy. Grab the appropriate set of exceptions to the
1796 // rule (either the blocklist or the allowlist, depending on whether script
1797 // is enabled or disabled by default).
1798 nsCOMPtr
<nsIDomainSet
> exceptions
;
1799 nsCOMPtr
<nsIDomainSet
> superExceptions
;
1801 mDomainPolicy
->GetBlocklist(getter_AddRefs(exceptions
));
1802 mDomainPolicy
->GetSuperBlocklist(getter_AddRefs(superExceptions
));
1804 mDomainPolicy
->GetAllowlist(getter_AddRefs(exceptions
));
1805 mDomainPolicy
->GetSuperAllowlist(getter_AddRefs(superExceptions
));
1809 rv
= exceptions
->Contains(aURI
, &contains
);
1810 NS_ENSURE_SUCCESS(rv
, rv
);
1815 rv
= superExceptions
->ContainsSuperDomain(aURI
, &contains
);
1816 NS_ENSURE_SUCCESS(rv
, rv
);
1824 const nsTArray
<nsCOMPtr
<nsIURI
>>&
1825 nsScriptSecurityManager::EnsureFileURIAllowlist() {
1826 if (mFileURIAllowlist
.isSome()) {
1827 return mFileURIAllowlist
.ref();
1831 // Rebuild the set of principals for which we allow file:// URI loads. This
1832 // implements a small subset of an old pref-based CAPS people that people
1833 // have come to depend on. See bug 995943.
1836 mFileURIAllowlist
.emplace();
1837 nsAutoCString policies
;
1838 mozilla::Preferences::GetCString("capability.policy.policynames", policies
);
1839 for (uint32_t base
= SkipPast
<IsWhitespaceOrComma
>(policies
, 0), bound
= 0;
1840 base
< policies
.Length();
1841 base
= SkipPast
<IsWhitespaceOrComma
>(policies
, bound
)) {
1842 // Grab the current policy name.
1843 bound
= SkipUntil
<IsWhitespaceOrComma
>(policies
, base
);
1844 auto policyName
= Substring(policies
, base
, bound
- base
);
1846 // Figure out if this policy allows loading file:// URIs. If not, we can
1848 nsCString checkLoadURIPrefName
=
1849 "capability.policy."_ns
+ policyName
+ ".checkloaduri.enabled"_ns
;
1851 nsresult rv
= Preferences::GetString(checkLoadURIPrefName
.get(), value
);
1852 if (NS_FAILED(rv
) || !value
.LowerCaseEqualsLiteral("allaccess")) {
1856 // Grab the list of domains associated with this policy.
1857 nsCString domainPrefName
=
1858 "capability.policy."_ns
+ policyName
+ ".sites"_ns
;
1859 nsAutoCString siteList
;
1860 Preferences::GetCString(domainPrefName
.get(), siteList
);
1861 AddSitesToFileURIAllowlist(siteList
);
1864 return mFileURIAllowlist
.ref();