Bug 1690340 - Part 2: Use the new naming for the developer tools menu items. r=jdescottes
[gecko.git] / caps / nsScriptSecurityManager.cpp
blob73fa1b7d510b7472b2f4d7888c3476f379eb060b
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"
21 #include "nspr.h"
22 #include "nsJSPrincipals.h"
23 #include "mozilla/BasePrincipal.h"
24 #include "ExpandedPrincipal.h"
25 #include "SystemPrincipal.h"
26 #include "DomainPolicy.h"
27 #include "nsString.h"
28 #include "nsCRT.h"
29 #include "nsCRTGlue.h"
30 #include "nsContentSecurityUtils.h"
31 #include "nsDocShell.h"
32 #include "nsError.h"
33 #include "nsGlobalWindowInner.h"
34 #include "nsDOMCID.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"
57 #include <stdint.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;
81 namespace {
83 class BundleHelper {
84 public:
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.
92 if (sShutdown) {
93 return nullptr;
96 if (!sSelf) {
97 sSelf = new BundleHelper();
100 return sSelf->GetOrCreateInternal();
103 static void Shutdown() {
104 sSelf = nullptr;
105 sShutdown = true;
108 private:
109 ~BundleHelper() = default;
111 nsIStringBundle* GetOrCreateInternal() {
112 if (!mBundle) {
113 nsCOMPtr<nsIStringBundleService> bundleService =
114 mozilla::services::GetStringBundleService();
115 if (NS_WARN_IF(!bundleService)) {
116 return nullptr;
119 nsresult rv = bundleService->CreateBundle(
120 "chrome://global/locale/security/caps.properties",
121 getter_AddRefs(mBundle));
122 if (NS_WARN_IF(NS_FAILED(rv))) {
123 return nullptr;
127 return mBundle;
130 nsCOMPtr<nsIStringBundle> mBundle;
132 static StaticRefPtr<BundleHelper> sSelf;
133 static bool sShutdown;
136 StaticRefPtr<BundleHelper> BundleHelper::sSelf;
137 bool BundleHelper::sShutdown = false;
139 } // namespace
141 ///////////////////////////
142 // Convenience Functions //
143 ///////////////////////////
145 class nsAutoInPrincipalDomainOriginSetter {
146 public:
147 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin; }
148 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin; }
149 static uint32_t sInPrincipalDomainOrigin;
151 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
153 static nsresult GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin) {
154 if (!aURI) {
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;
178 } else {
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);
185 return NS_OK;
188 static nsresult GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
189 nsACString& aOrigin) {
190 aOrigin.Truncate();
191 nsCOMPtr<nsIURI> uri;
192 aPrincipal->GetDomain(getter_AddRefs(uri));
193 nsresult rv = GetOriginFromURI(uri, aOrigin);
194 if (NS_SUCCEEDED(rv)) {
195 return 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());
210 /* static */
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
219 // nsNetUtil.h.
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.
233 NS_IMETHODIMP
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);
246 NS_IMETHODIMP
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))) {
253 return rv;
256 return StoragePrincipalHelper::Create(
257 aChannel, principal, /* aForceIsolation */ false, aPrincipal);
260 NS_IMETHODIMP
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))) {
267 return 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);
276 return NS_OK;
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);
293 return NS_OK;
296 nsCOMPtr<nsISupports> owner;
297 aChannel->GetOwner(getter_AddRefs(owner));
298 if (owner) {
299 CallQueryInterface(owner, aPrincipal);
300 if (*aPrincipal) {
301 return NS_OK;
305 if (!aIgnoreSandboxing && loadInfo->GetLoadingSandboxed()) {
306 nsCOMPtr<nsIPrincipal> sandboxedLoadingPrincipal =
307 loadInfo->GetSandboxedLoadingPrincipal();
308 MOZ_ASSERT(sandboxedLoadingPrincipal);
309 sandboxedLoadingPrincipal.forget(aPrincipal);
310 return NS_OK;
313 bool forceInherit = loadInfo->GetForceInheritPrincipal();
314 if (aIgnoreSandboxing && !forceInherit) {
315 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
316 // sandboxing:
317 if (loadInfo->GetLoadingSandboxed() &&
318 loadInfo->GetForceInheritPrincipalDropped()) {
319 forceInherit = true;
322 if (forceInherit) {
323 nsCOMPtr<nsIPrincipal> principalToInherit =
324 loadInfo->FindPrincipalToInherit(aChannel);
325 principalToInherit.forget(aPrincipal);
326 return NS_OK;
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() &&
333 (securityMode ==
334 nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT ||
335 securityMode ==
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);
349 return NS_OK;
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)."
366 NS_IMETHODIMP
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)) {
414 csp = win->GetCsp();
417 nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
418 if (!csp) {
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
428 if (!csp) {
429 return true;
433 nsCOMPtr<nsICSPEventListener> cspEventListener;
434 if (!NS_IsMainThread()) {
435 WorkerPrivate* workerPrivate =
436 mozilla::dom::GetWorkerPrivateFromContext(cx);
437 if (workerPrivate) {
438 cspEventListener = workerPrivate->CSPEventListener();
442 bool evalOK = true;
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);
454 return false;
458 #if !defined(ANDROID)
459 if (!nsContentSecurityUtils::IsEvalAllowed(
460 cx, subjectPrincipal->IsSystemPrincipal(), scriptSample)) {
461 return false;
463 #endif
465 if (NS_FAILED(rv)) {
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);
479 } else {
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);
488 return evalOK;
491 // static
492 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals* first,
493 JSPrincipals* second) {
494 return nsJSPrincipals::get(first)->Subsumes(nsJSPrincipals::get(second));
497 NS_IMETHODIMP
498 nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
499 nsIURI* aTargetURI,
500 bool reportError,
501 bool aFromPrivateWindow) {
502 // Please note that aFromPrivateWindow is only 100% accurate if
503 // reportError is true.
504 if (!SecurityCompareURIs(aSourceURI, aTargetURI)) {
505 if (reportError) {
506 ReportError("CheckSameOriginError", aSourceURI, aTargetURI,
507 aFromPrivateWindow);
509 return NS_ERROR_DOM_BAD_URI;
511 return NS_OK;
514 NS_IMETHODIMP
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)) {
524 // OK to load
525 return NS_OK;
528 // Report error.
529 nsAutoCString spec;
530 if (NS_FAILED(aURI->GetAsciiSpec(spec))) return NS_ERROR_FAILURE;
531 nsAutoCString msg("Access to '");
532 msg.Append(spec);
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!");
547 bool uriHasFlags;
548 nsresult rv = NS_URIChainHasFlags(aURI, aURIFlags, &uriHasFlags);
549 NS_ENSURE_SUCCESS(rv, rv);
551 if (uriHasFlags) {
552 return NS_ERROR_DOM_BAD_URI;
555 return NS_OK;
558 static bool EqualOrSubdomain(nsIURI* aProbeArg, nsIURI* aBase) {
559 nsresult rv;
560 nsCOMPtr<nsIURI> probe = aProbeArg;
562 nsCOMPtr<nsIEffectiveTLDService> tldService =
563 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
564 NS_ENSURE_TRUE(tldService, false);
565 while (true) {
566 if (nsScriptSecurityManager::SecurityCompareURIs(probe, aBase)) {
567 return true;
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) {
576 return false;
578 NS_ENSURE_SUCCESS(rv, false);
579 rv = NS_MutateURI(probe).SetHost(newHost).Finalize(probe);
580 NS_ENSURE_SUCCESS(rv, false);
584 NS_IMETHODIMP
585 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal* aPrincipal,
586 nsIURI* aTargetURI,
587 uint32_t aFlags,
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
593 // provide.
594 NS_ENSURE_FALSE(
595 aFlags &
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) {
615 // Allow access
616 return NS_OK;
619 nsCOMPtr<nsIURI> sourceURI;
620 auto* basePrin = BasePrincipal::Cast(aPrincipal);
621 basePrin->GetURI(getter_AddRefs(sourceURI));
622 if (!sourceURI) {
623 if (basePrin->Is<ExpandedPrincipal>()) {
624 auto expanded = basePrin->As<ExpandedPrincipal>();
625 for (auto& prin : expanded->AllowList()) {
626 nsresult rv =
627 CheckLoadURIWithPrincipal(prin, aTargetURI, aFlags, aInnerWindowID);
628 if (NS_SUCCEEDED(rv)) {
629 // Allow access if it succeeded with one of the allowlisted principals
630 return NS_OK;
633 // None of our allowlisted principals worked.
634 return NS_ERROR_DOM_BAD_URI;
636 NS_ERROR(
637 "Non-system principals or expanded principal passed to "
638 "CheckLoadURIWithPrincipal "
639 "must have a URI!");
640 return NS_ERROR_UNEXPECTED;
643 // Automatic loads are not allowed from certain protocols.
644 if (aFlags &
645 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT) {
646 nsresult rv = DenyAccessIfURIHasFlags(
647 sourceURI,
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
676 // access:
677 rv = CheckLoadURIFlags(
678 sourceURI, aTargetURI, sourceBaseURI, targetBaseURI, aFlags,
679 aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0,
680 aInnerWindowID);
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,
687 aInnerWindowID);
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) {
698 return NS_OK;
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.
706 return NS_OK;
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()) {
718 return NS_OK;
721 // If we get here, check all the schemes can link to each other, from the top
722 // down:
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);
737 bool schemesMatch =
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:
744 isSamePage =
745 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI, moduleName)) &&
746 NS_SUCCEEDED(
747 NS_GetAboutModuleName(currentOtherURI, otherModuleName)) &&
748 moduleName.Equals(otherModuleName);
749 if (!isSamePage) {
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 =
761 NS_SUCCEEDED(
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;
767 knowBothModules =
768 knowBothModules &&
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);
776 if (isSamePage &&
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.
783 return NS_OK;
787 } else {
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,
802 aInnerWindowID);
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) {
810 return NS_OK;
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);
850 if (NS_FAILED(rv)) {
851 // Deny access, since the origin principal is not system
852 if (reportErrors) {
853 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
854 aInnerWindowID);
856 return rv;
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);
864 if (NS_FAILED(rv)) {
865 if (reportErrors) {
866 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
867 aInnerWindowID);
869 return rv;
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
893 if (StaticPrefs::
894 security_caps_allow_uri_is_ui_resource_in_checkloaduriflags()) {
895 return NS_OK;
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")) {
900 return NS_OK;
904 if (targetScheme.EqualsLiteral("resource")) {
905 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
906 return NS_OK;
909 nsCOMPtr<nsIProtocolHandler> ph;
910 rv = sIOService->GetProtocolHandler("resource", getter_AddRefs(ph));
911 NS_ENSURE_SUCCESS(rv, rv);
912 if (!ph) {
913 return NS_ERROR_DOM_BAD_URI;
916 nsCOMPtr<nsIResProtocolHandler> rph = do_QueryInterface(ph);
917 if (!rph) {
918 return NS_ERROR_DOM_BAD_URI;
921 bool accessAllowed = false;
922 rph->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
923 if (accessAllowed) {
924 return NS_OK;
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));
930 if (reg) {
931 bool accessAllowed = false;
932 reg->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
933 if (accessAllowed) {
934 return NS_OK;
937 } else if (targetScheme.EqualsLiteral("moz-page-thumb")) {
938 if (XRE_IsParentProcess()) {
939 return NS_OK;
942 auto& remoteType = dom::ContentChild::GetSingleton()->GetRemoteType();
943 if (remoteType == PRIVILEGEDABOUT_REMOTE_TYPE) {
944 return NS_OK;
949 if (reportErrors) {
950 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
951 aInnerWindowID);
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.
964 bool isAllowlisted;
965 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI, &isAllowlisted));
966 if (isAllowlisted) {
967 return NS_OK;
970 // Allow chrome://
971 if (aSourceBaseURI->SchemeIs("chrome")) {
972 return NS_OK;
975 // Nothing else.
976 if (reportErrors) {
977 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
978 aInnerWindowID);
980 return NS_ERROR_DOM_BAD_URI;
983 #ifdef DEBUG
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,
990 &hasSubsumersFlag);
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?");
998 #endif
1000 return NS_OK;
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()) {
1009 return NS_OK;
1012 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
1013 if (NS_WARN_IF(!bundle)) {
1014 return NS_OK;
1017 // Localize the error message
1018 nsAutoString message;
1019 AutoTArray<nsString, 2> formatStrings;
1020 CopyASCIItoUTF16(aSourceSpec, *formatStrings.AppendElement());
1021 CopyASCIItoUTF16(aTargetSpec, *formatStrings.AppendElement());
1022 nsresult rv =
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 */);
1037 } else {
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);
1043 return NS_OK;
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,
1063 aInnerWindowID);
1066 NS_IMETHODIMP
1067 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1068 nsIPrincipal* aPrincipal, const nsACString& aTargetURIStr,
1069 uint32_t aFlags) {
1070 nsresult rv;
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
1078 // return values.
1079 return rv;
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();
1087 if (!fixup) {
1088 return rv;
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
1094 // available.
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
1112 // return values.
1113 return rv;
1115 NS_ENSURE_SUCCESS(rv, rv);
1118 return rv;
1121 NS_IMETHODIMP
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);
1130 nsresult rv =
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);
1150 return rv;
1153 NS_IMETHODIMP
1154 nsScriptSecurityManager::CheckLoadURIStrWithPrincipalFromJS(
1155 nsIPrincipal* aPrincipal, const nsACString& aTargetURIStr, uint32_t aFlags,
1156 JSContext* aCx) {
1157 nsCOMPtr<nsIURI> targetURI;
1158 MOZ_TRY(NS_NewURI(getter_AddRefs(targetURI), aTargetURIStr));
1160 return CheckLoadURIWithPrincipalFromJS(aPrincipal, targetURI, aFlags, 0, aCx);
1163 NS_IMETHODIMP
1164 nsScriptSecurityManager::InFileURIAllowlist(nsIURI* aUri, bool* aResult) {
1165 MOZ_ASSERT(aUri);
1166 MOZ_ASSERT(aResult);
1168 *aResult = false;
1169 for (nsIURI* uri : EnsureFileURIAllowlist()) {
1170 if (EqualOrSubdomain(aUri, uri)) {
1171 *aResult = true;
1172 return NS_OK;
1176 return NS_OK;
1179 ///////////////// Principals ///////////////////////
1181 NS_IMETHODIMP
1182 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal** result) {
1183 NS_ADDREF(*result = mSystemPrincipal);
1185 return NS_OK;
1188 NS_IMETHODIMP
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;
1202 NS_IMETHODIMP
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;
1219 NS_IMETHODIMP
1220 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal* aPrincipal,
1221 nsACString& aJSON) {
1222 aJSON.Truncate();
1223 if (!aPrincipal) {
1224 return NS_ERROR_FAILURE;
1227 BasePrincipal::Cast(aPrincipal)->ToJSON(aJSON);
1229 if (aJSON.IsEmpty()) {
1230 return NS_ERROR_FAILURE;
1233 return NS_OK;
1236 NS_IMETHODIMP
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);
1245 if (!principal) {
1246 return NS_ERROR_FAILURE;
1249 principal.forget(aPrincipal);
1250 return NS_OK;
1253 NS_IMETHODIMP
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);
1263 return NS_OK;
1266 NS_IMETHODIMP
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;
1279 NS_IMETHODIMP
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;
1288 NS_IMETHODIMP
1289 nsScriptSecurityManager::PrincipalWithOA(
1290 nsIPrincipal* aPrincipal, JS::Handle<JS::Value> aOriginAttributes,
1291 JSContext* aCx, nsIPrincipal** aReturnPrincipal) {
1292 if (!aPrincipal) {
1293 return NS_OK;
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);
1305 } else {
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;
1316 NS_IMETHODIMP
1317 nsScriptSecurityManager::CanCreateWrapper(JSContext* cx, const nsIID& aIID,
1318 nsISupports* aObj,
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)) {
1326 return NS_OK;
1329 if (nsContentUtils::IsCallerChrome()) {
1330 return NS_OK;
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;
1339 if (aClassInfo) {
1340 aClassInfo->GetClassDescription(classInfoNameUTF8);
1342 if (classInfoNameUTF8.IsEmpty()) {
1343 classInfoNameUTF8.AssignLiteral("UnnamedClass");
1346 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
1347 if (NS_WARN_IF(!bundle)) {
1348 return NS_OK;
1351 NS_ConvertUTF8toUTF16 classInfoUTF16(classInfoNameUTF8);
1352 nsresult rv;
1353 nsAutoString errorMsg;
1354 if (originUTF16.IsEmpty()) {
1355 AutoTArray<nsString, 1> formatStrings = {classInfoUTF16};
1356 rv = bundle->FormatStringFromName("CreateWrapperDenied", formatStrings,
1357 errorMsg);
1358 } else {
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;
1369 NS_IMETHODIMP
1370 nsScriptSecurityManager::CanCreateInstance(JSContext* cx, const nsCID& aCID) {
1371 if (nsContentUtils::IsCallerChrome()) {
1372 return NS_OK;
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;
1384 NS_IMETHODIMP
1385 nsScriptSecurityManager::CanGetService(JSContext* cx, const nsCID& aCID) {
1386 if (nsContentUtils::IsCallerChrome()) {
1387 return NS_OK;
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) {
1412 static_assert(
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);
1422 InitPrefs();
1424 // Create our system principal singleton
1425 RefPtr<SystemPrincipal> system = SystemPrincipal::Create();
1427 mSystemPrincipal = system;
1429 return NS_OK;
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));
1448 /* static */
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;
1477 /* static */
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
1491 // singleton.
1492 already_AddRefed<SystemPrincipal>
1493 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1494 if (gScriptSecMan)
1495 return do_AddRef(gScriptSecMan->mSystemPrincipal)
1496 .downcast<SystemPrincipal>();
1497 return nullptr;
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])) {
1512 ++base;
1514 return base;
1517 template <typename Predicate>
1518 uint32_t SkipUntil(const nsCString& str, uint32_t base) {
1519 while (base < str.Length() && !Predicate::Test(str[base])) {
1520 ++base;
1522 return base;
1525 // static
1526 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref,
1527 void* aSelf) {
1528 static_cast<nsScriptSecurityManager*>(aSelf)->ScriptSecurityPrefChanged(
1529 aPref);
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);
1556 continue;
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);
1564 } else {
1565 nsCOMPtr<nsIConsoleService> console(
1566 do_GetService("@mozilla.org/consoleservice;1"));
1567 if (console) {
1568 nsAutoString msg =
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);
1590 return NS_OK;
1593 NS_IMETHODIMP
1594 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv) {
1595 *aRv = !!mDomainPolicy;
1596 return NS_OK;
1599 NS_IMETHODIMP
1600 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy** aRv) {
1601 if (!XRE_IsParentProcess()) {
1602 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1605 return ActivateDomainPolicyInternal(aRv);
1608 NS_IMETHODIMP
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;
1618 ptr.forget(aRv);
1619 return NS_OK;
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) {
1629 MOZ_ASSERT(aClone);
1630 if (mDomainPolicy) {
1631 mDomainPolicy->CloneDomainPolicy(aClone);
1632 } else {
1633 aClone->active() = false;
1637 NS_IMETHODIMP
1638 nsScriptSecurityManager::PolicyAllowsScript(nsIURI* aURI, bool* aRv) {
1639 nsresult rv;
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) {
1645 return NS_OK;
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;
1653 if (*aRv) {
1654 mDomainPolicy->GetBlocklist(getter_AddRefs(exceptions));
1655 mDomainPolicy->GetSuperBlocklist(getter_AddRefs(superExceptions));
1656 } else {
1657 mDomainPolicy->GetAllowlist(getter_AddRefs(exceptions));
1658 mDomainPolicy->GetSuperAllowlist(getter_AddRefs(superExceptions));
1661 bool contains;
1662 rv = exceptions->Contains(aURI, &contains);
1663 NS_ENSURE_SUCCESS(rv, rv);
1664 if (contains) {
1665 *aRv = !*aRv;
1666 return NS_OK;
1668 rv = superExceptions->ContainsSuperDomain(aURI, &contains);
1669 NS_ENSURE_SUCCESS(rv, rv);
1670 if (contains) {
1671 *aRv = !*aRv;
1674 return NS_OK;
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
1700 // skip it.
1701 nsCString checkLoadURIPrefName =
1702 "capability.policy."_ns + policyName + ".checkloaduri.enabled"_ns;
1703 nsAutoString value;
1704 nsresult rv = Preferences::GetString(checkLoadURIPrefName.get(), value);
1705 if (NS_FAILED(rv) || !value.LowerCaseEqualsLiteral("allaccess")) {
1706 continue;
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();