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"
75 // This should be probably defined on some other place... but I couldn't find it
76 #define WEBAPPS_PERM_NAME "webapps-manage"
78 using namespace mozilla
;
79 using namespace mozilla::dom
;
81 nsIIOService
* nsScriptSecurityManager::sIOService
= nullptr;
82 bool nsScriptSecurityManager::sStrictFileOriginPolicy
= true;
88 NS_INLINE_DECL_REFCOUNTING(BundleHelper
)
90 static nsIStringBundle
* GetOrCreate() {
91 MOZ_ASSERT(!sShutdown
);
93 // Already shutting down. Nothing should require the use of the string
94 // bundle when shutting down.
100 sSelf
= new BundleHelper();
103 return sSelf
->GetOrCreateInternal();
106 static void Shutdown() {
112 ~BundleHelper() = default;
114 nsIStringBundle
* GetOrCreateInternal() {
116 nsCOMPtr
<nsIStringBundleService
> bundleService
=
117 mozilla::components::StringBundle::Service();
118 if (NS_WARN_IF(!bundleService
)) {
122 nsresult rv
= bundleService
->CreateBundle(
123 "chrome://global/locale/security/caps.properties",
124 getter_AddRefs(mBundle
));
125 if (NS_WARN_IF(NS_FAILED(rv
))) {
133 nsCOMPtr
<nsIStringBundle
> mBundle
;
135 static StaticRefPtr
<BundleHelper
> sSelf
;
136 static bool sShutdown
;
139 StaticRefPtr
<BundleHelper
> BundleHelper::sSelf
;
140 bool BundleHelper::sShutdown
= false;
144 ///////////////////////////
145 // Convenience Functions //
146 ///////////////////////////
148 class nsAutoInPrincipalDomainOriginSetter
{
150 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin
; }
151 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin
; }
152 static uint32_t sInPrincipalDomainOrigin
;
154 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
;
156 static nsresult
GetOriginFromURI(nsIURI
* aURI
, nsACString
& aOrigin
) {
158 return NS_ERROR_NULL_POINTER
;
160 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin
> 1) {
161 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
162 // might be happening on a different principal from the first call. But
163 // after that, cut off the recursion; it just indicates that something
164 // we're doing in this method causes us to reenter a security check here.
165 return NS_ERROR_NOT_AVAILABLE
;
168 nsAutoInPrincipalDomainOriginSetter autoSetter
;
170 nsCOMPtr
<nsIURI
> uri
= NS_GetInnermostURI(aURI
);
171 NS_ENSURE_TRUE(uri
, NS_ERROR_UNEXPECTED
);
173 nsAutoCString hostPort
;
175 nsresult rv
= uri
->GetHostPort(hostPort
);
176 if (NS_SUCCEEDED(rv
)) {
177 nsAutoCString scheme
;
178 rv
= uri
->GetScheme(scheme
);
179 NS_ENSURE_SUCCESS(rv
, rv
);
180 aOrigin
= scheme
+ "://"_ns
+ hostPort
;
182 // Some URIs (e.g., nsSimpleURI) don't support host. Just
183 // get the full spec.
184 rv
= uri
->GetSpec(aOrigin
);
185 NS_ENSURE_SUCCESS(rv
, rv
);
191 static nsresult
GetPrincipalDomainOrigin(nsIPrincipal
* aPrincipal
,
192 nsACString
& aOrigin
) {
194 nsCOMPtr
<nsIURI
> uri
;
195 aPrincipal
->GetDomain(getter_AddRefs(uri
));
196 nsresult rv
= GetOriginFromURI(uri
, aOrigin
);
197 if (NS_SUCCEEDED(rv
)) {
200 // If there is no Domain fallback to the Principals Origin
201 return aPrincipal
->GetOriginNoSuffix(aOrigin
);
204 inline void SetPendingExceptionASCII(JSContext
* cx
, const char* aMsg
) {
205 JS_ReportErrorASCII(cx
, "%s", aMsg
);
208 inline void SetPendingException(JSContext
* cx
, const char16_t
* aMsg
) {
209 NS_ConvertUTF16toUTF8
msg(aMsg
);
210 JS_ReportErrorUTF8(cx
, "%s", msg
.get());
214 bool nsScriptSecurityManager::SecurityCompareURIs(nsIURI
* aSourceURI
,
215 nsIURI
* aTargetURI
) {
216 return NS_SecurityCompareURIs(aSourceURI
, aTargetURI
,
217 sStrictFileOriginPolicy
);
220 // SecurityHashURI is consistent with SecurityCompareURIs because
221 // NS_SecurityHashURI is consistent with NS_SecurityCompareURIs. See
223 uint32_t nsScriptSecurityManager::SecurityHashURI(nsIURI
* aURI
) {
224 return NS_SecurityHashURI(aURI
);
228 * GetChannelResultPrincipal will return the principal that the resource
229 * returned by this channel will use. For example, if the resource is in
230 * a sandbox, it will return the nullprincipal. If the resource is forced
231 * to inherit principal, it will return the principal of its parent. If
232 * the load doesn't require sandboxing or inheriting, it will return the same
233 * principal as GetChannelURIPrincipal. Namely the principal of the URI
234 * that is being loaded.
237 nsScriptSecurityManager::GetChannelResultPrincipal(nsIChannel
* aChannel
,
238 nsIPrincipal
** aPrincipal
) {
239 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
240 /*aIgnoreSandboxing*/ false);
243 nsresult
nsScriptSecurityManager::GetChannelResultPrincipalIfNotSandboxed(
244 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
245 return GetChannelResultPrincipal(aChannel
, aPrincipal
,
246 /*aIgnoreSandboxing*/ true);
250 nsScriptSecurityManager::GetChannelResultStoragePrincipal(
251 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
) {
252 nsCOMPtr
<nsIPrincipal
> principal
;
253 nsresult rv
= GetChannelResultPrincipal(aChannel
, getter_AddRefs(principal
),
254 /*aIgnoreSandboxing*/ false);
255 if (NS_WARN_IF(NS_FAILED(rv
) || !principal
)) {
259 if (!(principal
->GetIsContentPrincipal())) {
260 // If for some reason we don't have a content principal here, just reuse our
261 // principal for the storage principal too, since attempting to create a
262 // storage principal would fail anyway.
263 principal
.forget(aPrincipal
);
267 return StoragePrincipalHelper::Create(
268 aChannel
, principal
, /* aForceIsolation */ false, aPrincipal
);
272 nsScriptSecurityManager::GetChannelResultPrincipals(
273 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
,
274 nsIPrincipal
** aPartitionedPrincipal
) {
275 nsresult rv
= GetChannelResultPrincipal(aChannel
, aPrincipal
,
276 /*aIgnoreSandboxing*/ false);
277 if (NS_WARN_IF(NS_FAILED(rv
))) {
281 if (!(*aPrincipal
)->GetIsContentPrincipal()) {
282 // If for some reason we don't have a content principal here, just reuse our
283 // principal for the storage principal too, since attempting to create a
284 // storage principal would fail anyway.
285 nsCOMPtr
<nsIPrincipal
> copy
= *aPrincipal
;
286 copy
.forget(aPartitionedPrincipal
);
290 return StoragePrincipalHelper::Create(
291 aChannel
, *aPrincipal
, /* aForceIsolation */ true, aPartitionedPrincipal
);
294 nsresult
nsScriptSecurityManager::GetChannelResultPrincipal(
295 nsIChannel
* aChannel
, nsIPrincipal
** aPrincipal
, bool aIgnoreSandboxing
) {
296 MOZ_ASSERT(aChannel
, "Must have channel!");
298 // Check whether we have an nsILoadInfo that says what we should do.
299 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
300 if (loadInfo
->GetForceInheritPrincipalOverruleOwner()) {
301 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
302 loadInfo
->FindPrincipalToInherit(aChannel
);
303 principalToInherit
.forget(aPrincipal
);
307 nsCOMPtr
<nsISupports
> owner
;
308 aChannel
->GetOwner(getter_AddRefs(owner
));
310 CallQueryInterface(owner
, aPrincipal
);
316 if (!aIgnoreSandboxing
&& loadInfo
->GetLoadingSandboxed()) {
317 // Determine the unsandboxed result principal to use as this null
318 // principal's precursor. Ignore errors here, as the precursor isn't
320 nsCOMPtr
<nsIPrincipal
> precursor
;
321 GetChannelResultPrincipal(aChannel
, getter_AddRefs(precursor
),
322 /*aIgnoreSandboxing*/ true);
324 // Construct a deterministic null principal URI from the precursor and the
325 // loadinfo's nullPrincipalID.
326 nsCOMPtr
<nsIURI
> nullPrincipalURI
= NullPrincipal::CreateURI(
327 precursor
, &loadInfo
->GetSandboxedNullPrincipalID());
329 // Use the URI to construct the sandboxed result principal.
330 OriginAttributes attrs
;
331 loadInfo
->GetOriginAttributes(&attrs
);
332 nsCOMPtr
<nsIPrincipal
> sandboxedPrincipal
=
333 NullPrincipal::Create(attrs
, nullPrincipalURI
);
334 sandboxedPrincipal
.forget(aPrincipal
);
338 bool forceInherit
= loadInfo
->GetForceInheritPrincipal();
339 if (aIgnoreSandboxing
&& !forceInherit
) {
340 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
342 if (loadInfo
->GetLoadingSandboxed() &&
343 loadInfo
->GetForceInheritPrincipalDropped()) {
348 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
349 loadInfo
->FindPrincipalToInherit(aChannel
);
350 principalToInherit
.forget(aPrincipal
);
354 auto securityMode
= loadInfo
->GetSecurityMode();
355 // The data: inheritance flags should only apply to the initial load,
356 // not to loads that it might have redirected to.
357 if (loadInfo
->RedirectChain().IsEmpty() &&
359 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT
||
361 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
||
362 securityMode
== nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT
)) {
363 nsCOMPtr
<nsIURI
> uri
;
364 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
365 NS_ENSURE_SUCCESS(rv
, rv
);
367 nsCOMPtr
<nsIPrincipal
> principalToInherit
=
368 loadInfo
->FindPrincipalToInherit(aChannel
);
369 bool inheritForAboutBlank
= loadInfo
->GetAboutBlankInherits();
371 if (nsContentUtils::ChannelShouldInheritPrincipal(
372 principalToInherit
, uri
, inheritForAboutBlank
, false)) {
373 principalToInherit
.forget(aPrincipal
);
377 return GetChannelURIPrincipal(aChannel
, aPrincipal
);
380 /* The principal of the URI that this channel is loading. This is never
381 * affected by things like sandboxed loads, or loads where we forcefully
382 * inherit the principal. Think of this as the principal of the server
383 * which this channel is loading from. Most callers should use
384 * GetChannelResultPrincipal instead of GetChannelURIPrincipal. Only
385 * call GetChannelURIPrincipal if you are sure that you want the
386 * principal that matches the uri, even in cases when the load is
387 * sandboxed or when the load could be a blob or data uri (i.e even when
388 * you encounter loads that may or may not be sandboxed and loads
389 * that may or may not inherit)."
392 nsScriptSecurityManager::GetChannelURIPrincipal(nsIChannel
* aChannel
,
393 nsIPrincipal
** aPrincipal
) {
394 MOZ_ASSERT(aChannel
, "Must have channel!");
396 // Get the principal from the URI. Make sure this does the same thing
397 // as Document::Reset and PrototypeDocumentContentSink::Init.
398 nsCOMPtr
<nsIURI
> uri
;
399 nsresult rv
= NS_GetFinalChannelURI(aChannel
, getter_AddRefs(uri
));
400 NS_ENSURE_SUCCESS(rv
, rv
);
402 nsCOMPtr
<nsILoadInfo
> loadInfo
= aChannel
->LoadInfo();
404 // Inherit the origin attributes from loadInfo.
405 // If this is a top-level document load, the origin attributes of the
406 // loadInfo will be set from nsDocShell::DoURILoad.
407 // For subresource loading, the origin attributes of the loadInfo is from
408 // its loadingPrincipal.
409 OriginAttributes attrs
= loadInfo
->GetOriginAttributes();
411 // If the URI is supposed to inherit the security context of whoever loads it,
412 // we shouldn't make a content principal for it, so instead return a null
414 bool inheritsPrincipal
= false;
415 rv
= NS_URIChainHasFlags(uri
,
416 nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT
,
418 if (NS_FAILED(rv
) || inheritsPrincipal
) {
419 // Find a precursor principal to credit for the load. This won't impact
420 // security checks, but makes tracking the source of related loads easier.
421 nsCOMPtr
<nsIPrincipal
> precursorPrincipal
=
422 loadInfo
->FindPrincipalToInherit(aChannel
);
423 nsCOMPtr
<nsIURI
> nullPrincipalURI
=
424 NullPrincipal::CreateURI(precursorPrincipal
);
425 *aPrincipal
= NullPrincipal::Create(attrs
, nullPrincipalURI
).take();
426 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
429 nsCOMPtr
<nsIPrincipal
> prin
=
430 BasePrincipal::CreateContentPrincipal(uri
, attrs
);
431 prin
.forget(aPrincipal
);
432 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
435 /////////////////////////////
436 // nsScriptSecurityManager //
437 /////////////////////////////
439 ////////////////////////////////////
440 // Methods implementing ISupports //
441 ////////////////////////////////////
442 NS_IMPL_ISUPPORTS(nsScriptSecurityManager
, nsIScriptSecurityManager
)
444 ///////////////////////////////////////////////////
445 // Methods implementing nsIScriptSecurityManager //
446 ///////////////////////////////////////////////////
448 ///////////////// Security Checks /////////////////
450 bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
451 JSContext
* cx
, JS::HandleString aCode
) {
452 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
454 // Get the window, if any, corresponding to the current global
455 nsCOMPtr
<nsIContentSecurityPolicy
> csp
;
456 if (nsGlobalWindowInner
* win
= xpc::CurrentWindowOrNull(cx
)) {
460 nsCOMPtr
<nsIPrincipal
> subjectPrincipal
= nsContentUtils::SubjectPrincipal();
462 // Get the CSP for addon sandboxes. If the principal is expanded and has a
463 // csp, we're probably in luck.
464 auto* basePrin
= BasePrincipal::Cast(subjectPrincipal
);
465 // ContentScriptAddonPolicy means it is also an expanded principal, thus
466 // this is in a sandbox used as a content script.
467 if (basePrin
->ContentScriptAddonPolicy()) {
468 basePrin
->As
<ExpandedPrincipal
>()->GetCsp(getter_AddRefs(csp
));
470 // don't do anything unless there's a CSP
476 nsCOMPtr
<nsICSPEventListener
> cspEventListener
;
477 if (!NS_IsMainThread()) {
478 WorkerPrivate
* workerPrivate
=
479 mozilla::dom::GetWorkerPrivateFromContext(cx
);
481 cspEventListener
= workerPrivate
->CSPEventListener();
486 bool reportViolation
= false;
487 nsresult rv
= csp
->GetAllowsEval(&reportViolation
, &evalOK
);
489 // A little convoluted. We want the scriptSample for a) reporting a violation
490 // or b) passing it to AssertEvalNotUsingSystemPrincipal or c) we're in the
491 // parent process. So do the work to get it if either of those cases is true.
492 nsAutoJSString scriptSample
;
493 if (reportViolation
|| subjectPrincipal
->IsSystemPrincipal() ||
494 XRE_IsE10sParentProcess()) {
495 if (NS_WARN_IF(!scriptSample
.init(cx
, aCode
))) {
496 JS_ClearPendingException(cx
);
501 #if !defined(ANDROID)
502 if (!nsContentSecurityUtils::IsEvalAllowed(
503 cx
, subjectPrincipal
->IsSystemPrincipal(), scriptSample
)) {
509 NS_WARNING("CSP: failed to get allowsEval");
510 return true; // fail open to not break sites.
513 if (reportViolation
) {
514 JS::AutoFilename scriptFilename
;
515 nsAutoString fileName
;
516 unsigned lineNum
= 0;
517 unsigned columnNum
= 0;
518 if (JS::DescribeScriptedCaller(cx
, &scriptFilename
, &lineNum
, &columnNum
)) {
519 if (const char* file
= scriptFilename
.get()) {
520 CopyUTF8toUTF16(nsDependentCString(file
), fileName
);
523 MOZ_ASSERT(!JS_IsExceptionPending(cx
));
525 csp
->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL
,
526 nullptr, // triggering element
527 cspEventListener
, fileName
, scriptSample
, lineNum
,
528 columnNum
, u
""_ns
, u
""_ns
);
535 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals
* first
,
536 JSPrincipals
* second
) {
537 return nsJSPrincipals::get(first
)->Subsumes(nsJSPrincipals::get(second
));
541 nsScriptSecurityManager::CheckSameOriginURI(nsIURI
* aSourceURI
,
544 bool aFromPrivateWindow
) {
545 // Please note that aFromPrivateWindow is only 100% accurate if
546 // reportError is true.
547 if (!SecurityCompareURIs(aSourceURI
, aTargetURI
)) {
549 ReportError("CheckSameOriginError", aSourceURI
, aTargetURI
,
552 return NS_ERROR_DOM_BAD_URI
;
558 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext
* cx
, nsIURI
* aURI
) {
559 // Get principal of currently executing script.
560 MOZ_ASSERT(cx
== nsContentUtils::GetCurrentJSContext());
561 nsIPrincipal
* principal
= nsContentUtils::SubjectPrincipal();
562 nsresult rv
= CheckLoadURIWithPrincipal(
563 // Passing 0 for the window ID here is OK, because we will report a
564 // script-visible exception anyway.
565 principal
, aURI
, nsIScriptSecurityManager::STANDARD
, 0);
566 if (NS_SUCCEEDED(rv
)) {
573 if (NS_FAILED(aURI
->GetAsciiSpec(spec
))) return NS_ERROR_FAILURE
;
574 nsAutoCString
msg("Access to '");
576 msg
.AppendLiteral("' from script denied");
577 SetPendingExceptionASCII(cx
, msg
.get());
578 return NS_ERROR_DOM_BAD_URI
;
582 * Helper method to handle cases where a flag passed to
583 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
584 * nsIProtocolHandler flags set.
585 * @return if success, access is allowed. Otherwise, deny access
587 static nsresult
DenyAccessIfURIHasFlags(nsIURI
* aURI
, uint32_t aURIFlags
) {
588 MOZ_ASSERT(aURI
, "Must have URI!");
591 nsresult rv
= NS_URIChainHasFlags(aURI
, aURIFlags
, &uriHasFlags
);
592 NS_ENSURE_SUCCESS(rv
, rv
);
595 return NS_ERROR_DOM_BAD_URI
;
601 static bool EqualOrSubdomain(nsIURI
* aProbeArg
, nsIURI
* aBase
) {
603 nsCOMPtr
<nsIURI
> probe
= aProbeArg
;
605 nsCOMPtr
<nsIEffectiveTLDService
> tldService
=
606 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID
);
607 NS_ENSURE_TRUE(tldService
, false);
609 if (nsScriptSecurityManager::SecurityCompareURIs(probe
, aBase
)) {
613 nsAutoCString host
, newHost
;
614 rv
= probe
->GetHost(host
);
615 NS_ENSURE_SUCCESS(rv
, false);
617 rv
= tldService
->GetNextSubDomain(host
, newHost
);
618 if (rv
== NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS
) {
621 NS_ENSURE_SUCCESS(rv
, false);
622 rv
= NS_MutateURI(probe
).SetHost(newHost
).Finalize(probe
);
623 NS_ENSURE_SUCCESS(rv
, false);
628 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal
* aPrincipal
,
631 uint64_t aInnerWindowID
) {
632 MOZ_ASSERT(aPrincipal
, "CheckLoadURIWithPrincipal must have a principal");
634 // If someone passes a flag that we don't understand, we should
635 // fail, because they may need a security check that we don't
639 ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
|
640 nsIScriptSecurityManager::ALLOW_CHROME
|
641 nsIScriptSecurityManager::DISALLOW_SCRIPT
|
642 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
|
643 nsIScriptSecurityManager::DONT_REPORT_ERRORS
),
644 NS_ERROR_UNEXPECTED
);
645 NS_ENSURE_ARG_POINTER(aPrincipal
);
646 NS_ENSURE_ARG_POINTER(aTargetURI
);
648 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
649 // would do such inheriting. That would be URIs that do not have their own
650 // security context. We do this even for the system principal.
651 if (aFlags
& nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL
) {
652 nsresult rv
= DenyAccessIfURIHasFlags(
653 aTargetURI
, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT
);
654 NS_ENSURE_SUCCESS(rv
, rv
);
657 if (aPrincipal
== mSystemPrincipal
) {
662 nsCOMPtr
<nsIURI
> sourceURI
;
663 auto* basePrin
= BasePrincipal::Cast(aPrincipal
);
664 basePrin
->GetURI(getter_AddRefs(sourceURI
));
666 if (basePrin
->Is
<ExpandedPrincipal
>()) {
667 auto expanded
= basePrin
->As
<ExpandedPrincipal
>();
668 const auto& allowList
= expanded
->AllowList();
669 // Only report errors when all principals fail.
670 uint32_t flags
= aFlags
| nsIScriptSecurityManager::DONT_REPORT_ERRORS
;
671 for (size_t i
= 0; i
< allowList
.Length() - 1; i
++) {
672 nsresult rv
= CheckLoadURIWithPrincipal(allowList
[i
], aTargetURI
, flags
,
674 if (NS_SUCCEEDED(rv
)) {
675 // Allow access if it succeeded with one of the allowlisted principals
680 // Report errors (if requested) for the last principal.
681 return CheckLoadURIWithPrincipal(allowList
.LastElement(), aTargetURI
,
682 aFlags
, aInnerWindowID
);
685 "Non-system principals or expanded principal passed to "
686 "CheckLoadURIWithPrincipal "
688 return NS_ERROR_UNEXPECTED
;
691 // Automatic loads are not allowed from certain protocols.
693 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT
) {
694 nsresult rv
= DenyAccessIfURIHasFlags(
696 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT
);
697 NS_ENSURE_SUCCESS(rv
, rv
);
700 // If either URI is a nested URI, get the base URI
701 nsCOMPtr
<nsIURI
> sourceBaseURI
= NS_GetInnermostURI(sourceURI
);
702 nsCOMPtr
<nsIURI
> targetBaseURI
= NS_GetInnermostURI(aTargetURI
);
704 //-- get the target scheme
705 nsAutoCString targetScheme
;
706 nsresult rv
= targetBaseURI
->GetScheme(targetScheme
);
707 if (NS_FAILED(rv
)) return rv
;
709 //-- Some callers do not allow loading javascript:
710 if ((aFlags
& nsIScriptSecurityManager::DISALLOW_SCRIPT
) &&
711 targetScheme
.EqualsLiteral("javascript")) {
712 return NS_ERROR_DOM_BAD_URI
;
715 // Extensions may allow access to a web accessible resource.
716 bool maybeWebAccessible
= false;
717 NS_URIChainHasFlags(targetBaseURI
,
718 nsIProtocolHandler::WEBEXT_URI_WEB_ACCESSIBLE
,
719 &maybeWebAccessible
);
720 NS_ENSURE_SUCCESS(rv
, rv
);
721 if (maybeWebAccessible
) {
722 bool isWebAccessible
= false;
723 rv
= ExtensionPolicyService::GetSingleton().SourceMayLoadExtensionURI(
724 sourceURI
, targetBaseURI
, &isWebAccessible
);
725 if (!(NS_SUCCEEDED(rv
) && isWebAccessible
)) {
726 return NS_ERROR_DOM_BAD_URI
;
730 // Check for uris that are only loadable by principals that subsume them
731 bool targetURIIsLoadableBySubsumers
= false;
732 rv
= NS_URIChainHasFlags(targetBaseURI
,
733 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
734 &targetURIIsLoadableBySubsumers
);
735 NS_ENSURE_SUCCESS(rv
, rv
);
737 if (targetURIIsLoadableBySubsumers
) {
738 // check nothing else in the URI chain has flags that prevent
740 rv
= CheckLoadURIFlags(
741 sourceURI
, aTargetURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
742 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
744 NS_ENSURE_SUCCESS(rv
, rv
);
745 // Check the principal is allowed to load the target.
746 if (aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
) {
747 return aPrincipal
->CheckMayLoad(targetBaseURI
, false);
749 return aPrincipal
->CheckMayLoadWithReporting(targetBaseURI
, false,
753 //-- get the source scheme
754 nsAutoCString sourceScheme
;
755 rv
= sourceBaseURI
->GetScheme(sourceScheme
);
756 if (NS_FAILED(rv
)) return rv
;
758 if (sourceScheme
.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME
)) {
759 // A null principal can target its own URI.
760 if (sourceURI
== aTargetURI
) {
763 } else if (sourceScheme
.EqualsIgnoreCase("file") &&
764 targetScheme
.EqualsIgnoreCase("moz-icon")) {
765 // exception for file: linking to moz-icon://.ext?size=...
766 // Note that because targetScheme is the base (innermost) URI scheme,
767 // this does NOT allow file -> moz-icon:file:///... links.
768 // This is intentional.
772 // Check for webextension
773 bool targetURIIsLoadableByExtensions
= false;
774 rv
= NS_URIChainHasFlags(aTargetURI
,
775 nsIProtocolHandler::URI_LOADABLE_BY_EXTENSIONS
,
776 &targetURIIsLoadableByExtensions
);
777 NS_ENSURE_SUCCESS(rv
, rv
);
779 if (targetURIIsLoadableByExtensions
&&
780 BasePrincipal::Cast(aPrincipal
)->AddonPolicy()) {
784 // If we get here, check all the schemes can link to each other, from the top
786 nsCOMPtr
<nsIURI
> currentURI
= sourceURI
;
787 nsCOMPtr
<nsIURI
> currentOtherURI
= aTargetURI
;
789 bool denySameSchemeLinks
= false;
790 rv
= NS_URIChainHasFlags(aTargetURI
,
791 nsIProtocolHandler::URI_SCHEME_NOT_SELF_LINKABLE
,
792 &denySameSchemeLinks
);
793 if (NS_FAILED(rv
)) return rv
;
795 while (currentURI
&& currentOtherURI
) {
796 nsAutoCString scheme
, otherScheme
;
797 currentURI
->GetScheme(scheme
);
798 currentOtherURI
->GetScheme(otherScheme
);
801 scheme
.Equals(otherScheme
, nsCaseInsensitiveCStringComparator
);
802 bool isSamePage
= false;
803 // about: URIs are special snowflakes.
804 if (scheme
.EqualsLiteral("about") && schemesMatch
) {
805 nsAutoCString moduleName
, otherModuleName
;
806 // about: pages can always link to themselves:
808 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI
, moduleName
)) &&
810 NS_GetAboutModuleName(currentOtherURI
, otherModuleName
)) &&
811 moduleName
.Equals(otherModuleName
);
813 // We will have allowed the load earlier if the source page has
814 // system principal. So we know the source has a content
815 // principal, and it's trying to link to something else.
816 // Linkable about: pages are always reachable, even if we hit
817 // the CheckLoadURIFlags call below.
818 // We punch only 1 other hole: iff the source is unlinkable,
819 // we let them link to other pages explicitly marked SAFE
820 // for content. This avoids world-linkable about: pages linking
821 // to non-world-linkable about: pages.
822 nsCOMPtr
<nsIAboutModule
> module
, otherModule
;
823 bool knowBothModules
=
825 NS_GetAboutModule(currentURI
, getter_AddRefs(module
))) &&
826 NS_SUCCEEDED(NS_GetAboutModule(currentOtherURI
,
827 getter_AddRefs(otherModule
)));
828 uint32_t aboutModuleFlags
= 0;
829 uint32_t otherAboutModuleFlags
= 0;
832 NS_SUCCEEDED(module
->GetURIFlags(currentURI
, &aboutModuleFlags
)) &&
833 NS_SUCCEEDED(otherModule
->GetURIFlags(currentOtherURI
,
834 &otherAboutModuleFlags
));
835 if (knowBothModules
) {
836 isSamePage
= !(aboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) &&
837 (otherAboutModuleFlags
&
838 nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT
);
840 otherAboutModuleFlags
& nsIAboutModule::MAKE_LINKABLE
) {
841 // XXXgijs: this is a hack. The target will be nested
842 // (with innerURI of moz-safe-about:whatever), and
843 // the source isn't, so we won't pass if we finish
844 // the loop. We *should* pass, though, so return here.
845 // This hack can go away when bug 1228118 is fixed.
851 bool equalExceptRef
= false;
852 rv
= currentURI
->EqualsExceptRef(currentOtherURI
, &equalExceptRef
);
853 isSamePage
= NS_SUCCEEDED(rv
) && equalExceptRef
;
856 // If schemes are not equal, or they're equal but the target URI
857 // is different from the source URI and doesn't always allow linking
858 // from the same scheme, check if the URI flags of the current target
859 // URI allow the current source URI to link to it.
860 // The policy is specified by the protocol flags on both URIs.
861 if (!schemesMatch
|| (denySameSchemeLinks
&& !isSamePage
)) {
862 return CheckLoadURIFlags(
863 currentURI
, currentOtherURI
, sourceBaseURI
, targetBaseURI
, aFlags
,
864 aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0,
867 // Otherwise... check if we can nest another level:
868 nsCOMPtr
<nsINestedURI
> nestedURI
= do_QueryInterface(currentURI
);
869 nsCOMPtr
<nsINestedURI
> nestedOtherURI
= do_QueryInterface(currentOtherURI
);
871 // If schemes match and neither URI is nested further, we're OK.
872 if (!nestedURI
&& !nestedOtherURI
) {
875 // If one is nested and the other isn't, something is wrong.
876 if (!nestedURI
!= !nestedOtherURI
) {
877 return NS_ERROR_DOM_BAD_URI
;
879 // Otherwise, both should be nested and we'll go through the loop again.
880 nestedURI
->GetInnerURI(getter_AddRefs(currentURI
));
881 nestedOtherURI
->GetInnerURI(getter_AddRefs(currentOtherURI
));
884 // We should never get here. We should always return from inside the loop.
885 return NS_ERROR_DOM_BAD_URI
;
889 * Helper method to check whether the target URI and its innermost ("base") URI
890 * has protocol flags that should stop it from being loaded by the source URI
891 * (and/or the source URI's innermost ("base") URI), taking into account any
892 * nsIScriptSecurityManager flags originally passed to
893 * CheckLoadURIWithPrincipal and friends.
895 * @return if success, access is allowed. Otherwise, deny access
897 nsresult
nsScriptSecurityManager::CheckLoadURIFlags(
898 nsIURI
* aSourceURI
, nsIURI
* aTargetURI
, nsIURI
* aSourceBaseURI
,
899 nsIURI
* aTargetBaseURI
, uint32_t aFlags
, bool aFromPrivateWindow
,
900 uint64_t aInnerWindowID
) {
901 // Note that the order of policy checks here is very important!
902 // We start from most restrictive and work our way down.
903 bool reportErrors
= !(aFlags
& nsIScriptSecurityManager::DONT_REPORT_ERRORS
);
904 const char* errorTag
= "CheckLoadURIError";
906 nsAutoCString targetScheme
;
907 nsresult rv
= aTargetBaseURI
->GetScheme(targetScheme
);
908 if (NS_FAILED(rv
)) return rv
;
910 // Check for system target URI
911 rv
= DenyAccessIfURIHasFlags(aTargetURI
,
912 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD
);
914 // Deny access, since the origin principal is not system
916 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
922 // Used by ExtensionProtocolHandler to prevent loading extension resources
923 // in private contexts if the extension does not have permission.
924 if (aFromPrivateWindow
) {
925 rv
= DenyAccessIfURIHasFlags(
926 aTargetURI
, nsIProtocolHandler::URI_DISALLOW_IN_PRIVATE_CONTEXT
);
929 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
936 // Check for chrome target URI
937 bool targetURIIsUIResource
= false;
938 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_UI_RESOURCE
,
939 &targetURIIsUIResource
);
940 NS_ENSURE_SUCCESS(rv
, rv
);
941 if (targetURIIsUIResource
) {
942 // ALLOW_CHROME is a flag that we pass on all loads _except_ docshell
943 // loads (since docshell loads run the loaded content with its origin
944 // principal). We are effectively allowing resource:// and chrome://
945 // URIs to load as long as they are content accessible and as long
946 // they're not loading it as a document.
947 if (aFlags
& nsIScriptSecurityManager::ALLOW_CHROME
) {
948 bool sourceIsUIResource
= false;
949 rv
= NS_URIChainHasFlags(aSourceBaseURI
,
950 nsIProtocolHandler::URI_IS_UI_RESOURCE
,
951 &sourceIsUIResource
);
952 NS_ENSURE_SUCCESS(rv
, rv
);
953 if (sourceIsUIResource
) {
954 // Special case for moz-icon URIs loaded by a local resources like
955 // e.g. chrome: or resource:
956 if (targetScheme
.EqualsLiteral("moz-icon")) {
961 if (targetScheme
.EqualsLiteral("resource")) {
962 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
966 nsCOMPtr
<nsIProtocolHandler
> ph
;
967 rv
= sIOService
->GetProtocolHandler("resource", getter_AddRefs(ph
));
968 NS_ENSURE_SUCCESS(rv
, rv
);
970 return NS_ERROR_DOM_BAD_URI
;
973 nsCOMPtr
<nsIResProtocolHandler
> rph
= do_QueryInterface(ph
);
975 return NS_ERROR_DOM_BAD_URI
;
978 bool accessAllowed
= false;
979 rph
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
983 } else if (targetScheme
.EqualsLiteral("chrome")) {
984 // Allow the load only if the chrome package is allowlisted.
985 nsCOMPtr
<nsIXULChromeRegistry
> reg(
986 do_GetService(NS_CHROMEREGISTRY_CONTRACTID
));
988 bool accessAllowed
= false;
989 reg
->AllowContentToAccess(aTargetBaseURI
, &accessAllowed
);
994 } else if (targetScheme
.EqualsLiteral("moz-page-thumb")) {
995 if (XRE_IsParentProcess()) {
999 auto& remoteType
= dom::ContentChild::GetSingleton()->GetRemoteType();
1000 if (remoteType
== PRIVILEGEDABOUT_REMOTE_TYPE
) {
1007 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1010 return NS_ERROR_DOM_BAD_URI
;
1013 // Check for target URI pointing to a file
1014 bool targetURIIsLocalFile
= false;
1015 rv
= NS_URIChainHasFlags(aTargetURI
, nsIProtocolHandler::URI_IS_LOCAL_FILE
,
1016 &targetURIIsLocalFile
);
1017 NS_ENSURE_SUCCESS(rv
, rv
);
1018 if (targetURIIsLocalFile
) {
1019 // Allow domains that were allowlisted in the prefs. In 99.9% of cases,
1020 // this array is empty.
1022 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI
, &isAllowlisted
));
1023 if (isAllowlisted
) {
1028 if (aSourceBaseURI
->SchemeIs("chrome")) {
1034 ReportError(errorTag
, aSourceURI
, aTargetURI
, aFromPrivateWindow
,
1037 return NS_ERROR_DOM_BAD_URI
;
1042 // Everyone is allowed to load this. The case URI_LOADABLE_BY_SUBSUMERS
1043 // is handled by the caller which is just delegating to us as a helper.
1044 bool hasSubsumersFlag
= false;
1045 NS_URIChainHasFlags(aTargetBaseURI
,
1046 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS
,
1048 bool hasLoadableByAnyone
= false;
1049 NS_URIChainHasFlags(aTargetBaseURI
,
1050 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE
,
1051 &hasLoadableByAnyone
);
1052 MOZ_ASSERT(hasLoadableByAnyone
|| hasSubsumersFlag
,
1053 "why do we get here and do not have any of the two flags set?");
1060 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1061 const nsACString
& aSourceSpec
,
1062 const nsACString
& aTargetSpec
,
1063 bool aFromPrivateWindow
,
1064 uint64_t aInnerWindowID
) {
1065 if (aSourceSpec
.IsEmpty() || aTargetSpec
.IsEmpty()) {
1069 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1070 if (NS_WARN_IF(!bundle
)) {
1074 // Localize the error message
1075 nsAutoString message
;
1076 AutoTArray
<nsString
, 2> formatStrings
;
1077 CopyASCIItoUTF16(aSourceSpec
, *formatStrings
.AppendElement());
1078 CopyASCIItoUTF16(aTargetSpec
, *formatStrings
.AppendElement());
1080 bundle
->FormatStringFromName(aMessageTag
, formatStrings
, message
);
1081 NS_ENSURE_SUCCESS(rv
, rv
);
1083 nsCOMPtr
<nsIConsoleService
> console(
1084 do_GetService(NS_CONSOLESERVICE_CONTRACTID
));
1085 NS_ENSURE_TRUE(console
, NS_ERROR_FAILURE
);
1086 nsCOMPtr
<nsIScriptError
> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID
));
1087 NS_ENSURE_TRUE(error
, NS_ERROR_FAILURE
);
1089 // using category of "SOP" so we can link to MDN
1090 if (aInnerWindowID
!= 0) {
1091 rv
= error
->InitWithWindowID(
1092 message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
, "SOP"_ns
,
1093 aInnerWindowID
, true /* From chrome context */);
1095 rv
= error
->Init(message
, u
""_ns
, u
""_ns
, 0, 0, nsIScriptError::errorFlag
,
1096 "SOP", aFromPrivateWindow
, true /* From chrome context */);
1098 NS_ENSURE_SUCCESS(rv
, rv
);
1099 console
->LogMessage(error
);
1103 nsresult
nsScriptSecurityManager::ReportError(const char* aMessageTag
,
1104 nsIURI
* aSource
, nsIURI
* aTarget
,
1105 bool aFromPrivateWindow
,
1106 uint64_t aInnerWindowID
) {
1107 NS_ENSURE_TRUE(aSource
&& aTarget
, NS_ERROR_NULL_POINTER
);
1109 // Get the source URL spec
1110 nsAutoCString sourceSpec
;
1111 nsresult rv
= aSource
->GetAsciiSpec(sourceSpec
);
1112 NS_ENSURE_SUCCESS(rv
, rv
);
1114 // Get the target URL spec
1115 nsAutoCString targetSpec
;
1116 rv
= aTarget
->GetAsciiSpec(targetSpec
);
1117 NS_ENSURE_SUCCESS(rv
, rv
);
1119 return ReportError(aMessageTag
, sourceSpec
, targetSpec
, aFromPrivateWindow
,
1124 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1125 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
,
1128 nsCOMPtr
<nsIURI
> target
;
1129 rv
= NS_NewURI(getter_AddRefs(target
), aTargetURIStr
);
1130 NS_ENSURE_SUCCESS(rv
, rv
);
1132 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1133 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1134 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1138 NS_ENSURE_SUCCESS(rv
, rv
);
1140 // Now start testing fixup -- since aTargetURIStr is a string, not
1141 // an nsIURI, we may well end up fixing it up before loading.
1142 // Note: This needs to stay in sync with the nsIURIFixup api.
1143 nsCOMPtr
<nsIURIFixup
> fixup
= components::URIFixup::Service();
1148 // URIFixup's keyword and alternate flags can only fixup to http/https, so we
1149 // can skip testing them. This simplifies our life because this code can be
1150 // invoked from the content process where the search service would not be
1152 uint32_t flags
[] = {nsIURIFixup::FIXUP_FLAG_NONE
,
1153 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS
};
1154 for (uint32_t i
= 0; i
< ArrayLength(flags
); ++i
) {
1155 uint32_t fixupFlags
= flags
[i
];
1156 if (aPrincipal
->OriginAttributesRef().mPrivateBrowsingId
> 0) {
1157 fixupFlags
|= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT
;
1159 nsCOMPtr
<nsIURIFixupInfo
> fixupInfo
;
1160 rv
= fixup
->GetFixupURIInfo(aTargetURIStr
, fixupFlags
,
1161 getter_AddRefs(fixupInfo
));
1162 NS_ENSURE_SUCCESS(rv
, rv
);
1163 rv
= fixupInfo
->GetPreferredURI(getter_AddRefs(target
));
1164 NS_ENSURE_SUCCESS(rv
, rv
);
1166 rv
= CheckLoadURIWithPrincipal(aPrincipal
, target
, aFlags
, 0);
1167 if (rv
== NS_ERROR_DOM_BAD_URI
) {
1168 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1172 NS_ENSURE_SUCCESS(rv
, rv
);
1179 nsScriptSecurityManager::CheckLoadURIWithPrincipalFromJS(
1180 nsIPrincipal
* aPrincipal
, nsIURI
* aTargetURI
, uint32_t aFlags
,
1181 uint64_t aInnerWindowID
, JSContext
* aCx
) {
1182 MOZ_ASSERT(aPrincipal
,
1183 "CheckLoadURIWithPrincipalFromJS must have a principal");
1184 NS_ENSURE_ARG_POINTER(aPrincipal
);
1185 NS_ENSURE_ARG_POINTER(aTargetURI
);
1188 CheckLoadURIWithPrincipal(aPrincipal
, aTargetURI
, aFlags
, aInnerWindowID
);
1189 if (NS_FAILED(rv
)) {
1190 nsAutoCString uriStr
;
1191 Unused
<< aTargetURI
->GetSpec(uriStr
);
1193 nsAutoCString
message("Load of ");
1194 message
.Append(uriStr
);
1196 nsAutoCString principalStr
;
1197 Unused
<< aPrincipal
->GetSpec(principalStr
);
1198 if (!principalStr
.IsEmpty()) {
1199 message
.AppendPrintf(" from %s", principalStr
.get());
1202 message
.Append(" denied");
1204 dom::Throw(aCx
, rv
, message
);
1211 nsScriptSecurityManager::CheckLoadURIStrWithPrincipalFromJS(
1212 nsIPrincipal
* aPrincipal
, const nsACString
& aTargetURIStr
, uint32_t aFlags
,
1214 nsCOMPtr
<nsIURI
> targetURI
;
1215 MOZ_TRY(NS_NewURI(getter_AddRefs(targetURI
), aTargetURIStr
));
1217 return CheckLoadURIWithPrincipalFromJS(aPrincipal
, targetURI
, aFlags
, 0, aCx
);
1221 nsScriptSecurityManager::InFileURIAllowlist(nsIURI
* aUri
, bool* aResult
) {
1223 MOZ_ASSERT(aResult
);
1226 for (nsIURI
* uri
: EnsureFileURIAllowlist()) {
1227 if (EqualOrSubdomain(aUri
, uri
)) {
1236 ///////////////// Principals ///////////////////////
1239 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal
** result
) {
1240 NS_ADDREF(*result
= mSystemPrincipal
);
1246 nsScriptSecurityManager::CreateContentPrincipal(
1247 nsIURI
* aURI
, JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1248 nsIPrincipal
** aPrincipal
) {
1249 OriginAttributes attrs
;
1250 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1251 return NS_ERROR_INVALID_ARG
;
1253 nsCOMPtr
<nsIPrincipal
> prin
=
1254 BasePrincipal::CreateContentPrincipal(aURI
, attrs
);
1255 prin
.forget(aPrincipal
);
1256 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1260 nsScriptSecurityManager::CreateContentPrincipalFromOrigin(
1261 const nsACString
& aOrigin
, nsIPrincipal
** aPrincipal
) {
1262 if (StringBeginsWith(aOrigin
, "["_ns
)) {
1263 return NS_ERROR_INVALID_ARG
;
1266 if (StringBeginsWith(aOrigin
,
1267 nsLiteralCString(NS_NULLPRINCIPAL_SCHEME
":"))) {
1268 return NS_ERROR_INVALID_ARG
;
1271 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(aOrigin
);
1272 prin
.forget(aPrincipal
);
1273 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1277 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal
* aPrincipal
,
1278 nsACString
& aJSON
) {
1281 return NS_ERROR_FAILURE
;
1284 BasePrincipal::Cast(aPrincipal
)->ToJSON(aJSON
);
1286 if (aJSON
.IsEmpty()) {
1287 return NS_ERROR_FAILURE
;
1294 nsScriptSecurityManager::JSONToPrincipal(const nsACString
& aJSON
,
1295 nsIPrincipal
** aPrincipal
) {
1296 if (aJSON
.IsEmpty()) {
1297 return NS_ERROR_FAILURE
;
1300 nsCOMPtr
<nsIPrincipal
> principal
= BasePrincipal::FromJSON(aJSON
);
1303 return NS_ERROR_FAILURE
;
1306 principal
.forget(aPrincipal
);
1311 nsScriptSecurityManager::CreateNullPrincipal(
1312 JS::Handle
<JS::Value
> aOriginAttributes
, JSContext
* aCx
,
1313 nsIPrincipal
** aPrincipal
) {
1314 OriginAttributes attrs
;
1315 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1316 return NS_ERROR_INVALID_ARG
;
1318 nsCOMPtr
<nsIPrincipal
> prin
= NullPrincipal::Create(attrs
);
1319 prin
.forget(aPrincipal
);
1324 nsScriptSecurityManager::GetLoadContextContentPrincipal(
1325 nsIURI
* aURI
, nsILoadContext
* aLoadContext
, nsIPrincipal
** aPrincipal
) {
1326 NS_ENSURE_STATE(aLoadContext
);
1327 OriginAttributes docShellAttrs
;
1328 aLoadContext
->GetOriginAttributes(docShellAttrs
);
1330 nsCOMPtr
<nsIPrincipal
> prin
=
1331 BasePrincipal::CreateContentPrincipal(aURI
, docShellAttrs
);
1332 prin
.forget(aPrincipal
);
1333 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1337 nsScriptSecurityManager::GetDocShellContentPrincipal(
1338 nsIURI
* aURI
, nsIDocShell
* aDocShell
, nsIPrincipal
** aPrincipal
) {
1339 nsCOMPtr
<nsIPrincipal
> prin
= BasePrincipal::CreateContentPrincipal(
1340 aURI
, nsDocShell::Cast(aDocShell
)->GetOriginAttributes());
1341 prin
.forget(aPrincipal
);
1342 return *aPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1346 nsScriptSecurityManager::PrincipalWithOA(
1347 nsIPrincipal
* aPrincipal
, JS::Handle
<JS::Value
> aOriginAttributes
,
1348 JSContext
* aCx
, nsIPrincipal
** aReturnPrincipal
) {
1352 if (aPrincipal
->GetIsContentPrincipal()) {
1353 OriginAttributes attrs
;
1354 if (!aOriginAttributes
.isObject() || !attrs
.Init(aCx
, aOriginAttributes
)) {
1355 return NS_ERROR_INVALID_ARG
;
1357 auto* contentPrincipal
= static_cast<ContentPrincipal
*>(aPrincipal
);
1358 RefPtr
<ContentPrincipal
> copy
=
1359 new ContentPrincipal(contentPrincipal
, attrs
);
1360 NS_ENSURE_TRUE(copy
, NS_ERROR_FAILURE
);
1361 copy
.forget(aReturnPrincipal
);
1363 // We do this for null principals, system principals (both fine)
1364 // ... and expanded principals, where we should probably do something
1365 // cleverer, but I also don't think we care too much.
1366 nsCOMPtr
<nsIPrincipal
> prin
= aPrincipal
;
1367 prin
.forget(aReturnPrincipal
);
1370 return *aReturnPrincipal
? NS_OK
: NS_ERROR_FAILURE
;
1374 nsScriptSecurityManager::CanCreateWrapper(JSContext
* cx
, const nsIID
& aIID
,
1376 nsIClassInfo
* aClassInfo
) {
1377 // XXX Special case for Exception ?
1379 // We give remote-XUL allowlisted domains a free pass here. See bug 932906.
1380 JS::Rooted
<JS::Realm
*> contextRealm(cx
, JS::GetCurrentRealmOrNull(cx
));
1381 MOZ_RELEASE_ASSERT(contextRealm
);
1382 if (!xpc::AllowContentXBLScope(contextRealm
)) {
1386 if (nsContentUtils::IsCallerChrome()) {
1390 //-- Access denied, report an error
1391 nsAutoCString originUTF8
;
1392 nsIPrincipal
* subjectPrincipal
= nsContentUtils::SubjectPrincipal();
1393 GetPrincipalDomainOrigin(subjectPrincipal
, originUTF8
);
1394 NS_ConvertUTF8toUTF16
originUTF16(originUTF8
);
1395 nsAutoCString classInfoNameUTF8
;
1397 aClassInfo
->GetClassDescription(classInfoNameUTF8
);
1399 if (classInfoNameUTF8
.IsEmpty()) {
1400 classInfoNameUTF8
.AssignLiteral("UnnamedClass");
1403 nsCOMPtr
<nsIStringBundle
> bundle
= BundleHelper::GetOrCreate();
1404 if (NS_WARN_IF(!bundle
)) {
1408 NS_ConvertUTF8toUTF16
classInfoUTF16(classInfoNameUTF8
);
1410 nsAutoString errorMsg
;
1411 if (originUTF16
.IsEmpty()) {
1412 AutoTArray
<nsString
, 1> formatStrings
= {classInfoUTF16
};
1413 rv
= bundle
->FormatStringFromName("CreateWrapperDenied", formatStrings
,
1416 AutoTArray
<nsString
, 2> formatStrings
= {classInfoUTF16
, originUTF16
};
1417 rv
= bundle
->FormatStringFromName("CreateWrapperDeniedForOrigin",
1418 formatStrings
, errorMsg
);
1420 NS_ENSURE_SUCCESS(rv
, rv
);
1422 SetPendingException(cx
, errorMsg
.get());
1423 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1427 nsScriptSecurityManager::CanCreateInstance(JSContext
* cx
, const nsCID
& aCID
) {
1428 if (nsContentUtils::IsCallerChrome()) {
1432 //-- Access denied, report an error
1433 nsAutoCString
errorMsg("Permission denied to create instance of class. CID=");
1434 char cidStr
[NSID_LENGTH
];
1435 aCID
.ToProvidedString(cidStr
);
1436 errorMsg
.Append(cidStr
);
1437 SetPendingExceptionASCII(cx
, errorMsg
.get());
1438 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1442 nsScriptSecurityManager::CanGetService(JSContext
* cx
, const nsCID
& aCID
) {
1443 if (nsContentUtils::IsCallerChrome()) {
1447 //-- Access denied, report an error
1448 nsAutoCString
errorMsg("Permission denied to get service. CID=");
1449 char cidStr
[NSID_LENGTH
];
1450 aCID
.ToProvidedString(cidStr
);
1451 errorMsg
.Append(cidStr
);
1452 SetPendingExceptionASCII(cx
, errorMsg
.get());
1453 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED
;
1456 const char sJSEnabledPrefName
[] = "javascript.enabled";
1457 const char sFileOriginPolicyPrefName
[] =
1458 "security.fileuri.strict_origin_policy";
1460 static const char* kObservedPrefs
[] = {sJSEnabledPrefName
,
1461 sFileOriginPolicyPrefName
,
1462 "capability.policy.", nullptr};
1464 /////////////////////////////////////////////
1465 // Constructor, Destructor, Initialization //
1466 /////////////////////////////////////////////
1467 nsScriptSecurityManager::nsScriptSecurityManager(void)
1468 : mPrefInitialized(false), mIsJavaScriptEnabled(false) {
1470 sizeof(intptr_t) == sizeof(void*),
1471 "intptr_t and void* have different lengths on this platform. "
1472 "This may cause a security failure with the SecurityLevel union.");
1475 nsresult
nsScriptSecurityManager::Init() {
1476 nsresult rv
= CallGetService(NS_IOSERVICE_CONTRACTID
, &sIOService
);
1477 NS_ENSURE_SUCCESS(rv
, rv
);
1481 // Create our system principal singleton
1482 RefPtr
<SystemPrincipal
> system
= SystemPrincipal::Create();
1484 mSystemPrincipal
= system
;
1489 void nsScriptSecurityManager::InitJSCallbacks(JSContext
* aCx
) {
1490 //-- Register security check callback in the JS engine
1491 // Currently this is used to control access to function.caller
1493 static const JSSecurityCallbacks securityCallbacks
= {
1494 ContentSecurityPolicyPermitsJSAction
,
1495 JSPrincipalsSubsume
,
1498 MOZ_ASSERT(!JS_GetSecurityCallbacks(aCx
));
1499 JS_SetSecurityCallbacks(aCx
, &securityCallbacks
);
1500 JS_InitDestroyPrincipalsCallback(aCx
, nsJSPrincipals::Destroy
);
1502 JS_SetTrustedPrincipals(aCx
, BasePrincipal::Cast(mSystemPrincipal
));
1506 void nsScriptSecurityManager::ClearJSCallbacks(JSContext
* aCx
) {
1507 JS_SetSecurityCallbacks(aCx
, nullptr);
1508 JS_SetTrustedPrincipals(aCx
, nullptr);
1511 static StaticRefPtr
<nsScriptSecurityManager
> gScriptSecMan
;
1513 nsScriptSecurityManager::~nsScriptSecurityManager(void) {
1514 Preferences::UnregisterPrefixCallbacks(
1515 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1516 if (mDomainPolicy
) {
1517 mDomainPolicy
->Deactivate();
1519 // ContentChild might hold a reference to the domain policy,
1520 // and it might release it only after the security manager is
1521 // gone. But we can still assert this for the main process.
1522 MOZ_ASSERT_IF(XRE_IsParentProcess(), !mDomainPolicy
);
1525 void nsScriptSecurityManager::Shutdown() {
1526 NS_IF_RELEASE(sIOService
);
1527 BundleHelper::Shutdown();
1530 nsScriptSecurityManager
* nsScriptSecurityManager::GetScriptSecurityManager() {
1531 return gScriptSecMan
;
1535 void nsScriptSecurityManager::InitStatics() {
1536 RefPtr
<nsScriptSecurityManager
> ssManager
= new nsScriptSecurityManager();
1537 nsresult rv
= ssManager
->Init();
1538 if (NS_FAILED(rv
)) {
1539 MOZ_CRASH("ssManager->Init() failed");
1542 ClearOnShutdown(&gScriptSecMan
);
1543 gScriptSecMan
= ssManager
;
1546 // Currently this nsGenericFactory constructor is used only from FastLoad
1547 // (XPCOM object deserialization) code, when "creating" the system principal
1549 already_AddRefed
<SystemPrincipal
>
1550 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1552 return do_AddRef(gScriptSecMan
->mSystemPrincipal
)
1553 .downcast
<SystemPrincipal
>();
1557 struct IsWhitespace
{
1558 static bool Test(char aChar
) { return NS_IsAsciiWhitespace(aChar
); };
1560 struct IsWhitespaceOrComma
{
1561 static bool Test(char aChar
) {
1562 return aChar
== ',' || NS_IsAsciiWhitespace(aChar
);
1566 template <typename Predicate
>
1567 uint32_t SkipPast(const nsCString
& str
, uint32_t base
) {
1568 while (base
< str
.Length() && Predicate::Test(str
[base
])) {
1574 template <typename Predicate
>
1575 uint32_t SkipUntil(const nsCString
& str
, uint32_t base
) {
1576 while (base
< str
.Length() && !Predicate::Test(str
[base
])) {
1583 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref
,
1585 static_cast<nsScriptSecurityManager
*>(aSelf
)->ScriptSecurityPrefChanged(
1589 inline void nsScriptSecurityManager::ScriptSecurityPrefChanged(
1590 const char* aPref
) {
1591 MOZ_ASSERT(mPrefInitialized
);
1592 mIsJavaScriptEnabled
=
1593 Preferences::GetBool(sJSEnabledPrefName
, mIsJavaScriptEnabled
);
1594 sStrictFileOriginPolicy
=
1595 Preferences::GetBool(sFileOriginPolicyPrefName
, false);
1596 mFileURIAllowlist
.reset();
1599 void nsScriptSecurityManager::AddSitesToFileURIAllowlist(
1600 const nsCString
& aSiteList
) {
1601 for (uint32_t base
= SkipPast
<IsWhitespace
>(aSiteList
, 0), bound
= 0;
1602 base
< aSiteList
.Length();
1603 base
= SkipPast
<IsWhitespace
>(aSiteList
, bound
)) {
1604 // Grab the current site.
1605 bound
= SkipUntil
<IsWhitespace
>(aSiteList
, base
);
1606 nsAutoCString
site(Substring(aSiteList
, base
, bound
- base
));
1608 // Check if the URI is schemeless. If so, add both http and https.
1609 nsAutoCString unused
;
1610 if (NS_FAILED(sIOService
->ExtractScheme(site
, unused
))) {
1611 AddSitesToFileURIAllowlist("http://"_ns
+ site
);
1612 AddSitesToFileURIAllowlist("https://"_ns
+ site
);
1616 // Convert it to a URI and add it to our list.
1617 nsCOMPtr
<nsIURI
> uri
;
1618 nsresult rv
= NS_NewURI(getter_AddRefs(uri
), site
);
1619 if (NS_SUCCEEDED(rv
)) {
1620 mFileURIAllowlist
.ref().AppendElement(uri
);
1622 nsCOMPtr
<nsIConsoleService
> console(
1623 do_GetService("@mozilla.org/consoleservice;1"));
1626 u
"Unable to to add site to file:// URI allowlist: "_ns
+
1627 NS_ConvertASCIItoUTF16(site
);
1628 console
->LogStringMessage(msg
.get());
1634 nsresult
nsScriptSecurityManager::InitPrefs() {
1635 nsIPrefBranch
* branch
= Preferences::GetRootBranch();
1636 NS_ENSURE_TRUE(branch
, NS_ERROR_FAILURE
);
1638 mPrefInitialized
= true;
1640 // Set the initial value of the "javascript.enabled" prefs
1641 ScriptSecurityPrefChanged();
1643 // set observer callbacks in case the value of the prefs change
1644 Preferences::RegisterPrefixCallbacks(
1645 nsScriptSecurityManager::ScriptSecurityPrefChanged
, kObservedPrefs
, this);
1651 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv
) {
1652 *aRv
= !!mDomainPolicy
;
1657 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy
** aRv
) {
1658 if (!XRE_IsParentProcess()) {
1659 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1662 return ActivateDomainPolicyInternal(aRv
);
1666 nsScriptSecurityManager::ActivateDomainPolicyInternal(nsIDomainPolicy
** aRv
) {
1667 // We only allow one domain policy at a time. The holder of the previous
1668 // policy must explicitly deactivate it first.
1669 if (mDomainPolicy
) {
1670 return NS_ERROR_SERVICE_NOT_AVAILABLE
;
1673 mDomainPolicy
= new DomainPolicy();
1674 nsCOMPtr
<nsIDomainPolicy
> ptr
= mDomainPolicy
;
1679 // Intentionally non-scriptable. Script must have a reference to the
1680 // nsIDomainPolicy to deactivate it.
1681 void nsScriptSecurityManager::DeactivateDomainPolicy() {
1682 mDomainPolicy
= nullptr;
1685 void nsScriptSecurityManager::CloneDomainPolicy(DomainPolicyClone
* aClone
) {
1687 if (mDomainPolicy
) {
1688 mDomainPolicy
->CloneDomainPolicy(aClone
);
1690 aClone
->active() = false;
1695 nsScriptSecurityManager::PolicyAllowsScript(nsIURI
* aURI
, bool* aRv
) {
1698 // Compute our rule. If we don't have any domain policy set up that might
1699 // provide exceptions to this rule, we're done.
1700 *aRv
= mIsJavaScriptEnabled
;
1701 if (!mDomainPolicy
) {
1705 // We have a domain policy. Grab the appropriate set of exceptions to the
1706 // rule (either the blocklist or the allowlist, depending on whether script
1707 // is enabled or disabled by default).
1708 nsCOMPtr
<nsIDomainSet
> exceptions
;
1709 nsCOMPtr
<nsIDomainSet
> superExceptions
;
1711 mDomainPolicy
->GetBlocklist(getter_AddRefs(exceptions
));
1712 mDomainPolicy
->GetSuperBlocklist(getter_AddRefs(superExceptions
));
1714 mDomainPolicy
->GetAllowlist(getter_AddRefs(exceptions
));
1715 mDomainPolicy
->GetSuperAllowlist(getter_AddRefs(superExceptions
));
1719 rv
= exceptions
->Contains(aURI
, &contains
);
1720 NS_ENSURE_SUCCESS(rv
, rv
);
1725 rv
= superExceptions
->ContainsSuperDomain(aURI
, &contains
);
1726 NS_ENSURE_SUCCESS(rv
, rv
);
1734 const nsTArray
<nsCOMPtr
<nsIURI
>>&
1735 nsScriptSecurityManager::EnsureFileURIAllowlist() {
1736 if (mFileURIAllowlist
.isSome()) {
1737 return mFileURIAllowlist
.ref();
1741 // Rebuild the set of principals for which we allow file:// URI loads. This
1742 // implements a small subset of an old pref-based CAPS people that people
1743 // have come to depend on. See bug 995943.
1746 mFileURIAllowlist
.emplace();
1747 nsAutoCString policies
;
1748 mozilla::Preferences::GetCString("capability.policy.policynames", policies
);
1749 for (uint32_t base
= SkipPast
<IsWhitespaceOrComma
>(policies
, 0), bound
= 0;
1750 base
< policies
.Length();
1751 base
= SkipPast
<IsWhitespaceOrComma
>(policies
, bound
)) {
1752 // Grab the current policy name.
1753 bound
= SkipUntil
<IsWhitespaceOrComma
>(policies
, base
);
1754 auto policyName
= Substring(policies
, base
, bound
- base
);
1756 // Figure out if this policy allows loading file:// URIs. If not, we can
1758 nsCString checkLoadURIPrefName
=
1759 "capability.policy."_ns
+ policyName
+ ".checkloaduri.enabled"_ns
;
1761 nsresult rv
= Preferences::GetString(checkLoadURIPrefName
.get(), value
);
1762 if (NS_FAILED(rv
) || !value
.LowerCaseEqualsLiteral("allaccess")) {
1766 // Grab the list of domains associated with this policy.
1767 nsCString domainPrefName
=
1768 "capability.policy."_ns
+ policyName
+ ".sites"_ns
;
1769 nsAutoCString siteList
;
1770 Preferences::GetCString(domainPrefName
.get(), siteList
);
1771 AddSitesToFileURIAllowlist(siteList
);
1774 return mFileURIAllowlist
.ref();