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 "ExpandedPrincipal.h"
25 #include "SystemPrincipal.h"
26 #include "DomainPolicy.h"
29 #include "nsCRTGlue.h"
30 #include "nsContentSecurityUtils.h"
31 #include "nsDocShell.h"
33 #include "nsGlobalWindowInner.h"
35 #include "nsTextFormatter.h"
36 #include "nsIStringBundle.h"
37 #include "nsNetUtil.h"
38 #include "nsIEffectiveTLDService.h"
39 #include "nsDirectoryServiceDefs.h"
40 #include "nsIScriptGlobalObject.h"
41 #include "nsPIDOMWindow.h"
42 #include "nsIDocShell.h"
43 #include "nsIConsoleService.h"
44 #include "nsIOService.h"
45 #include "nsIContent.h"
46 #include "nsDOMJSUtils.h"
47 #include "nsAboutProtocolUtils.h"
48 #include "nsIClassInfo.h"
49 #include "nsIURIFixup.h"
50 #include "nsIChromeRegistry.h"
51 #include "nsIResProtocolHandler.h"
52 #include "nsIContentSecurityPolicy.h"
53 #include "mozilla/Components.h"
54 #include "mozilla/Preferences.h"
55 #include "mozilla/dom/BindingUtils.h"
56 #include "mozilla/NullPrincipal.h"
58 #include "mozilla/dom/ContentChild.h"
59 #include "mozilla/dom/ContentParent.h"
60 #include "mozilla/dom/Exceptions.h"
61 #include "mozilla/dom/nsCSPContext.h"
62 #include "mozilla/dom/ScriptSettings.h"
63 #include "mozilla/ClearOnShutdown.h"
64 #include "mozilla/ResultExtensions.h"
65 #include "mozilla/StaticPtr.h"
66 #include "mozilla/dom/WorkerCommon.h"
67 #include "mozilla/dom/WorkerPrivate.h"
68 #include "nsContentUtils.h"
69 #include "nsJSUtils.h"
70 #include "nsILoadInfo.h"
72 // This should be probably defined on some other place... but I couldn't find it
73 #define WEBAPPS_PERM_NAME "webapps-manage"
75 using namespace mozilla
;
76 using namespace mozilla::dom
;
78 nsIIOService
* nsScriptSecurityManager::sIOService
= nullptr;
79 bool nsScriptSecurityManager::sStrictFileOriginPolicy
= true;
85 NS_INLINE_DECL_REFCOUNTING(BundleHelper
)
87 static nsIStringBundle
* GetOrCreate() {
88 MOZ_ASSERT(!sShutdown
);
90 // Already shutting down. Nothing should require the use of the string
91 // bundle when shutting down.
97 sSelf
= new BundleHelper();
100 return sSelf
->GetOrCreateInternal();
103 static void Shutdown() {
109 ~BundleHelper() = default;
111 nsIStringBundle
* GetOrCreateInternal() {
113 nsCOMPtr
<nsIStringBundleService
> bundleService
=
114 mozilla::services::GetStringBundleService();
115 if (NS_WARN_IF(!bundleService
)) {
119 nsresult rv
= bundleService
->CreateBundle(
120 "chrome://global/locale/security/caps.properties",
121 getter_AddRefs(mBundle
));
122 if (NS_WARN_IF(NS_FAILED(rv
))) {
130 nsCOMPtr
<nsIStringBundle
> mBundle
;
132 static StaticRefPtr
<BundleHelper
> sSelf
;
133 static bool sShutdown
;
136 StaticRefPtr
<BundleHelper
> BundleHelper::sSelf
;
137 bool BundleHelper::sShutdown
= false;
141 ///////////////////////////
142 // Convenience Functions //
143 ///////////////////////////
145 class nsAutoInPrincipalDomainOriginSetter
{
147 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin
; }
148 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin
; }
149 static uint32_t sInPrincipalDomainOrigin
;
151 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
;
153 static nsresult
GetOriginFromURI(nsIURI
* aURI
, nsACString
& aOrigin
) {
155 return NS_ERROR_NULL_POINTER
;
157 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
> 1) {
158 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
159 // might be happening on a different principal from the first call. But
160 // after that, cut off the recursion; it just indicates that something
161 // we're doing in this method causes us to reenter a security check here.
162 return NS_ERROR_NOT_AVAILABLE
;
165 nsAutoInPrincipalDomainOriginSetter autoSetter
;
167 nsCOMPtr
<nsIURI
> uri
= NS_GetInnermostURI(aURI
);
168 NS_ENSURE_TRUE(uri
, NS_ERROR_UNEXPECTED
);
170 nsAutoCString hostPort
;
172 nsresult rv
= uri
->GetHostPort(hostPort
);
173 if (NS_SUCCEEDED(rv
)) {
174 nsAutoCString scheme
;
175 rv
= uri
->GetScheme(scheme
);
176 NS_ENSURE_SUCCESS(rv
, rv
);
177 aOrigin
= scheme
+ "://"_ns
+ hostPort
;
179 // Some URIs (e.g., nsSimpleURI) don't support host. Just
180 // get the full spec.
181 rv
= uri
->GetSpec(aOrigin
);
182 NS_ENSURE_SUCCESS(rv
, rv
);
188 static nsresult
GetPrincipalDomainOrigin(nsIPrincipal
* aPrincipal
,
189 nsACString
& aOrigin
) {
191 nsCOMPtr
<nsIURI
> uri
;
192 aPrincipal
->GetDomain(getter_AddRefs(uri
));
193 nsresult rv
= GetOriginFromURI(uri
, aOrigin
);
194 if (NS_SUCCEEDED(rv
)) {
197 // If there is no Domain fallback to the Principals Origin
198 return aPrincipal
->GetOriginNoSuffix(aOrigin
);
201 inline void SetPendingExceptionASCII(JSContext
* cx
, const char* aMsg
) {
202 JS_ReportErrorASCII(cx
, "%s", aMsg
);
205 inline void SetPendingException(JSContext
* cx
, const char16_t
* aMsg
) {
206 NS_ConvertUTF16toUTF8
msg(aMsg
);
207 JS_ReportErrorUTF8(cx
, "%s", msg
.get());
211 bool nsScriptSecurityManager::SecurityCompareURIs(nsIURI
* aSourceURI
,
212 nsIURI
* aTargetURI
) {
213 return NS_SecurityCompareURIs(aSourceURI
, aTargetURI
,
214 sStrictFileOriginPolicy
);
217 // SecurityHashURI is consistent with SecurityCompareURIs because
218 // NS_SecurityHashURI is consistent with NS_SecurityCompareURIs. See
220 uint32_t nsScriptSecurityManager::SecurityHashURI(nsIURI
* aURI
) {
221 return NS_SecurityHashURI(aURI
);
225 * GetChannelResultPrincipal will return the principal that the resource
226 * returned by this channel will use. For example, if the resource is in
227 * a sandbox, it will return the nullprincipal. If the resource is forced
228 * to inherit principal, it will return the principal of its parent. If
229 * the load doesn't require sandboxing or inheriting, it will return the same
230 * principal as GetChannelURIPrincipal. Namely the principal of the URI
231 * that is being loaded.
234 nsScriptSecurityManager::GetChannelResultPrincipal(nsIChannel
* aChannel
,
235 nsIPrincipal
** aPrincipal
) {
236 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
237 /*aIgnoreSandboxing*/ false);
240 nsresult
nsScriptSecurityManager::GetChannelResultPrincipalIfNotSandboxed(
241 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
242 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
243 /*aIgnoreSandboxing*/ true);
247 nsScriptSecurityManager::GetChannelResultStoragePrincipal(
248 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
249 nsCOMPtr
<nsIPrincipal
> principal
;
250 nsresult rv
= GetChannelResultPrincipal(aChannel
, getter_AddRefs(principal
),
251 /*aIgnoreSandboxing*/ false);
252 if (NS_WARN_IF(NS_FAILED(rv
))) {
256 return StoragePrincipalHelper::Create(
257 aChannel
, principal
, /* aForceIsolation */ false, aPrincipal
);
261 nsScriptSecurityManager::GetChannelResultPrincipals(
262 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
,
263 nsIPrincipal
** aPartitionedPrincipal
) {
264 nsresult rv
= GetChannelResultPrincipal(aChannel
, aPrincipal
,
265 /*aIgnoreSandboxing*/ false);
266 if (NS_WARN_IF(NS_FAILED(rv
))) {
270 if (!(*aPrincipal
)->GetIsContentPrincipal()) {
271 // If for some reason we don't have a content principal here, just reuse our
272 // principal for the storage principal too, since attempting to create a
273 // storage principal would fail anyway.
274 nsCOMPtr
<nsIPrincipal
> copy
= *aPrincipal
;
275 copy
.forget(aPartitionedPrincipal
);
279 return StoragePrincipalHelper::Create(
280 aChannel
, *aPrincipal
, /* aForceIsolation */ true, aPartitionedPrincipal
);
283 nsresult
nsScriptSecurityManager::GetChannelResultPrincipal(
284 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
, bool aIgnoreSandboxing
) {
285 MOZ_ASSERT(aChannel
, "Must have channel!");
287 // Check whether we have an nsILoadInfo that says what we should do.
288 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
289 if (loadInfo
->GetForceInheritPrincipalOverruleOwner()) {
290 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
291 loadInfo
->FindPrincipalToInherit(aChannel
);
292 principalToInherit
.forget(aPrincipal
);
296 nsCOMPtr
<nsISupports
> owner
;
297 aChannel
->GetOwner(getter_AddRefs(owner
));
299 CallQueryInterface(owner
, aPrincipal
);
305 if (!aIgnoreSandboxing
&& loadInfo
->GetLoadingSandboxed()) {
306 nsCOMPtr
<nsIPrincipal
> sandboxedLoadingPrincipal
=
307 loadInfo
->GetSandboxedLoadingPrincipal();
308 MOZ_ASSERT(sandboxedLoadingPrincipal
);
309 sandboxedLoadingPrincipal
.forget(aPrincipal
);
313 bool forceInherit
= loadInfo
->GetForceInheritPrincipal();
314 if (aIgnoreSandboxing
&& !forceInherit
) {
315 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
317 if (loadInfo
->GetLoadingSandboxed() &&
318 loadInfo
->GetForceInheritPrincipalDropped()) {
323 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
324 loadInfo
->FindPrincipalToInherit(aChannel
);
325 principalToInherit
.forget(aPrincipal
);
329 auto securityMode
= loadInfo
->GetSecurityMode();
330 // The data: inheritance flags should only apply to the initial load,
331 // not to loads that it might have redirected to.
332 if (loadInfo
->RedirectChain().IsEmpty() &&
334 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
||
336 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
||
337 securityMode
== nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
)) {
338 nsCOMPtr
<nsIURI
> uri
;
339 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
340 NS_ENSURE_SUCCESS(rv
, rv
);
342 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
343 loadInfo
->FindPrincipalToInherit(aChannel
);
344 bool inheritForAboutBlank
= loadInfo
->GetAboutBlankInherits();
346 if (nsContentUtils::ChannelShouldInheritPrincipal(
347 principalToInherit
, uri
, inheritForAboutBlank
, false)) {
348 principalToInherit
.forget(aPrincipal
);
352 return GetChannelURIPrincipal(aChannel
, aPrincipal
);
355 /* The principal of the URI that this channel is loading. This is never
356 * affected by things like sandboxed loads, or loads where we forcefully
357 * inherit the principal. Think of this as the principal of the server
358 * which this channel is loading from. Most callers should use
359 * GetChannelResultPrincipal instead of GetChannelURIPrincipal. Only
360 * call GetChannelURIPrincipal if you are sure that you want the
361 * principal that matches the uri, even in cases when the load is
362 * sandboxed or when the load could be a blob or data uri (i.e even when
363 * you encounter loads that may or may not be sandboxed and loads
364 * that may or may not inherit)."
367 nsScriptSecurityManager::GetChannelURIPrincipal(nsIChannel
* aChannel
,
368 nsIPrincipal
** aPrincipal
) {
369 MOZ_ASSERT(aChannel
, "Must have channel!");
371 // Get the principal from the URI. Make sure this does the same thing
372 // as Document::Reset and PrototypeDocumentContentSink::Init.
373 nsCOMPtr
<nsIURI
> uri
;
374 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
375 NS_ENSURE_SUCCESS(rv
, rv
);
377 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
379 // Inherit the origin attributes from loadInfo.
380 // If this is a top-level document load, the origin attributes of the
381 // loadInfo will be set from nsDocShell::DoURILoad.
382 // For subresource loading, the origin attributes of the loadInfo is from
383 // its loadingPrincipal.
384 OriginAttributes attrs
= loadInfo
->GetOriginAttributes();
386 nsCOMPtr
<nsIPrincipal
> prin
=
387 BasePrincipal::CreateContentPrincipal(uri
, attrs
);
388 prin
.forget(aPrincipal
);
389 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
392 /////////////////////////////
393 // nsScriptSecurityManager //
394 /////////////////////////////
396 ////////////////////////////////////
397 // Methods implementing ISupports //
398 ////////////////////////////////////
399 NS_IMPL_ISUPPORTS(nsScriptSecurityManager
, nsIScriptSecurityManager
)
401 ///////////////////////////////////////////////////
402 // Methods implementing nsIScriptSecurityManager //
403 ///////////////////////////////////////////////////
405 ///////////////// Security Checks /////////////////
407 bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
408 JSContext
* cx
, JS::HandleString aCode
) {
409 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
411 // Get the window, if any, corresponding to the current global
412 nsCOMPtr
<nsIContentSecurityPolicy
> csp
;
413 if (nsGlobalWindowInner
* win
= xpc::CurrentWindowOrNull(cx
)) {
417 nsCOMPtr
<nsIPrincipal
> subjectPrincipal
= nsContentUtils::SubjectPrincipal();
419 // Get the CSP for addon sandboxes. If the principal is expanded and has a
420 // csp, we're probably in luck.
421 auto* basePrin
= BasePrincipal::Cast(subjectPrincipal
);
422 // ContentScriptAddonPolicy means it is also an expanded principal, thus
423 // this is in a sandbox used as a content script.
424 if (basePrin
->ContentScriptAddonPolicy()) {
425 basePrin
->As
<ExpandedPrincipal
>()->GetCsp(getter_AddRefs(csp
));
427 // don't do anything unless there's a CSP
433 nsCOMPtr
<nsICSPEventListener
> cspEventListener
;
434 if (!NS_IsMainThread()) {
435 WorkerPrivate
* workerPrivate
=
436 mozilla::dom::GetWorkerPrivateFromContext(cx
);
438 cspEventListener
= workerPrivate
->CSPEventListener();
443 bool reportViolation
= false;
444 nsresult rv
= csp
->GetAllowsEval(&reportViolation
, &evalOK
);
446 // A little convoluted. We want the scriptSample for a) reporting a violation
447 // or b) passing it to AssertEvalNotUsingSystemPrincipal or c) we're in the
448 // parent process. So do the work to get it if either of those cases is true.
449 nsAutoJSString scriptSample
;
450 if (reportViolation
|| subjectPrincipal
->IsSystemPrincipal() ||
451 XRE_IsE10sParentProcess()) {
452 if (NS_WARN_IF(!scriptSample
.init(cx
, aCode
))) {
453 JS_ClearPendingException(cx
);
458 #if !defined(ANDROID)
459 if (!nsContentSecurityUtils::IsEvalAllowed(
460 cx
, subjectPrincipal
->IsSystemPrincipal(), scriptSample
)) {
466 NS_WARNING("CSP: failed to get allowsEval");
467 return true; // fail open to not break sites.
470 if (reportViolation
) {
471 JS::AutoFilename scriptFilename
;
472 nsAutoString fileName
;
473 unsigned lineNum
= 0;
474 unsigned columnNum
= 0;
475 if (JS::DescribeScriptedCaller(cx
, &scriptFilename
, &lineNum
, &columnNum
)) {
476 if (const char* file
= scriptFilename
.get()) {
477 CopyUTF8toUTF16(nsDependentCString(file
), fileName
);
480 MOZ_ASSERT(!JS_IsExceptionPending(cx
));
482 csp
->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL
,
483 nullptr, // triggering element
484 cspEventListener
, fileName
, scriptSample
, lineNum
,
485 columnNum
, u
""_ns
, u
""_ns
);
492 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals
* first
,
493 JSPrincipals
* second
) {
494 return nsJSPrincipals::get(first
)->Subsumes(nsJSPrincipals::get(second
));
498 nsScriptSecurityManager::CheckSameOriginURI(nsIURI
* aSourceURI
,
501 bool aFromPrivateWindow
) {
502 // Please note that aFromPrivateWindow is only 100% accurate if
503 // reportError is true.
504 if (!SecurityCompareURIs(aSourceURI
, aTargetURI
)) {
506 ReportError("CheckSameOriginError", aSourceURI
, aTargetURI
,
509 return NS_ERROR_DOM_BAD_URI
;
515 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext
* cx
, nsIURI
* aURI
) {
516 // Get principal of currently executing script.
517 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
518 nsIPrincipal
* principal
= nsContentUtils::SubjectPrincipal();
519 nsresult rv
= CheckLoadURIWithPrincipal(
520 // Passing 0 for the window ID here is OK, because we will report a
521 // script-visible exception anyway.
522 principal
, aURI
, nsIScriptSecurityManager::STANDARD
, 0);
523 if (NS_SUCCEEDED(rv
)) {
530 if (NS_FAILED(aURI
->GetAsciiSpec(spec
))) return NS_ERROR_FAILURE
;
531 nsAutoCString
msg("Access to '");
533 msg
.AppendLiteral("' from script denied");
534 SetPendingExceptionASCII(cx
, msg
.get());
535 return NS_ERROR_DOM_BAD_URI
;
539 * Helper method to handle cases where a flag passed to
540 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
541 * nsIProtocolHandler flags set.
542 * @return if success, access is allowed. Otherwise, deny access
544 static nsresult
DenyAccessIfURIHasFlags(nsIURI
* aURI
, uint32_t aURIFlags
) {
545 MOZ_ASSERT(aURI
, "Must have URI!");
548 nsresult rv
= NS_URIChainHasFlags(aURI
, aURIFlags
, &uriHasFlags
);
549 NS_ENSURE_SUCCESS(rv
, rv
);
552 return NS_ERROR_DOM_BAD_URI
;
558 static bool EqualOrSubdomain(nsIURI
* aProbeArg
, nsIURI
* aBase
) {
560 nsCOMPtr
<nsIURI
> probe
= aProbeArg
;
562 nsCOMPtr
<nsIEffectiveTLDService
> tldService
=
563 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID
);
564 NS_ENSURE_TRUE(tldService
, false);
566 if (nsScriptSecurityManager::SecurityCompareURIs(probe
, aBase
)) {
570 nsAutoCString host
, newHost
;
571 rv
= probe
->GetHost(host
);
572 NS_ENSURE_SUCCESS(rv
, false);
574 rv
= tldService
->GetNextSubDomain(host
, newHost
);
575 if (rv
== NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS
) {
578 NS_ENSURE_SUCCESS(rv
, false);
579 rv
= NS_MutateURI(probe
).SetHost(newHost
).Finalize(probe
);
580 NS_ENSURE_SUCCESS(rv
, false);
585 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal
* aPrincipal
,
588 uint64_t aInnerWindowID
) {
589 MOZ_ASSERT(aPrincipal
, "CheckLoadURIWithPrincipal must have a principal");
591 // If someone passes a flag that we don't understand, we should
592 // fail, because they may need a security check that we don't
596 ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
|
597 nsIScriptSecurityManager::ALLOW_CHROME
|
598 nsIScriptSecurityManager::DISALLOW_SCRIPT
|
599 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
|
600 nsIScriptSecurityManager::DONT_REPORT_ERRORS
),
601 NS_ERROR_UNEXPECTED
);
602 NS_ENSURE_ARG_POINTER(aPrincipal
);
603 NS_ENSURE_ARG_POINTER(aTargetURI
);
605 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
606 // would do such inheriting. That would be URIs that do not have their own
607 // security context. We do this even for the system principal.
608 if (aFlags
& nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
) {
609 nsresult rv
= DenyAccessIfURIHasFlags(
610 aTargetURI
, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT
);
611 NS_ENSURE_SUCCESS(rv
, rv
);
614 if (aPrincipal
== mSystemPrincipal
) {
619 nsCOMPtr
<nsIURI
> sourceURI
;
620 auto* basePrin
= BasePrincipal::Cast(aPrincipal
);
621 basePrin
->GetURI(getter_AddRefs(sourceURI
));
623 if (basePrin
->Is
<ExpandedPrincipal
>()) {
624 auto expanded
= basePrin
->As
<ExpandedPrincipal
>();
625 for (auto& prin
: expanded
->AllowList()) {
627 CheckLoadURIWithPrincipal(prin
, aTargetURI
, aFlags
, aInnerWindowID
);
628 if (NS_SUCCEEDED(rv
)) {
629 // Allow access if it succeeded with one of the allowlisted principals
633 // None of our allowlisted principals worked.
634 return NS_ERROR_DOM_BAD_URI
;
637 "Non-system principals or expanded principal passed to "
638 "CheckLoadURIWithPrincipal "
640 return NS_ERROR_UNEXPECTED
;
643 // Automatic loads are not allowed from certain protocols.
645 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
) {
646 nsresult rv
= DenyAccessIfURIHasFlags(
648 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT
);
649 NS_ENSURE_SUCCESS(rv
, rv
);
652 // If either URI is a nested URI, get the base URI
653 nsCOMPtr
<nsIURI
> sourceBaseURI
= NS_GetInnermostURI(sourceURI
);
654 nsCOMPtr
<nsIURI
> targetBaseURI
= NS_GetInnermostURI(aTargetURI
);
656 //-- get the target scheme
657 nsAutoCString targetScheme
;
658 nsresult rv
= targetBaseURI
->GetScheme(targetScheme
);
659 if (NS_FAILED(rv
)) return rv
;
661 //-- Some callers do not allow loading javascript:
662 if ((aFlags
& nsIScriptSecurityManager::DISALLOW_SCRIPT
) &&
663 targetScheme
.EqualsLiteral("javascript")) {
664 return NS_ERROR_DOM_BAD_URI
;
667 // Check for uris that are only loadable by principals that subsume them
668 bool targetURIIsLoadableBySubsumers
= false;
669 rv
= NS_URIChainHasFlags(targetBaseURI
,
670 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
671 &targetURIIsLoadableBySubsumers
);
672 NS_ENSURE_SUCCESS(rv
, rv
);
674 if (targetURIIsLoadableBySubsumers
) {
675 // check nothing else in the URI chain has flags that prevent
677 rv
= CheckLoadURIFlags(
678 sourceURI
, aTargetURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
679 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
681 NS_ENSURE_SUCCESS(rv
, rv
);
682 // Check the principal is allowed to load the target.
683 if (aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
) {
684 return aPrincipal
->CheckMayLoad(targetBaseURI
, false);
686 return aPrincipal
->CheckMayLoadWithReporting(targetBaseURI
, false,
690 //-- get the source scheme
691 nsAutoCString sourceScheme
;
692 rv
= sourceBaseURI
->GetScheme(sourceScheme
);
693 if (NS_FAILED(rv
)) return rv
;
695 if (sourceScheme
.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME
)) {
696 // A null principal can target its own URI.
697 if (sourceURI
== aTargetURI
) {
700 } else if (sourceScheme
.EqualsIgnoreCase("file") &&
701 targetScheme
.EqualsIgnoreCase("moz-icon")) {
702 // exception for file: linking to moz-icon://.ext?size=...
703 // Note that because targetScheme is the base (innermost) URI scheme,
704 // this does NOT allow file -> moz-icon:file:///... links.
705 // This is intentional.
709 // Check for webextension
710 bool targetURIIsLoadableByExtensions
= false;
711 rv
= NS_URIChainHasFlags(aTargetURI
,
712 nsIProtocolHandler::URI_LOADABLE_BY_EXTENSIONS
,
713 &targetURIIsLoadableByExtensions
);
714 NS_ENSURE_SUCCESS(rv
, rv
);
716 if (targetURIIsLoadableByExtensions
&&
717 BasePrincipal::Cast(aPrincipal
)->AddonPolicy()) {
721 // If we get here, check all the schemes can link to each other, from the top
723 nsCOMPtr
<nsIURI
> currentURI
= sourceURI
;
724 nsCOMPtr
<nsIURI
> currentOtherURI
= aTargetURI
;
726 bool denySameSchemeLinks
= false;
727 rv
= NS_URIChainHasFlags(aTargetURI
,
728 nsIProtocolHandler::URI_SCHEME_NOT_SELF_LINKABLE
,
729 &denySameSchemeLinks
);
730 if (NS_FAILED(rv
)) return rv
;
732 while (currentURI
&& currentOtherURI
) {
733 nsAutoCString scheme
, otherScheme
;
734 currentURI
->GetScheme(scheme
);
735 currentOtherURI
->GetScheme(otherScheme
);
738 scheme
.Equals(otherScheme
, nsCaseInsensitiveCStringComparator
);
739 bool isSamePage
= false;
740 // about: URIs are special snowflakes.
741 if (scheme
.EqualsLiteral("about") && schemesMatch
) {
742 nsAutoCString moduleName
, otherModuleName
;
743 // about: pages can always link to themselves:
745 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI
, moduleName
)) &&
747 NS_GetAboutModuleName(currentOtherURI
, otherModuleName
)) &&
748 moduleName
.Equals(otherModuleName
);
750 // We will have allowed the load earlier if the source page has
751 // system principal. So we know the source has a content
752 // principal, and it's trying to link to something else.
753 // Linkable about: pages are always reachable, even if we hit
754 // the CheckLoadURIFlags call below.
755 // We punch only 1 other hole: iff the source is unlinkable,
756 // we let them link to other pages explicitly marked SAFE
757 // for content. This avoids world-linkable about: pages linking
758 // to non-world-linkable about: pages.
759 nsCOMPtr
<nsIAboutModule
> module
, otherModule
;
760 bool knowBothModules
=
762 NS_GetAboutModule(currentURI
, getter_AddRefs(module
))) &&
763 NS_SUCCEEDED(NS_GetAboutModule(currentOtherURI
,
764 getter_AddRefs(otherModule
)));
765 uint32_t aboutModuleFlags
= 0;
766 uint32_t otherAboutModuleFlags
= 0;
769 NS_SUCCEEDED(module
->GetURIFlags(currentURI
, &aboutModuleFlags
)) &&
770 NS_SUCCEEDED(otherModule
->GetURIFlags(currentOtherURI
,
771 &otherAboutModuleFlags
));
772 if (knowBothModules
) {
773 isSamePage
= !(aboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) &&
774 (otherAboutModuleFlags
&
775 nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT
);
777 otherAboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) {
778 // XXXgijs: this is a hack. The target will be nested
779 // (with innerURI of moz-safe-about:whatever), and
780 // the source isn't, so we won't pass if we finish
781 // the loop. We *should* pass, though, so return here.
782 // This hack can go away when bug 1228118 is fixed.
788 bool equalExceptRef
= false;
789 rv
= currentURI
->EqualsExceptRef(currentOtherURI
, &equalExceptRef
);
790 isSamePage
= NS_SUCCEEDED(rv
) && equalExceptRef
;
793 // If schemes are not equal, or they're equal but the target URI
794 // is different from the source URI and doesn't always allow linking
795 // from the same scheme, check if the URI flags of the current target
796 // URI allow the current source URI to link to it.
797 // The policy is specified by the protocol flags on both URIs.
798 if (!schemesMatch
|| (denySameSchemeLinks
&& !isSamePage
)) {
799 return CheckLoadURIFlags(
800 currentURI
, currentOtherURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
801 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
804 // Otherwise... check if we can nest another level:
805 nsCOMPtr
<nsINestedURI
> nestedURI
= do_QueryInterface(currentURI
);
806 nsCOMPtr
<nsINestedURI
> nestedOtherURI
= do_QueryInterface(currentOtherURI
);
808 // If schemes match and neither URI is nested further, we're OK.
809 if (!nestedURI
&& !nestedOtherURI
) {
812 // If one is nested and the other isn't, something is wrong.
813 if (!nestedURI
!= !nestedOtherURI
) {
814 return NS_ERROR_DOM_BAD_URI
;
816 // Otherwise, both should be nested and we'll go through the loop again.
817 nestedURI
->GetInnerURI(getter_AddRefs(currentURI
));
818 nestedOtherURI
->GetInnerURI(getter_AddRefs(currentOtherURI
));
821 // We should never get here. We should always return from inside the loop.
822 return NS_ERROR_DOM_BAD_URI
;
826 * Helper method to check whether the target URI and its innermost ("base") URI
827 * has protocol flags that should stop it from being loaded by the source URI
828 * (and/or the source URI's innermost ("base") URI), taking into account any
829 * nsIScriptSecurityManager flags originally passed to
830 * CheckLoadURIWithPrincipal and friends.
832 * @return if success, access is allowed. Otherwise, deny access
834 nsresult
nsScriptSecurityManager::CheckLoadURIFlags(
835 nsIURI
* aSourceURI
, nsIURI
* aTargetURI
, nsIURI
* aSourceBaseURI
,
836 nsIURI
* aTargetBaseURI
, uint32_t aFlags
, bool aFromPrivateWindow
,
837 uint64_t aInnerWindowID
) {
838 // Note that the order of policy checks here is very important!
839 // We start from most restrictive and work our way down.
840 bool reportErrors
= !(aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
);
841 const char* errorTag
= "CheckLoadURIError";
843 nsAutoCString targetScheme
;
844 nsresult rv
= aTargetBaseURI
->GetScheme(targetScheme
);
845 if (NS_FAILED(rv
)) return rv
;
847 // Check for system target URI
848 rv
= DenyAccessIfURIHasFlags(aTargetURI
,
849 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD
);
851 // Deny access, since the origin principal is not system
853 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
859 // Used by ExtensionProtocolHandler to prevent loading extension resources
860 // in private contexts if the extension does not have permission.
861 if (aFromPrivateWindow
) {
862 rv
= DenyAccessIfURIHasFlags(
863 aTargetURI
, nsIProtocolHandler::URI_DISALLOW_IN_PRIVATE_CONTEXT
);
866 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
873 // Check for chrome target URI
874 bool targetURIIsUIResource
= false;
875 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_UI_RESOURCE
,
876 &targetURIIsUIResource
);
877 NS_ENSURE_SUCCESS(rv
, rv
);
878 if (targetURIIsUIResource
) {
879 // ALLOW_CHROME is a flag that we pass on all loads _except_ docshell
880 // loads (since docshell loads run the loaded content with its origin
881 // principal). We are effectively allowing resource:// and chrome://
882 // URIs to load as long as they are content accessible and as long
883 // they're not loading it as a document.
884 if (aFlags
& nsIScriptSecurityManager::ALLOW_CHROME
) {
885 bool sourceIsUIResource
= false;
886 rv
= NS_URIChainHasFlags(aSourceBaseURI
,
887 nsIProtocolHandler::URI_IS_UI_RESOURCE
,
888 &sourceIsUIResource
);
889 NS_ENSURE_SUCCESS(rv
, rv
);
890 if (sourceIsUIResource
) {
891 // TODO Bug 1654488: Remove pref in CheckLoadURIFlags which
892 // allows all UI resources to load
894 security_caps_allow_uri_is_ui_resource_in_checkloaduriflags()) {
897 // Special case for moz-icon URIs loaded by a local resources like
898 // e.g. chrome: or resource:
899 if (targetScheme
.EqualsLiteral("moz-icon")) {
904 if (targetScheme
.EqualsLiteral("resource")) {
905 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
909 nsCOMPtr
<nsIProtocolHandler
> ph
;
910 rv
= sIOService
->GetProtocolHandler("resource", getter_AddRefs(ph
));
911 NS_ENSURE_SUCCESS(rv
, rv
);
913 return NS_ERROR_DOM_BAD_URI
;
916 nsCOMPtr
<nsIResProtocolHandler
> rph
= do_QueryInterface(ph
);
918 return NS_ERROR_DOM_BAD_URI
;
921 bool accessAllowed
= false;
922 rph
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
926 } else if (targetScheme
.EqualsLiteral("chrome")) {
927 // Allow the load only if the chrome package is allowlisted.
928 nsCOMPtr
<nsIXULChromeRegistry
> reg(
929 do_GetService(NS_CHROMEREGISTRY_CONTRACTID
));
931 bool accessAllowed
= false;
932 reg
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
937 } else if (targetScheme
.EqualsLiteral("moz-page-thumb")) {
938 if (XRE_IsParentProcess()) {
942 auto& remoteType
= dom::ContentChild::GetSingleton()->GetRemoteType();
943 if (remoteType
== PRIVILEGEDABOUT_REMOTE_TYPE
) {
950 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
953 return NS_ERROR_DOM_BAD_URI
;
956 // Check for target URI pointing to a file
957 bool targetURIIsLocalFile
= false;
958 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_LOCAL_FILE
,
959 &targetURIIsLocalFile
);
960 NS_ENSURE_SUCCESS(rv
, rv
);
961 if (targetURIIsLocalFile
) {
962 // Allow domains that were allowlisted in the prefs. In 99.9% of cases,
963 // this array is empty.
965 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI
, &isAllowlisted
));
971 if (aSourceBaseURI
->SchemeIs("chrome")) {
977 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
980 return NS_ERROR_DOM_BAD_URI
;
985 // Everyone is allowed to load this. The case URI_LOADABLE_BY_SUBSUMERS
986 // is handled by the caller which is just delegating to us as a helper.
987 bool hasSubsumersFlag
= false;
988 NS_URIChainHasFlags(aTargetBaseURI
,
989 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
991 bool hasLoadableByAnyone
= false;
992 NS_URIChainHasFlags(aTargetBaseURI
,
993 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE
,
994 &hasLoadableByAnyone
);
995 MOZ_ASSERT(hasLoadableByAnyone
|| hasSubsumersFlag
,
996 "why do we get here and do not have any of the two flags set?");
1003 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1004 const nsACString
& aSourceSpec
,
1005 const nsACString
& aTargetSpec
,
1006 bool aFromPrivateWindow
,
1007 uint64_t aInnerWindowID
) {
1008 if (aSourceSpec
.IsEmpty() || aTargetSpec
.IsEmpty()) {
1012 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1013 if (NS_WARN_IF(!bundle
)) {
1017 // Localize the error message
1018 nsAutoString message
;
1019 AutoTArray
<nsString
, 2> formatStrings
;
1020 CopyASCIItoUTF16(aSourceSpec
, *formatStrings
.AppendElement());
1021 CopyASCIItoUTF16(aTargetSpec
, *formatStrings
.AppendElement());
1023 bundle
->FormatStringFromName(aMessageTag
, formatStrings
, message
);
1024 NS_ENSURE_SUCCESS(rv
, rv
);
1026 nsCOMPtr
<nsIConsoleService
> console(
1027 do_GetService(NS_CONSOLESERVICE_CONTRACTID
));
1028 NS_ENSURE_TRUE(console
, NS_ERROR_FAILURE
);
1029 nsCOMPtr
<nsIScriptError
> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID
));
1030 NS_ENSURE_TRUE(error
, NS_ERROR_FAILURE
);
1032 // using category of "SOP" so we can link to MDN
1033 if (aInnerWindowID
!= 0) {
1034 rv
= error
->InitWithWindowID(
1035 message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
, "SOP"_ns
,
1036 aInnerWindowID
, true /* From chrome context */);
1038 rv
= error
->Init(message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
,
1039 "SOP", aFromPrivateWindow
, true /* From chrome context */);
1041 NS_ENSURE_SUCCESS(rv
, rv
);
1042 console
->LogMessage(error
);
1046 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1047 nsIURI
* aSource
, nsIURI
* aTarget
,
1048 bool aFromPrivateWindow
,
1049 uint64_t aInnerWindowID
) {
1050 NS_ENSURE_TRUE(aSource
&& aTarget
, NS_ERROR_NULL_POINTER
);
1052 // Get the source URL spec
1053 nsAutoCString sourceSpec
;
1054 nsresult rv
= aSource
->GetAsciiSpec(sourceSpec
);
1055 NS_ENSURE_SUCCESS(rv
, rv
);
1057 // Get the target URL spec
1058 nsAutoCString targetSpec
;
1059 rv
= aTarget
->GetAsciiSpec(targetSpec
);
1060 NS_ENSURE_SUCCESS(rv
, rv
);
1062 return ReportError(aMessageTag
, sourceSpec
, targetSpec
, aFromPrivateWindow
,
1067 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1068 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
,
1071 nsCOMPtr
<nsIURI
> target
;
1072 rv
= NS_NewURI(getter_AddRefs(target
), aTargetURIStr
);
1073 NS_ENSURE_SUCCESS(rv
, rv
);
1075 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1076 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1077 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1081 NS_ENSURE_SUCCESS(rv
, rv
);
1083 // Now start testing fixup -- since aTargetURIStr is a string, not
1084 // an nsIURI, we may well end up fixing it up before loading.
1085 // Note: This needs to stay in sync with the nsIURIFixup api.
1086 nsCOMPtr
<nsIURIFixup
> fixup
= components::URIFixup::Service();
1091 // URIFixup's keyword and alternate flags can only fixup to http/https, so we
1092 // can skip testing them. This simplifies our life because this code can be
1093 // invoked from the content process where the search service would not be
1095 uint32_t flags
[] = {nsIURIFixup::FIXUP_FLAG_NONE
,
1096 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS
};
1097 for (uint32_t i
= 0; i
< ArrayLength(flags
); ++i
) {
1098 uint32_t fixupFlags
= flags
[i
];
1099 if (aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0) {
1100 fixupFlags
|= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT
;
1102 nsCOMPtr
<nsIURIFixupInfo
> fixupInfo
;
1103 rv
= fixup
->GetFixupURIInfo(aTargetURIStr
, fixupFlags
,
1104 getter_AddRefs(fixupInfo
));
1105 NS_ENSURE_SUCCESS(rv
, rv
);
1106 rv
= fixupInfo
->GetPreferredURI(getter_AddRefs(target
));
1107 NS_ENSURE_SUCCESS(rv
, rv
);
1109 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1110 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1111 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1115 NS_ENSURE_SUCCESS(rv
, rv
);
1122 nsScriptSecurityManager::CheckLoadURIWithPrincipalFromJS(
1123 nsIPrincipal
* aPrincipal
, nsIURI
* aTargetURI
, uint32_t aFlags
,
1124 uint64_t aInnerWindowID
, JSContext
* aCx
) {
1125 MOZ_ASSERT(aPrincipal
,
1126 "CheckLoadURIWithPrincipalFromJS must have a principal");
1127 NS_ENSURE_ARG_POINTER(aPrincipal
);
1128 NS_ENSURE_ARG_POINTER(aTargetURI
);
1131 CheckLoadURIWithPrincipal(aPrincipal
, aTargetURI
, aFlags
, aInnerWindowID
);
1132 if (NS_FAILED(rv
)) {
1133 nsAutoCString uriStr
;
1134 Unused
<< aTargetURI
->GetSpec(uriStr
);
1136 nsAutoCString
message("Load of ");
1137 message
.Append(uriStr
);
1139 nsAutoCString principalStr
;
1140 Unused
<< aPrincipal
->GetSpec(principalStr
);
1141 if (!principalStr
.IsEmpty()) {
1142 message
.AppendPrintf(" from %s", principalStr
.get());
1145 message
.Append(" denied");
1147 dom::Throw(aCx
, rv
, message
);
1154 nsScriptSecurityManager::CheckLoadURIStrWithPrincipalFromJS(
1155 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
, uint32_t aFlags
,
1157 nsCOMPtr
<nsIURI
> targetURI
;
1158 MOZ_TRY(NS_NewURI(getter_AddRefs(targetURI
), aTargetURIStr
));
1160 return CheckLoadURIWithPrincipalFromJS(aPrincipal
, targetURI
, aFlags
, 0, aCx
);
1164 nsScriptSecurityManager::InFileURIAllowlist(nsIURI
* aUri
, bool* aResult
) {
1166 MOZ_ASSERT(aResult
);
1169 for (nsIURI
* uri
: EnsureFileURIAllowlist()) {
1170 if (EqualOrSubdomain(aUri
, uri
)) {
1179 ///////////////// Principals ///////////////////////
1182 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal
** result
) {
1183 NS_ADDREF(*result
= mSystemPrincipal
);
1189 nsScriptSecurityManager::CreateContentPrincipal(
1190 nsIURI
* aURI
, JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1191 nsIPrincipal
** aPrincipal
) {
1192 OriginAttributes attrs
;
1193 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1194 return NS_ERROR_INVALID_ARG
;
1196 nsCOMPtr
<nsIPrincipal
> prin
=
1197 BasePrincipal::CreateContentPrincipal(aURI
, attrs
);
1198 prin
.forget(aPrincipal
);
1199 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1203 nsScriptSecurityManager::CreateContentPrincipalFromOrigin(
1204 const nsACString
& aOrigin
, nsIPrincipal
** aPrincipal
) {
1205 if (StringBeginsWith(aOrigin
, "["_ns
)) {
1206 return NS_ERROR_INVALID_ARG
;
1209 if (StringBeginsWith(aOrigin
,
1210 nsLiteralCString(NS_NULLPRINCIPAL_SCHEME
":"))) {
1211 return NS_ERROR_INVALID_ARG
;
1214 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(aOrigin
);
1215 prin
.forget(aPrincipal
);
1216 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1220 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal
* aPrincipal
,
1221 nsACString
& aJSON
) {
1224 return NS_ERROR_FAILURE
;
1227 BasePrincipal::Cast(aPrincipal
)->ToJSON(aJSON
);
1229 if (aJSON
.IsEmpty()) {
1230 return NS_ERROR_FAILURE
;
1237 nsScriptSecurityManager::JSONToPrincipal(const nsACString
& aJSON
,
1238 nsIPrincipal
** aPrincipal
) {
1239 if (aJSON
.IsEmpty()) {
1240 return NS_ERROR_FAILURE
;
1243 nsCOMPtr
<nsIPrincipal
> principal
= BasePrincipal::FromJSON(aJSON
);
1246 return NS_ERROR_FAILURE
;
1249 principal
.forget(aPrincipal
);
1254 nsScriptSecurityManager::CreateNullPrincipal(
1255 JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1256 nsIPrincipal
** aPrincipal
) {
1257 OriginAttributes attrs
;
1258 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1259 return NS_ERROR_INVALID_ARG
;
1261 nsCOMPtr
<nsIPrincipal
> prin
= NullPrincipal::Create(attrs
);
1262 prin
.forget(aPrincipal
);
1267 nsScriptSecurityManager::GetLoadContextContentPrincipal(
1268 nsIURI
* aURI
, nsILoadContext
* aLoadContext
, nsIPrincipal
** aPrincipal
) {
1269 NS_ENSURE_STATE(aLoadContext
);
1270 OriginAttributes docShellAttrs
;
1271 aLoadContext
->GetOriginAttributes(docShellAttrs
);
1273 nsCOMPtr
<nsIPrincipal
> prin
=
1274 BasePrincipal::CreateContentPrincipal(aURI
, docShellAttrs
);
1275 prin
.forget(aPrincipal
);
1276 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1280 nsScriptSecurityManager::GetDocShellContentPrincipal(
1281 nsIURI
* aURI
, nsIDocShell
* aDocShell
, nsIPrincipal
** aPrincipal
) {
1282 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(
1283 aURI
, nsDocShell::Cast(aDocShell
)->GetOriginAttributes());
1284 prin
.forget(aPrincipal
);
1285 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1289 nsScriptSecurityManager::PrincipalWithOA(
1290 nsIPrincipal
* aPrincipal
, JS::Handle
<JS::Value
> aOriginAttributes
,
1291 JSContext
* aCx
, nsIPrincipal
** aReturnPrincipal
) {
1295 if (aPrincipal
->GetIsContentPrincipal()) {
1296 OriginAttributes attrs
;
1297 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1298 return NS_ERROR_INVALID_ARG
;
1300 RefPtr
<ContentPrincipal
> copy
= new ContentPrincipal();
1301 auto* contentPrincipal
= static_cast<ContentPrincipal
*>(aPrincipal
);
1302 nsresult rv
= copy
->Init(contentPrincipal
, attrs
);
1303 NS_ENSURE_SUCCESS(rv
, rv
);
1304 copy
.forget(aReturnPrincipal
);
1306 // We do this for null principals, system principals (both fine)
1307 // ... and expanded principals, where we should probably do something
1308 // cleverer, but I also don't think we care too much.
1309 nsCOMPtr
<nsIPrincipal
> prin
= aPrincipal
;
1310 prin
.forget(aReturnPrincipal
);
1313 return *aReturnPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1317 nsScriptSecurityManager::CanCreateWrapper(JSContext
* cx
, const nsIID
& aIID
,
1319 nsIClassInfo
* aClassInfo
) {
1320 // XXX Special case for Exception ?
1322 // We give remote-XUL allowlisted domains a free pass here. See bug 932906.
1323 JS::Rooted
<JS::Realm
*> contextRealm(cx
, JS::GetCurrentRealmOrNull(cx
));
1324 MOZ_RELEASE_ASSERT(contextRealm
);
1325 if (!xpc::AllowContentXBLScope(contextRealm
)) {
1329 if (nsContentUtils::IsCallerChrome()) {
1333 //-- Access denied, report an error
1334 nsAutoCString originUTF8
;
1335 nsIPrincipal
* subjectPrincipal
= nsContentUtils::SubjectPrincipal();
1336 GetPrincipalDomainOrigin(subjectPrincipal
, originUTF8
);
1337 NS_ConvertUTF8toUTF16
originUTF16(originUTF8
);
1338 nsAutoCString classInfoNameUTF8
;
1340 aClassInfo
->GetClassDescription(classInfoNameUTF8
);
1342 if (classInfoNameUTF8
.IsEmpty()) {
1343 classInfoNameUTF8
.AssignLiteral("UnnamedClass");
1346 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1347 if (NS_WARN_IF(!bundle
)) {
1351 NS_ConvertUTF8toUTF16
classInfoUTF16(classInfoNameUTF8
);
1353 nsAutoString errorMsg
;
1354 if (originUTF16
.IsEmpty()) {
1355 AutoTArray
<nsString
, 1> formatStrings
= {classInfoUTF16
};
1356 rv
= bundle
->FormatStringFromName("CreateWrapperDenied", formatStrings
,
1359 AutoTArray
<nsString
, 2> formatStrings
= {classInfoUTF16
, originUTF16
};
1360 rv
= bundle
->FormatStringFromName("CreateWrapperDeniedForOrigin",
1361 formatStrings
, errorMsg
);
1363 NS_ENSURE_SUCCESS(rv
, rv
);
1365 SetPendingException(cx
, errorMsg
.get());
1366 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1370 nsScriptSecurityManager::CanCreateInstance(JSContext
* cx
, const nsCID
& aCID
) {
1371 if (nsContentUtils::IsCallerChrome()) {
1375 //-- Access denied, report an error
1376 nsAutoCString
errorMsg("Permission denied to create instance of class. CID=");
1377 char cidStr
[NSID_LENGTH
];
1378 aCID
.ToProvidedString(cidStr
);
1379 errorMsg
.Append(cidStr
);
1380 SetPendingExceptionASCII(cx
, errorMsg
.get());
1381 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1385 nsScriptSecurityManager::CanGetService(JSContext
* cx
, const nsCID
& aCID
) {
1386 if (nsContentUtils::IsCallerChrome()) {
1390 //-- Access denied, report an error
1391 nsAutoCString
errorMsg("Permission denied to get service. CID=");
1392 char cidStr
[NSID_LENGTH
];
1393 aCID
.ToProvidedString(cidStr
);
1394 errorMsg
.Append(cidStr
);
1395 SetPendingExceptionASCII(cx
, errorMsg
.get());
1396 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1399 const char sJSEnabledPrefName
[] = "javascript.enabled";
1400 const char sFileOriginPolicyPrefName
[] =
1401 "security.fileuri.strict_origin_policy";
1403 static const char* kObservedPrefs
[] = {sJSEnabledPrefName
,
1404 sFileOriginPolicyPrefName
,
1405 "capability.policy.", nullptr};
1407 /////////////////////////////////////////////
1408 // Constructor, Destructor, Initialization //
1409 /////////////////////////////////////////////
1410 nsScriptSecurityManager::nsScriptSecurityManager(void)
1411 : mPrefInitialized(false), mIsJavaScriptEnabled(false) {
1413 sizeof(intptr_t) == sizeof(void*),
1414 "intptr_t and void* have different lengths on this platform. "
1415 "This may cause a security failure with the SecurityLevel union.");
1418 nsresult
nsScriptSecurityManager::Init() {
1419 nsresult rv
= CallGetService(NS_IOSERVICE_CONTRACTID
, &sIOService
);
1420 NS_ENSURE_SUCCESS(rv
, rv
);
1424 // Create our system principal singleton
1425 RefPtr
<SystemPrincipal
> system
= SystemPrincipal::Create();
1427 mSystemPrincipal
= system
;
1432 void nsScriptSecurityManager::InitJSCallbacks(JSContext
* aCx
) {
1433 //-- Register security check callback in the JS engine
1434 // Currently this is used to control access to function.caller
1436 static const JSSecurityCallbacks securityCallbacks
= {
1437 ContentSecurityPolicyPermitsJSAction
,
1438 JSPrincipalsSubsume
,
1441 MOZ_ASSERT(!JS_GetSecurityCallbacks(aCx
));
1442 JS_SetSecurityCallbacks(aCx
, &securityCallbacks
);
1443 JS_InitDestroyPrincipalsCallback(aCx
, nsJSPrincipals::Destroy
);
1445 JS_SetTrustedPrincipals(aCx
, BasePrincipal::Cast(mSystemPrincipal
));
1449 void nsScriptSecurityManager::ClearJSCallbacks(JSContext
* aCx
) {
1450 JS_SetSecurityCallbacks(aCx
, nullptr);
1451 JS_SetTrustedPrincipals(aCx
, nullptr);
1454 static StaticRefPtr
<nsScriptSecurityManager
> gScriptSecMan
;
1456 nsScriptSecurityManager::~nsScriptSecurityManager(void) {
1457 Preferences::UnregisterPrefixCallbacks(
1458 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1459 if (mDomainPolicy
) {
1460 mDomainPolicy
->Deactivate();
1462 // ContentChild might hold a reference to the domain policy,
1463 // and it might release it only after the security manager is
1464 // gone. But we can still assert this for the main process.
1465 MOZ_ASSERT_IF(XRE_IsParentProcess(), !mDomainPolicy
);
1468 void nsScriptSecurityManager::Shutdown() {
1469 NS_IF_RELEASE(sIOService
);
1470 BundleHelper::Shutdown();
1473 nsScriptSecurityManager
* nsScriptSecurityManager::GetScriptSecurityManager() {
1474 return gScriptSecMan
;
1478 void nsScriptSecurityManager::InitStatics() {
1479 RefPtr
<nsScriptSecurityManager
> ssManager
= new nsScriptSecurityManager();
1480 nsresult rv
= ssManager
->Init();
1481 if (NS_FAILED(rv
)) {
1482 MOZ_CRASH("ssManager->Init() failed");
1485 ClearOnShutdown(&gScriptSecMan
);
1486 gScriptSecMan
= ssManager
;
1489 // Currently this nsGenericFactory constructor is used only from FastLoad
1490 // (XPCOM object deserialization) code, when "creating" the system principal
1492 already_AddRefed
<SystemPrincipal
>
1493 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1495 return do_AddRef(gScriptSecMan
->mSystemPrincipal
)
1496 .downcast
<SystemPrincipal
>();
1500 struct IsWhitespace
{
1501 static bool Test(char aChar
) { return NS_IsAsciiWhitespace(aChar
); };
1503 struct IsWhitespaceOrComma
{
1504 static bool Test(char aChar
) {
1505 return aChar
== ',' || NS_IsAsciiWhitespace(aChar
);
1509 template <typename Predicate
>
1510 uint32_t SkipPast(const nsCString
& str
, uint32_t base
) {
1511 while (base
< str
.Length() && Predicate::Test(str
[base
])) {
1517 template <typename Predicate
>
1518 uint32_t SkipUntil(const nsCString
& str
, uint32_t base
) {
1519 while (base
< str
.Length() && !Predicate::Test(str
[base
])) {
1526 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref
,
1528 static_cast<nsScriptSecurityManager
*>(aSelf
)->ScriptSecurityPrefChanged(
1532 inline void nsScriptSecurityManager::ScriptSecurityPrefChanged(
1533 const char* aPref
) {
1534 MOZ_ASSERT(mPrefInitialized
);
1535 mIsJavaScriptEnabled
=
1536 Preferences::GetBool(sJSEnabledPrefName
, mIsJavaScriptEnabled
);
1537 sStrictFileOriginPolicy
=
1538 Preferences::GetBool(sFileOriginPolicyPrefName
, false);
1539 mFileURIAllowlist
.reset();
1542 void nsScriptSecurityManager::AddSitesToFileURIAllowlist(
1543 const nsCString
& aSiteList
) {
1544 for (uint32_t base
= SkipPast
<IsWhitespace
>(aSiteList
, 0), bound
= 0;
1545 base
< aSiteList
.Length();
1546 base
= SkipPast
<IsWhitespace
>(aSiteList
, bound
)) {
1547 // Grab the current site.
1548 bound
= SkipUntil
<IsWhitespace
>(aSiteList
, base
);
1549 nsAutoCString
site(Substring(aSiteList
, base
, bound
- base
));
1551 // Check if the URI is schemeless. If so, add both http and https.
1552 nsAutoCString unused
;
1553 if (NS_FAILED(sIOService
->ExtractScheme(site
, unused
))) {
1554 AddSitesToFileURIAllowlist("http://"_ns
+ site
);
1555 AddSitesToFileURIAllowlist("https://"_ns
+ site
);
1559 // Convert it to a URI and add it to our list.
1560 nsCOMPtr
<nsIURI
> uri
;
1561 nsresult rv
= NS_NewURI(getter_AddRefs(uri
), site
);
1562 if (NS_SUCCEEDED(rv
)) {
1563 mFileURIAllowlist
.ref().AppendElement(uri
);
1565 nsCOMPtr
<nsIConsoleService
> console(
1566 do_GetService("@mozilla.org/consoleservice;1"));
1569 u
"Unable to to add site to file:// URI allowlist: "_ns
+
1570 NS_ConvertASCIItoUTF16(site
);
1571 console
->LogStringMessage(msg
.get());
1577 nsresult
nsScriptSecurityManager::InitPrefs() {
1578 nsIPrefBranch
* branch
= Preferences::GetRootBranch();
1579 NS_ENSURE_TRUE(branch
, NS_ERROR_FAILURE
);
1581 mPrefInitialized
= true;
1583 // Set the initial value of the "javascript.enabled" prefs
1584 ScriptSecurityPrefChanged();
1586 // set observer callbacks in case the value of the prefs change
1587 Preferences::RegisterPrefixCallbacks(
1588 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1594 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv
) {
1595 *aRv
= !!mDomainPolicy
;
1600 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy
** aRv
) {
1601 if (!XRE_IsParentProcess()) {
1602 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1605 return ActivateDomainPolicyInternal(aRv
);
1609 nsScriptSecurityManager::ActivateDomainPolicyInternal(nsIDomainPolicy
** aRv
) {
1610 // We only allow one domain policy at a time. The holder of the previous
1611 // policy must explicitly deactivate it first.
1612 if (mDomainPolicy
) {
1613 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1616 mDomainPolicy
= new DomainPolicy();
1617 nsCOMPtr
<nsIDomainPolicy
> ptr
= mDomainPolicy
;
1622 // Intentionally non-scriptable. Script must have a reference to the
1623 // nsIDomainPolicy to deactivate it.
1624 void nsScriptSecurityManager::DeactivateDomainPolicy() {
1625 mDomainPolicy
= nullptr;
1628 void nsScriptSecurityManager::CloneDomainPolicy(DomainPolicyClone
* aClone
) {
1630 if (mDomainPolicy
) {
1631 mDomainPolicy
->CloneDomainPolicy(aClone
);
1633 aClone
->active() = false;
1638 nsScriptSecurityManager::PolicyAllowsScript(nsIURI
* aURI
, bool* aRv
) {
1641 // Compute our rule. If we don't have any domain policy set up that might
1642 // provide exceptions to this rule, we're done.
1643 *aRv
= mIsJavaScriptEnabled
;
1644 if (!mDomainPolicy
) {
1648 // We have a domain policy. Grab the appropriate set of exceptions to the
1649 // rule (either the blocklist or the allowlist, depending on whether script
1650 // is enabled or disabled by default).
1651 nsCOMPtr
<nsIDomainSet
> exceptions
;
1652 nsCOMPtr
<nsIDomainSet
> superExceptions
;
1654 mDomainPolicy
->GetBlocklist(getter_AddRefs(exceptions
));
1655 mDomainPolicy
->GetSuperBlocklist(getter_AddRefs(superExceptions
));
1657 mDomainPolicy
->GetAllowlist(getter_AddRefs(exceptions
));
1658 mDomainPolicy
->GetSuperAllowlist(getter_AddRefs(superExceptions
));
1662 rv
= exceptions
->Contains(aURI
, &contains
);
1663 NS_ENSURE_SUCCESS(rv
, rv
);
1668 rv
= superExceptions
->ContainsSuperDomain(aURI
, &contains
);
1669 NS_ENSURE_SUCCESS(rv
, rv
);
1677 const nsTArray
<nsCOMPtr
<nsIURI
>>&
1678 nsScriptSecurityManager::EnsureFileURIAllowlist() {
1679 if (mFileURIAllowlist
.isSome()) {
1680 return mFileURIAllowlist
.ref();
1684 // Rebuild the set of principals for which we allow file:// URI loads. This
1685 // implements a small subset of an old pref-based CAPS people that people
1686 // have come to depend on. See bug 995943.
1689 mFileURIAllowlist
.emplace();
1690 nsAutoCString policies
;
1691 mozilla::Preferences::GetCString("capability.policy.policynames", policies
);
1692 for (uint32_t base
= SkipPast
<IsWhitespaceOrComma
>(policies
, 0), bound
= 0;
1693 base
< policies
.Length();
1694 base
= SkipPast
<IsWhitespaceOrComma
>(policies
, bound
)) {
1695 // Grab the current policy name.
1696 bound
= SkipUntil
<IsWhitespaceOrComma
>(policies
, base
);
1697 auto policyName
= Substring(policies
, base
, bound
- base
);
1699 // Figure out if this policy allows loading file:// URIs. If not, we can
1701 nsCString checkLoadURIPrefName
=
1702 "capability.policy."_ns
+ policyName
+ ".checkloaduri.enabled"_ns
;
1704 nsresult rv
= Preferences::GetString(checkLoadURIPrefName
.get(), value
);
1705 if (NS_FAILED(rv
) || !value
.LowerCaseEqualsLiteral("allaccess")) {
1709 // Grab the list of domains associated with this policy.
1710 nsCString domainPrefName
=
1711 "capability.policy."_ns
+ policyName
+ ".sites"_ns
;
1712 nsAutoCString siteList
;
1713 Preferences::GetCString(domainPrefName
.get(), siteList
);
1714 AddSitesToFileURIAllowlist(siteList
);
1717 return mFileURIAllowlist
.ref();