Bug 1625482 [wpt PR 22496] - [ScrollTimeline] Do not show scrollbar to bypass flakine...
[gecko.git] / caps / nsScriptSecurityManager.cpp
blob840e9c64c25d3fdf30d6cf233b7a0dc41a52ada2
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/nsCSPContext.h"
59 #include "mozilla/dom/ScriptSettings.h"
60 #include "mozilla/ClearOnShutdown.h"
61 #include "mozilla/StaticPtr.h"
62 #include "mozilla/dom/WorkerCommon.h"
63 #include "mozilla/dom/WorkerPrivate.h"
64 #include "nsContentUtils.h"
65 #include "nsJSUtils.h"
66 #include "nsILoadInfo.h"
68 // This should be probably defined on some other place... but I couldn't find it
69 #define WEBAPPS_PERM_NAME "webapps-manage"
71 using namespace mozilla;
72 using namespace mozilla::dom;
74 nsIIOService* nsScriptSecurityManager::sIOService = nullptr;
75 bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
77 namespace {
79 class BundleHelper {
80 public:
81 NS_INLINE_DECL_REFCOUNTING(BundleHelper)
83 static nsIStringBundle* GetOrCreate() {
84 MOZ_ASSERT(!sShutdown);
86 // Already shutting down. Nothing should require the use of the string
87 // bundle when shutting down.
88 if (sShutdown) {
89 return nullptr;
92 if (!sSelf) {
93 sSelf = new BundleHelper();
96 return sSelf->GetOrCreateInternal();
99 static void Shutdown() {
100 sSelf = nullptr;
101 sShutdown = true;
104 private:
105 ~BundleHelper() = default;
107 nsIStringBundle* GetOrCreateInternal() {
108 if (!mBundle) {
109 nsCOMPtr<nsIStringBundleService> bundleService =
110 mozilla::services::GetStringBundleService();
111 if (NS_WARN_IF(!bundleService)) {
112 return nullptr;
115 nsresult rv = bundleService->CreateBundle(
116 "chrome://global/locale/security/caps.properties",
117 getter_AddRefs(mBundle));
118 if (NS_WARN_IF(NS_FAILED(rv))) {
119 return nullptr;
123 return mBundle;
126 nsCOMPtr<nsIStringBundle> mBundle;
128 static StaticRefPtr<BundleHelper> sSelf;
129 static bool sShutdown;
132 StaticRefPtr<BundleHelper> BundleHelper::sSelf;
133 bool BundleHelper::sShutdown = false;
135 } // namespace
137 ///////////////////////////
138 // Convenience Functions //
139 ///////////////////////////
141 class nsAutoInPrincipalDomainOriginSetter {
142 public:
143 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin; }
144 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin; }
145 static uint32_t sInPrincipalDomainOrigin;
147 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
149 static nsresult GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin) {
150 if (!aURI) {
151 return NS_ERROR_NULL_POINTER;
153 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin > 1) {
154 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
155 // might be happening on a different principal from the first call. But
156 // after that, cut off the recursion; it just indicates that something
157 // we're doing in this method causes us to reenter a security check here.
158 return NS_ERROR_NOT_AVAILABLE;
161 nsAutoInPrincipalDomainOriginSetter autoSetter;
163 nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI);
164 NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
166 nsAutoCString hostPort;
168 nsresult rv = uri->GetHostPort(hostPort);
169 if (NS_SUCCEEDED(rv)) {
170 nsAutoCString scheme;
171 rv = uri->GetScheme(scheme);
172 NS_ENSURE_SUCCESS(rv, rv);
173 aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort;
174 } else {
175 // Some URIs (e.g., nsSimpleURI) don't support host. Just
176 // get the full spec.
177 rv = uri->GetSpec(aOrigin);
178 NS_ENSURE_SUCCESS(rv, rv);
181 return NS_OK;
184 static nsresult GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
185 nsACString& aOrigin) {
186 aOrigin.Truncate();
187 nsCOMPtr<nsIURI> uri;
188 aPrincipal->GetDomain(getter_AddRefs(uri));
189 nsresult rv = GetOriginFromURI(uri, aOrigin);
190 if (NS_SUCCEEDED(rv)) {
191 return rv;
193 // If there is no Domain fallback to the Principals Origin
194 return aPrincipal->GetOriginNoSuffix(aOrigin);
197 inline void SetPendingExceptionASCII(JSContext* cx, const char* aMsg) {
198 JS_ReportErrorASCII(cx, "%s", aMsg);
201 inline void SetPendingException(JSContext* cx, const char16_t* aMsg) {
202 NS_ConvertUTF16toUTF8 msg(aMsg);
203 JS_ReportErrorUTF8(cx, "%s", msg.get());
206 /* static */
207 bool nsScriptSecurityManager::SecurityCompareURIs(nsIURI* aSourceURI,
208 nsIURI* aTargetURI) {
209 return NS_SecurityCompareURIs(aSourceURI, aTargetURI,
210 sStrictFileOriginPolicy);
213 // SecurityHashURI is consistent with SecurityCompareURIs because
214 // NS_SecurityHashURI is consistent with NS_SecurityCompareURIs. See
215 // nsNetUtil.h.
216 uint32_t nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI) {
217 return NS_SecurityHashURI(aURI);
221 * GetChannelResultPrincipal will return the principal that the resource
222 * returned by this channel will use. For example, if the resource is in
223 * a sandbox, it will return the nullprincipal. If the resource is forced
224 * to inherit principal, it will return the principal of its parent. If
225 * the load doesn't require sandboxing or inheriting, it will return the same
226 * principal as GetChannelURIPrincipal. Namely the principal of the URI
227 * that is being loaded.
229 NS_IMETHODIMP
230 nsScriptSecurityManager::GetChannelResultPrincipal(nsIChannel* aChannel,
231 nsIPrincipal** aPrincipal) {
232 return GetChannelResultPrincipal(aChannel, aPrincipal,
233 /*aIgnoreSandboxing*/ false);
236 nsresult nsScriptSecurityManager::GetChannelResultPrincipalIfNotSandboxed(
237 nsIChannel* aChannel, nsIPrincipal** aPrincipal) {
238 return GetChannelResultPrincipal(aChannel, aPrincipal,
239 /*aIgnoreSandboxing*/ true);
242 NS_IMETHODIMP
243 nsScriptSecurityManager::GetChannelResultStoragePrincipal(
244 nsIChannel* aChannel, nsIPrincipal** aPrincipal) {
245 nsCOMPtr<nsIPrincipal> principal;
246 nsresult rv = GetChannelResultPrincipal(aChannel, getter_AddRefs(principal),
247 /*aIgnoreSandboxing*/ false);
248 if (NS_WARN_IF(NS_FAILED(rv))) {
249 return rv;
252 return StoragePrincipalHelper::Create(aChannel, principal, aPrincipal);
255 NS_IMETHODIMP
256 nsScriptSecurityManager::GetChannelResultPrincipals(
257 nsIChannel* aChannel, nsIPrincipal** aPrincipal,
258 nsIPrincipal** aStoragePrincipal) {
259 nsresult rv = GetChannelResultPrincipal(aChannel, aPrincipal,
260 /*aIgnoreSandboxing*/ false);
261 if (NS_WARN_IF(NS_FAILED(rv))) {
262 return rv;
265 if (!(*aPrincipal)->GetIsContentPrincipal()) {
266 // If for some reason we don't have a content principal here, just reuse our
267 // principal for the storage principal too, since attempting to create a
268 // storage principal would fail anyway.
269 nsCOMPtr<nsIPrincipal> copy = *aPrincipal;
270 copy.forget(aStoragePrincipal);
271 return NS_OK;
274 return StoragePrincipalHelper::Create(aChannel, *aPrincipal,
275 aStoragePrincipal);
278 nsresult nsScriptSecurityManager::GetChannelResultPrincipal(
279 nsIChannel* aChannel, nsIPrincipal** aPrincipal, bool aIgnoreSandboxing) {
280 MOZ_ASSERT(aChannel, "Must have channel!");
282 // Check whether we have an nsILoadInfo that says what we should do.
283 nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
284 if (loadInfo->GetForceInheritPrincipalOverruleOwner()) {
285 nsCOMPtr<nsIPrincipal> principalToInherit =
286 loadInfo->FindPrincipalToInherit(aChannel);
287 principalToInherit.forget(aPrincipal);
288 return NS_OK;
291 nsCOMPtr<nsISupports> owner;
292 aChannel->GetOwner(getter_AddRefs(owner));
293 if (owner) {
294 CallQueryInterface(owner, aPrincipal);
295 if (*aPrincipal) {
296 return NS_OK;
300 if (!aIgnoreSandboxing && loadInfo->GetLoadingSandboxed()) {
301 nsCOMPtr<nsIPrincipal> sandboxedLoadingPrincipal =
302 loadInfo->GetSandboxedLoadingPrincipal();
303 MOZ_ASSERT(sandboxedLoadingPrincipal);
304 sandboxedLoadingPrincipal.forget(aPrincipal);
305 return NS_OK;
308 bool forceInherit = loadInfo->GetForceInheritPrincipal();
309 if (aIgnoreSandboxing && !forceInherit) {
310 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
311 // sandboxing:
312 if (loadInfo->GetLoadingSandboxed() &&
313 loadInfo->GetForceInheritPrincipalDropped()) {
314 forceInherit = true;
317 if (forceInherit) {
318 nsCOMPtr<nsIPrincipal> principalToInherit =
319 loadInfo->FindPrincipalToInherit(aChannel);
320 principalToInherit.forget(aPrincipal);
321 return NS_OK;
324 auto securityMode = loadInfo->GetSecurityMode();
325 // The data: inheritance flags should only apply to the initial load,
326 // not to loads that it might have redirected to.
327 if (loadInfo->RedirectChain().IsEmpty() &&
328 (securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS ||
329 securityMode == nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS ||
330 securityMode == nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS)) {
331 nsCOMPtr<nsIURI> uri;
332 nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
333 NS_ENSURE_SUCCESS(rv, rv);
335 nsCOMPtr<nsIPrincipal> principalToInherit =
336 loadInfo->FindPrincipalToInherit(aChannel);
337 bool inheritForAboutBlank = loadInfo->GetAboutBlankInherits();
339 if (nsContentUtils::ChannelShouldInheritPrincipal(
340 principalToInherit, uri, inheritForAboutBlank, false)) {
341 principalToInherit.forget(aPrincipal);
342 return NS_OK;
345 return GetChannelURIPrincipal(aChannel, aPrincipal);
348 /* The principal of the URI that this channel is loading. This is never
349 * affected by things like sandboxed loads, or loads where we forcefully
350 * inherit the principal. Think of this as the principal of the server
351 * which this channel is loading from. Most callers should use
352 * GetChannelResultPrincipal instead of GetChannelURIPrincipal. Only
353 * call GetChannelURIPrincipal if you are sure that you want the
354 * principal that matches the uri, even in cases when the load is
355 * sandboxed or when the load could be a blob or data uri (i.e even when
356 * you encounter loads that may or may not be sandboxed and loads
357 * that may or may not inherit)."
359 NS_IMETHODIMP
360 nsScriptSecurityManager::GetChannelURIPrincipal(nsIChannel* aChannel,
361 nsIPrincipal** aPrincipal) {
362 MOZ_ASSERT(aChannel, "Must have channel!");
364 // Get the principal from the URI. Make sure this does the same thing
365 // as Document::Reset and PrototypeDocumentContentSink::Init.
366 nsCOMPtr<nsIURI> uri;
367 nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
368 NS_ENSURE_SUCCESS(rv, rv);
370 nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
372 // Inherit the origin attributes from loadInfo.
373 // If this is a top-level document load, the origin attributes of the
374 // loadInfo will be set from nsDocShell::DoURILoad.
375 // For subresource loading, the origin attributes of the loadInfo is from
376 // its loadingPrincipal.
377 OriginAttributes attrs = loadInfo->GetOriginAttributes();
379 nsCOMPtr<nsIPrincipal> prin =
380 BasePrincipal::CreateContentPrincipal(uri, attrs);
381 prin.forget(aPrincipal);
382 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
385 /////////////////////////////
386 // nsScriptSecurityManager //
387 /////////////////////////////
389 ////////////////////////////////////
390 // Methods implementing ISupports //
391 ////////////////////////////////////
392 NS_IMPL_ISUPPORTS(nsScriptSecurityManager, nsIScriptSecurityManager)
394 ///////////////////////////////////////////////////
395 // Methods implementing nsIScriptSecurityManager //
396 ///////////////////////////////////////////////////
398 ///////////////// Security Checks /////////////////
400 bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
401 JSContext* cx, JS::HandleString aCode) {
402 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
404 // Get the window, if any, corresponding to the current global
405 nsCOMPtr<nsIContentSecurityPolicy> csp;
406 if (nsGlobalWindowInner* win = xpc::CurrentWindowOrNull(cx)) {
407 csp = win->GetCsp();
410 nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
411 if (!csp) {
412 if (!StaticPrefs::extensions_content_script_csp_enabled()) {
413 return true;
415 // Get the CSP for addon sandboxes. If the principal is expanded and has a
416 // csp, we're probably in luck.
417 auto* basePrin = BasePrincipal::Cast(subjectPrincipal);
418 // ContentScriptAddonPolicy means it is also an expanded principal, thus
419 // this is in a sandbox used as a content script.
420 if (basePrin->ContentScriptAddonPolicy()) {
421 basePrin->As<ExpandedPrincipal>()->GetCsp(getter_AddRefs(csp));
423 // don't do anything unless there's a CSP
424 if (!csp) {
425 return true;
429 nsCOMPtr<nsICSPEventListener> cspEventListener;
430 if (!NS_IsMainThread()) {
431 WorkerPrivate* workerPrivate =
432 mozilla::dom::GetWorkerPrivateFromContext(cx);
433 if (workerPrivate) {
434 cspEventListener = workerPrivate->CSPEventListener();
438 bool evalOK = true;
439 bool reportViolation = false;
440 nsresult rv = csp->GetAllowsEval(&reportViolation, &evalOK);
442 // A little convoluted. We want the scriptSample for a) reporting a violation
443 // or b) passing it to AssertEvalNotUsingSystemPrincipal or c) we're in the
444 // parent process. So do the work to get it if either of those cases is true.
445 nsAutoJSString scriptSample;
446 if (reportViolation || subjectPrincipal->IsSystemPrincipal() ||
447 XRE_IsE10sParentProcess()) {
448 if (NS_WARN_IF(!scriptSample.init(cx, aCode))) {
449 JS_ClearPendingException(cx);
450 return false;
454 #if !defined(ANDROID)
455 if (!nsContentSecurityUtils::IsEvalAllowed(
456 cx, subjectPrincipal->IsSystemPrincipal(), scriptSample)) {
457 return false;
459 #endif
461 if (NS_FAILED(rv)) {
462 NS_WARNING("CSP: failed to get allowsEval");
463 return true; // fail open to not break sites.
466 if (reportViolation) {
467 JS::AutoFilename scriptFilename;
468 nsAutoString fileName;
469 unsigned lineNum = 0;
470 unsigned columnNum = 0;
471 if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum, &columnNum)) {
472 if (const char* file = scriptFilename.get()) {
473 CopyUTF8toUTF16(nsDependentCString(file), fileName);
475 } else {
476 MOZ_ASSERT(!JS_IsExceptionPending(cx));
478 csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
479 nullptr, // triggering element
480 cspEventListener, fileName, scriptSample, lineNum,
481 columnNum, EmptyString(), EmptyString());
484 return evalOK;
487 // static
488 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals* first,
489 JSPrincipals* second) {
490 return nsJSPrincipals::get(first)->Subsumes(nsJSPrincipals::get(second));
493 NS_IMETHODIMP
494 nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
495 nsIURI* aTargetURI,
496 bool reportError,
497 bool aFromPrivateWindow) {
498 // Please note that aFromPrivateWindow is only 100% accurate if
499 // reportError is true.
500 if (!SecurityCompareURIs(aSourceURI, aTargetURI)) {
501 if (reportError) {
502 ReportError("CheckSameOriginError", aSourceURI, aTargetURI,
503 aFromPrivateWindow);
505 return NS_ERROR_DOM_BAD_URI;
507 return NS_OK;
510 NS_IMETHODIMP
511 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext* cx, nsIURI* aURI) {
512 // Get principal of currently executing script.
513 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
514 nsIPrincipal* principal = nsContentUtils::SubjectPrincipal();
515 nsresult rv = CheckLoadURIWithPrincipal(
516 // Passing 0 for the window ID here is OK, because we will report a
517 // script-visible exception anyway.
518 principal, aURI, nsIScriptSecurityManager::STANDARD, 0);
519 if (NS_SUCCEEDED(rv)) {
520 // OK to load
521 return NS_OK;
524 // Report error.
525 nsAutoCString spec;
526 if (NS_FAILED(aURI->GetAsciiSpec(spec))) return NS_ERROR_FAILURE;
527 nsAutoCString msg("Access to '");
528 msg.Append(spec);
529 msg.AppendLiteral("' from script denied");
530 SetPendingExceptionASCII(cx, msg.get());
531 return NS_ERROR_DOM_BAD_URI;
535 * Helper method to handle cases where a flag passed to
536 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
537 * nsIProtocolHandler flags set.
538 * @return if success, access is allowed. Otherwise, deny access
540 static nsresult DenyAccessIfURIHasFlags(nsIURI* aURI, uint32_t aURIFlags) {
541 MOZ_ASSERT(aURI, "Must have URI!");
543 bool uriHasFlags;
544 nsresult rv = NS_URIChainHasFlags(aURI, aURIFlags, &uriHasFlags);
545 NS_ENSURE_SUCCESS(rv, rv);
547 if (uriHasFlags) {
548 return NS_ERROR_DOM_BAD_URI;
551 return NS_OK;
554 static bool EqualOrSubdomain(nsIURI* aProbeArg, nsIURI* aBase) {
555 nsresult rv;
556 nsCOMPtr<nsIURI> probe = aProbeArg;
558 nsCOMPtr<nsIEffectiveTLDService> tldService =
559 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
560 NS_ENSURE_TRUE(tldService, false);
561 while (true) {
562 if (nsScriptSecurityManager::SecurityCompareURIs(probe, aBase)) {
563 return true;
566 nsAutoCString host, newHost;
567 rv = probe->GetHost(host);
568 NS_ENSURE_SUCCESS(rv, false);
570 rv = tldService->GetNextSubDomain(host, newHost);
571 if (rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
572 return false;
574 NS_ENSURE_SUCCESS(rv, false);
575 rv = NS_MutateURI(probe).SetHost(newHost).Finalize(probe);
576 NS_ENSURE_SUCCESS(rv, false);
580 NS_IMETHODIMP
581 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal* aPrincipal,
582 nsIURI* aTargetURI,
583 uint32_t aFlags,
584 uint64_t aInnerWindowID) {
585 MOZ_ASSERT(aPrincipal, "CheckLoadURIWithPrincipal must have a principal");
587 // If someone passes a flag that we don't understand, we should
588 // fail, because they may need a security check that we don't
589 // provide.
590 NS_ENSURE_FALSE(
591 aFlags &
592 ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
593 nsIScriptSecurityManager::ALLOW_CHROME |
594 nsIScriptSecurityManager::DISALLOW_SCRIPT |
595 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL |
596 nsIScriptSecurityManager::DONT_REPORT_ERRORS),
597 NS_ERROR_UNEXPECTED);
598 NS_ENSURE_ARG_POINTER(aPrincipal);
599 NS_ENSURE_ARG_POINTER(aTargetURI);
601 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
602 // would do such inheriting. That would be URIs that do not have their own
603 // security context. We do this even for the system principal.
604 if (aFlags & nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL) {
605 nsresult rv = DenyAccessIfURIHasFlags(
606 aTargetURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT);
607 NS_ENSURE_SUCCESS(rv, rv);
610 if (aPrincipal == mSystemPrincipal) {
611 // Allow access
612 return NS_OK;
615 nsCOMPtr<nsIURI> sourceURI;
616 aPrincipal->GetURI(getter_AddRefs(sourceURI));
617 if (!sourceURI) {
618 auto* basePrin = BasePrincipal::Cast(aPrincipal);
619 if (basePrin->Is<ExpandedPrincipal>()) {
620 auto expanded = basePrin->As<ExpandedPrincipal>();
621 for (auto& prin : expanded->AllowList()) {
622 nsresult rv =
623 CheckLoadURIWithPrincipal(prin, aTargetURI, aFlags, aInnerWindowID);
624 if (NS_SUCCEEDED(rv)) {
625 // Allow access if it succeeded with one of the allowlisted principals
626 return NS_OK;
629 // None of our allowlisted principals worked.
630 return NS_ERROR_DOM_BAD_URI;
632 NS_ERROR(
633 "Non-system principals or expanded principal passed to "
634 "CheckLoadURIWithPrincipal "
635 "must have a URI!");
636 return NS_ERROR_UNEXPECTED;
639 // Automatic loads are not allowed from certain protocols.
640 if (aFlags &
641 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT) {
642 nsresult rv = DenyAccessIfURIHasFlags(
643 sourceURI,
644 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT);
645 NS_ENSURE_SUCCESS(rv, rv);
648 // If either URI is a nested URI, get the base URI
649 nsCOMPtr<nsIURI> sourceBaseURI = NS_GetInnermostURI(sourceURI);
650 nsCOMPtr<nsIURI> targetBaseURI = NS_GetInnermostURI(aTargetURI);
652 //-- get the target scheme
653 nsAutoCString targetScheme;
654 nsresult rv = targetBaseURI->GetScheme(targetScheme);
655 if (NS_FAILED(rv)) return rv;
657 //-- Some callers do not allow loading javascript:
658 if ((aFlags & nsIScriptSecurityManager::DISALLOW_SCRIPT) &&
659 targetScheme.EqualsLiteral("javascript")) {
660 return NS_ERROR_DOM_BAD_URI;
663 // Check for uris that are only loadable by principals that subsume them
664 bool hasFlags;
665 rv = NS_URIChainHasFlags(
666 targetBaseURI, nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS, &hasFlags);
667 NS_ENSURE_SUCCESS(rv, rv);
669 if (hasFlags) {
670 // check nothing else in the URI chain has flags that prevent
671 // access:
672 rv = CheckLoadURIFlags(
673 sourceURI, aTargetURI, sourceBaseURI, targetBaseURI, aFlags,
674 aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0,
675 aInnerWindowID);
676 NS_ENSURE_SUCCESS(rv, rv);
677 // Check the principal is allowed to load the target.
678 if (aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS) {
679 return aPrincipal->CheckMayLoad(targetBaseURI, false);
681 return aPrincipal->CheckMayLoadWithReporting(targetBaseURI, false,
682 aInnerWindowID);
685 //-- get the source scheme
686 nsAutoCString sourceScheme;
687 rv = sourceBaseURI->GetScheme(sourceScheme);
688 if (NS_FAILED(rv)) return rv;
690 if (sourceScheme.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME)) {
691 // A null principal can target its own URI.
692 if (sourceURI == aTargetURI) {
693 return NS_OK;
695 } else if (StaticPrefs::
696 security_view_source_reachable_from_inner_protocol() &&
697 sourceScheme.EqualsIgnoreCase(targetScheme.get()) &&
698 aTargetURI->SchemeIs("view-source")) {
699 // exception for foo: linking to view-source:foo for reftests...
700 return NS_OK;
701 } else if (sourceScheme.EqualsIgnoreCase("file") &&
702 targetScheme.EqualsIgnoreCase("moz-icon")) {
703 // exception for file: linking to moz-icon://.ext?size=...
704 // Note that because targetScheme is the base (innermost) URI scheme,
705 // this does NOT allow file -> moz-icon:file:///... links.
706 // This is intentional.
707 return NS_OK;
710 // Check for webextension
711 rv = NS_URIChainHasFlags(
712 aTargetURI, nsIProtocolHandler::URI_LOADABLE_BY_EXTENSIONS, &hasFlags);
713 NS_ENSURE_SUCCESS(rv, rv);
715 if (hasFlags && BasePrincipal::Cast(aPrincipal)->AddonPolicy()) {
716 return NS_OK;
719 // If we get here, check all the schemes can link to each other, from the top
720 // down:
721 nsCaseInsensitiveCStringComparator stringComparator;
722 nsCOMPtr<nsIURI> currentURI = sourceURI;
723 nsCOMPtr<nsIURI> currentOtherURI = aTargetURI;
725 bool denySameSchemeLinks = false;
726 rv = NS_URIChainHasFlags(aTargetURI,
727 nsIProtocolHandler::URI_SCHEME_NOT_SELF_LINKABLE,
728 &denySameSchemeLinks);
729 if (NS_FAILED(rv)) return rv;
731 while (currentURI && currentOtherURI) {
732 nsAutoCString scheme, otherScheme;
733 currentURI->GetScheme(scheme);
734 currentOtherURI->GetScheme(otherScheme);
736 bool schemesMatch = scheme.Equals(otherScheme, stringComparator);
737 bool isSamePage = false;
738 // about: URIs are special snowflakes.
739 if (scheme.EqualsLiteral("about") && schemesMatch) {
740 nsAutoCString moduleName, otherModuleName;
741 // about: pages can always link to themselves:
742 isSamePage =
743 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI, moduleName)) &&
744 NS_SUCCEEDED(
745 NS_GetAboutModuleName(currentOtherURI, otherModuleName)) &&
746 moduleName.Equals(otherModuleName);
747 if (!isSamePage) {
748 // We will have allowed the load earlier if the source page has
749 // system principal. So we know the source has a content
750 // principal, and it's trying to link to something else.
751 // Linkable about: pages are always reachable, even if we hit
752 // the CheckLoadURIFlags call below.
753 // We punch only 1 other hole: iff the source is unlinkable,
754 // we let them link to other pages explicitly marked SAFE
755 // for content. This avoids world-linkable about: pages linking
756 // to non-world-linkable about: pages.
757 nsCOMPtr<nsIAboutModule> module, otherModule;
758 bool knowBothModules =
759 NS_SUCCEEDED(
760 NS_GetAboutModule(currentURI, getter_AddRefs(module))) &&
761 NS_SUCCEEDED(NS_GetAboutModule(currentOtherURI,
762 getter_AddRefs(otherModule)));
763 uint32_t aboutModuleFlags = 0;
764 uint32_t otherAboutModuleFlags = 0;
765 knowBothModules =
766 knowBothModules &&
767 NS_SUCCEEDED(module->GetURIFlags(currentURI, &aboutModuleFlags)) &&
768 NS_SUCCEEDED(otherModule->GetURIFlags(currentOtherURI,
769 &otherAboutModuleFlags));
770 if (knowBothModules) {
771 isSamePage = !(aboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) &&
772 (otherAboutModuleFlags &
773 nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT);
774 if (isSamePage &&
775 otherAboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) {
776 // XXXgijs: this is a hack. The target will be nested
777 // (with innerURI of moz-safe-about:whatever), and
778 // the source isn't, so we won't pass if we finish
779 // the loop. We *should* pass, though, so return here.
780 // This hack can go away when bug 1228118 is fixed.
781 return NS_OK;
785 } else {
786 bool equalExceptRef = false;
787 rv = currentURI->EqualsExceptRef(currentOtherURI, &equalExceptRef);
788 isSamePage = NS_SUCCEEDED(rv) && equalExceptRef;
791 // If schemes are not equal, or they're equal but the target URI
792 // is different from the source URI and doesn't always allow linking
793 // from the same scheme, check if the URI flags of the current target
794 // URI allow the current source URI to link to it.
795 // The policy is specified by the protocol flags on both URIs.
796 if (!schemesMatch || (denySameSchemeLinks && !isSamePage)) {
797 return CheckLoadURIFlags(
798 currentURI, currentOtherURI, sourceBaseURI, targetBaseURI, aFlags,
799 aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0,
800 aInnerWindowID);
802 // Otherwise... check if we can nest another level:
803 nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(currentURI);
804 nsCOMPtr<nsINestedURI> nestedOtherURI = do_QueryInterface(currentOtherURI);
806 // If schemes match and neither URI is nested further, we're OK.
807 if (!nestedURI && !nestedOtherURI) {
808 return NS_OK;
810 // If one is nested and the other isn't, something is wrong.
811 if (!nestedURI != !nestedOtherURI) {
812 return NS_ERROR_DOM_BAD_URI;
814 // Otherwise, both should be nested and we'll go through the loop again.
815 nestedURI->GetInnerURI(getter_AddRefs(currentURI));
816 nestedOtherURI->GetInnerURI(getter_AddRefs(currentOtherURI));
819 // We should never get here. We should always return from inside the loop.
820 return NS_ERROR_DOM_BAD_URI;
824 * Helper method to check whether the target URI and its innermost ("base") URI
825 * has protocol flags that should stop it from being loaded by the source URI
826 * (and/or the source URI's innermost ("base") URI), taking into account any
827 * nsIScriptSecurityManager flags originally passed to
828 * CheckLoadURIWithPrincipal and friends.
830 * @return if success, access is allowed. Otherwise, deny access
832 nsresult nsScriptSecurityManager::CheckLoadURIFlags(
833 nsIURI* aSourceURI, nsIURI* aTargetURI, nsIURI* aSourceBaseURI,
834 nsIURI* aTargetBaseURI, uint32_t aFlags, bool aFromPrivateWindow,
835 uint64_t aInnerWindowID) {
836 // Note that the order of policy checks here is very important!
837 // We start from most restrictive and work our way down.
838 bool reportErrors = !(aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS);
839 const char* errorTag = "CheckLoadURIError";
841 nsAutoCString targetScheme;
842 nsresult rv = aTargetBaseURI->GetScheme(targetScheme);
843 if (NS_FAILED(rv)) return rv;
845 // Check for system target URI
846 rv = DenyAccessIfURIHasFlags(aTargetURI,
847 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD);
848 if (NS_FAILED(rv)) {
849 // Deny access, since the origin principal is not system
850 if (reportErrors) {
851 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
852 aInnerWindowID);
854 return rv;
857 // Used by ExtensionProtocolHandler to prevent loading extension resources
858 // in private contexts if the extension does not have permission.
859 if (aFromPrivateWindow) {
860 rv = DenyAccessIfURIHasFlags(
861 aTargetURI, nsIProtocolHandler::URI_DISALLOW_IN_PRIVATE_CONTEXT);
862 if (NS_FAILED(rv)) {
863 if (reportErrors) {
864 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
865 aInnerWindowID);
867 return rv;
871 // Check for chrome target URI
872 bool hasFlags = false;
873 rv = NS_URIChainHasFlags(aTargetURI, nsIProtocolHandler::URI_IS_UI_RESOURCE,
874 &hasFlags);
875 NS_ENSURE_SUCCESS(rv, rv);
876 if (hasFlags) {
877 if (aFlags & nsIScriptSecurityManager::ALLOW_CHROME) {
878 // Allow a URI_IS_UI_RESOURCE source to link to a URI_IS_UI_RESOURCE
879 // target if ALLOW_CHROME is set.
881 // ALLOW_CHROME is a flag that we pass on all loads _except_ docshell
882 // loads (since docshell loads run the loaded content with its origin
883 // principal). So we're effectively allowing resource://, chrome://,
884 // and moz-icon:// source URIs to load resource://, chrome://, and
885 // moz-icon:// files, so long as they're not loading it as a document.
886 bool sourceIsUIResource;
887 rv = NS_URIChainHasFlags(aSourceBaseURI,
888 nsIProtocolHandler::URI_IS_UI_RESOURCE,
889 &sourceIsUIResource);
890 NS_ENSURE_SUCCESS(rv, rv);
891 if (sourceIsUIResource) {
892 return NS_OK;
895 if (targetScheme.EqualsLiteral("resource")) {
896 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
897 return NS_OK;
900 nsCOMPtr<nsIProtocolHandler> ph;
901 rv = sIOService->GetProtocolHandler("resource", getter_AddRefs(ph));
902 NS_ENSURE_SUCCESS(rv, rv);
903 if (!ph) {
904 return NS_ERROR_DOM_BAD_URI;
907 nsCOMPtr<nsIResProtocolHandler> rph = do_QueryInterface(ph);
908 if (!rph) {
909 return NS_ERROR_DOM_BAD_URI;
912 bool accessAllowed = false;
913 rph->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
914 if (accessAllowed) {
915 return NS_OK;
917 } else if (targetScheme.EqualsLiteral("chrome")) {
918 // Allow the load only if the chrome package is allowlisted.
919 nsCOMPtr<nsIXULChromeRegistry> reg(
920 do_GetService(NS_CHROMEREGISTRY_CONTRACTID));
921 if (reg) {
922 bool accessAllowed = false;
923 reg->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
924 if (accessAllowed) {
925 return NS_OK;
931 if (reportErrors) {
932 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
933 aInnerWindowID);
935 return NS_ERROR_DOM_BAD_URI;
938 // Check for target URI pointing to a file
939 rv = NS_URIChainHasFlags(aTargetURI, nsIProtocolHandler::URI_IS_LOCAL_FILE,
940 &hasFlags);
941 NS_ENSURE_SUCCESS(rv, rv);
942 if (hasFlags) {
943 // Allow domains that were allowlisted in the prefs. In 99.9% of cases,
944 // this array is empty.
945 bool isAllowlisted;
946 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI, &isAllowlisted));
947 if (isAllowlisted) {
948 return NS_OK;
951 // Allow chrome://
952 if (aSourceBaseURI->SchemeIs("chrome")) {
953 return NS_OK;
956 // Nothing else.
957 if (reportErrors) {
958 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
959 aInnerWindowID);
961 return NS_ERROR_DOM_BAD_URI;
964 #ifdef DEBUG
966 // Everyone is allowed to load this. The case URI_LOADABLE_BY_SUBSUMERS
967 // is handled by the caller which is just delegating to us as a helper.
968 bool hasSubsumersFlag = false;
969 NS_URIChainHasFlags(aTargetBaseURI,
970 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS,
971 &hasSubsumersFlag);
972 bool hasLoadableByAnyone = false;
973 NS_URIChainHasFlags(aTargetBaseURI,
974 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE,
975 &hasLoadableByAnyone);
976 MOZ_ASSERT(hasLoadableByAnyone || hasSubsumersFlag,
977 "why do we get here and do not have any of the two flags set?");
979 #endif
981 return NS_OK;
984 nsresult nsScriptSecurityManager::ReportError(const char* aMessageTag,
985 const nsACString& aSourceSpec,
986 const nsACString& aTargetSpec,
987 bool aFromPrivateWindow,
988 uint64_t aInnerWindowID) {
989 if (aSourceSpec.IsEmpty() || aTargetSpec.IsEmpty()) {
990 return NS_OK;
993 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
994 if (NS_WARN_IF(!bundle)) {
995 return NS_OK;
998 // Localize the error message
999 nsAutoString message;
1000 AutoTArray<nsString, 2> formatStrings;
1001 CopyASCIItoUTF16(aSourceSpec, *formatStrings.AppendElement());
1002 CopyASCIItoUTF16(aTargetSpec, *formatStrings.AppendElement());
1003 nsresult rv =
1004 bundle->FormatStringFromName(aMessageTag, formatStrings, message);
1005 NS_ENSURE_SUCCESS(rv, rv);
1007 nsCOMPtr<nsIConsoleService> console(
1008 do_GetService(NS_CONSOLESERVICE_CONTRACTID));
1009 NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
1010 nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
1011 NS_ENSURE_TRUE(error, NS_ERROR_FAILURE);
1013 // using category of "SOP" so we can link to MDN
1014 if (aInnerWindowID != 0) {
1015 rv = error->InitWithWindowID(message, EmptyString(), EmptyString(), 0, 0,
1016 nsIScriptError::errorFlag,
1017 NS_LITERAL_CSTRING("SOP"), aInnerWindowID,
1018 true /* From chrome context */);
1019 } else {
1020 rv = error->Init(message, EmptyString(), EmptyString(), 0, 0,
1021 nsIScriptError::errorFlag, "SOP", aFromPrivateWindow,
1022 true /* From chrome context */);
1024 NS_ENSURE_SUCCESS(rv, rv);
1025 console->LogMessage(error);
1026 return NS_OK;
1029 nsresult nsScriptSecurityManager::ReportError(const char* aMessageTag,
1030 nsIURI* aSource, nsIURI* aTarget,
1031 bool aFromPrivateWindow,
1032 uint64_t aInnerWindowID) {
1033 NS_ENSURE_TRUE(aSource && aTarget, NS_ERROR_NULL_POINTER);
1035 // Get the source URL spec
1036 nsAutoCString sourceSpec;
1037 nsresult rv = aSource->GetAsciiSpec(sourceSpec);
1038 NS_ENSURE_SUCCESS(rv, rv);
1040 // Get the target URL spec
1041 nsAutoCString targetSpec;
1042 rv = aTarget->GetAsciiSpec(targetSpec);
1043 NS_ENSURE_SUCCESS(rv, rv);
1045 return ReportError(aMessageTag, sourceSpec, targetSpec, aFromPrivateWindow,
1046 aInnerWindowID);
1049 NS_IMETHODIMP
1050 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1051 nsIPrincipal* aPrincipal, const nsACString& aTargetURIStr,
1052 uint32_t aFlags) {
1053 nsresult rv;
1054 nsCOMPtr<nsIURI> target;
1055 rv = NS_NewURI(getter_AddRefs(target), aTargetURIStr);
1056 NS_ENSURE_SUCCESS(rv, rv);
1058 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags, 0);
1059 if (rv == NS_ERROR_DOM_BAD_URI) {
1060 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1061 // return values.
1062 return rv;
1064 NS_ENSURE_SUCCESS(rv, rv);
1066 // Now start testing fixup -- since aTargetURIStr is a string, not
1067 // an nsIURI, we may well end up fixing it up before loading.
1068 // Note: This needs to stay in sync with the nsIURIFixup api.
1069 nsCOMPtr<nsIURIFixup> fixup = components::URIFixup::Service();
1070 if (!fixup) {
1071 return rv;
1074 uint32_t flags[] = {nsIURIFixup::FIXUP_FLAG_NONE,
1075 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS,
1076 nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP,
1077 nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI,
1078 nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP |
1079 nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI};
1081 for (uint32_t i = 0; i < ArrayLength(flags); ++i) {
1082 uint32_t fixupFlags = flags[i];
1083 if (aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0) {
1084 fixupFlags |= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT;
1086 rv = fixup->CreateFixupURI(aTargetURIStr, fixupFlags, nullptr,
1087 getter_AddRefs(target));
1088 NS_ENSURE_SUCCESS(rv, rv);
1090 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags, 0);
1091 if (rv == NS_ERROR_DOM_BAD_URI) {
1092 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1093 // return values.
1094 return rv;
1096 NS_ENSURE_SUCCESS(rv, rv);
1099 return rv;
1102 NS_IMETHODIMP
1103 nsScriptSecurityManager::InFileURIAllowlist(nsIURI* aUri, bool* aResult) {
1104 MOZ_ASSERT(aUri);
1105 MOZ_ASSERT(aResult);
1107 *aResult = false;
1108 for (nsIURI* uri : EnsureFileURIAllowlist()) {
1109 if (EqualOrSubdomain(aUri, uri)) {
1110 *aResult = true;
1111 return NS_OK;
1115 return NS_OK;
1118 ///////////////// Principals ///////////////////////
1120 NS_IMETHODIMP
1121 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal** result) {
1122 NS_ADDREF(*result = mSystemPrincipal);
1124 return NS_OK;
1127 NS_IMETHODIMP
1128 nsScriptSecurityManager::CreateContentPrincipal(
1129 nsIURI* aURI, JS::Handle<JS::Value> aOriginAttributes, JSContext* aCx,
1130 nsIPrincipal** aPrincipal) {
1131 OriginAttributes attrs;
1132 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1133 return NS_ERROR_INVALID_ARG;
1135 nsCOMPtr<nsIPrincipal> prin =
1136 BasePrincipal::CreateContentPrincipal(aURI, attrs);
1137 prin.forget(aPrincipal);
1138 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1141 NS_IMETHODIMP
1142 nsScriptSecurityManager::CreateContentPrincipalFromOrigin(
1143 const nsACString& aOrigin, nsIPrincipal** aPrincipal) {
1144 if (StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("["))) {
1145 return NS_ERROR_INVALID_ARG;
1148 if (StringBeginsWith(aOrigin,
1149 NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":"))) {
1150 return NS_ERROR_INVALID_ARG;
1153 nsCOMPtr<nsIPrincipal> prin = BasePrincipal::CreateContentPrincipal(aOrigin);
1154 prin.forget(aPrincipal);
1155 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1158 NS_IMETHODIMP
1159 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal* aPrincipal,
1160 nsACString& aJSON) {
1161 aJSON.Truncate();
1162 if (!aPrincipal) {
1163 return NS_ERROR_FAILURE;
1166 BasePrincipal::Cast(aPrincipal)->ToJSON(aJSON);
1168 if (aJSON.IsEmpty()) {
1169 return NS_ERROR_FAILURE;
1172 return NS_OK;
1175 NS_IMETHODIMP
1176 nsScriptSecurityManager::JSONToPrincipal(const nsACString& aJSON,
1177 nsIPrincipal** aPrincipal) {
1178 if (aJSON.IsEmpty()) {
1179 return NS_ERROR_FAILURE;
1182 nsCOMPtr<nsIPrincipal> principal = BasePrincipal::FromJSON(aJSON);
1184 if (!principal) {
1185 return NS_ERROR_FAILURE;
1188 principal.forget(aPrincipal);
1189 return NS_OK;
1192 NS_IMETHODIMP
1193 nsScriptSecurityManager::CreateNullPrincipal(
1194 JS::Handle<JS::Value> aOriginAttributes, JSContext* aCx,
1195 nsIPrincipal** aPrincipal) {
1196 OriginAttributes attrs;
1197 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1198 return NS_ERROR_INVALID_ARG;
1200 nsCOMPtr<nsIPrincipal> prin = NullPrincipal::Create(attrs);
1201 prin.forget(aPrincipal);
1202 return NS_OK;
1205 NS_IMETHODIMP
1206 nsScriptSecurityManager::GetLoadContextContentPrincipal(
1207 nsIURI* aURI, nsILoadContext* aLoadContext, nsIPrincipal** aPrincipal) {
1208 NS_ENSURE_STATE(aLoadContext);
1209 OriginAttributes docShellAttrs;
1210 aLoadContext->GetOriginAttributes(docShellAttrs);
1212 nsCOMPtr<nsIPrincipal> prin =
1213 BasePrincipal::CreateContentPrincipal(aURI, docShellAttrs);
1214 prin.forget(aPrincipal);
1215 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1218 NS_IMETHODIMP
1219 nsScriptSecurityManager::GetDocShellContentPrincipal(
1220 nsIURI* aURI, nsIDocShell* aDocShell, nsIPrincipal** aPrincipal) {
1221 nsCOMPtr<nsIPrincipal> prin = BasePrincipal::CreateContentPrincipal(
1222 aURI, nsDocShell::Cast(aDocShell)->GetOriginAttributes());
1223 prin.forget(aPrincipal);
1224 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1227 NS_IMETHODIMP
1228 nsScriptSecurityManager::PrincipalWithOA(
1229 nsIPrincipal* aPrincipal, JS::Handle<JS::Value> aOriginAttributes,
1230 JSContext* aCx, nsIPrincipal** aReturnPrincipal) {
1231 if (!aPrincipal) {
1232 return NS_OK;
1234 if (aPrincipal->GetIsContentPrincipal()) {
1235 OriginAttributes attrs;
1236 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1237 return NS_ERROR_INVALID_ARG;
1239 RefPtr<ContentPrincipal> copy = new ContentPrincipal();
1240 auto* contentPrincipal = static_cast<ContentPrincipal*>(aPrincipal);
1241 nsresult rv = copy->Init(contentPrincipal, attrs);
1242 NS_ENSURE_SUCCESS(rv, rv);
1243 copy.forget(aReturnPrincipal);
1244 } else {
1245 // We do this for null principals, system principals (both fine)
1246 // ... and expanded principals, where we should probably do something
1247 // cleverer, but I also don't think we care too much.
1248 nsCOMPtr<nsIPrincipal> prin = aPrincipal;
1249 prin.forget(aReturnPrincipal);
1252 return *aReturnPrincipal ? NS_OK : NS_ERROR_FAILURE;
1255 NS_IMETHODIMP
1256 nsScriptSecurityManager::CanCreateWrapper(JSContext* cx, const nsIID& aIID,
1257 nsISupports* aObj,
1258 nsIClassInfo* aClassInfo) {
1259 // XXX Special case for Exception ?
1261 // We give remote-XUL allowlisted domains a free pass here. See bug 932906.
1262 JS::Rooted<JS::Realm*> contextRealm(cx, JS::GetCurrentRealmOrNull(cx));
1263 MOZ_RELEASE_ASSERT(contextRealm);
1264 if (!xpc::AllowContentXBLScope(contextRealm)) {
1265 return NS_OK;
1268 if (nsContentUtils::IsCallerChrome()) {
1269 return NS_OK;
1272 //-- Access denied, report an error
1273 nsAutoCString originUTF8;
1274 nsIPrincipal* subjectPrincipal = nsContentUtils::SubjectPrincipal();
1275 GetPrincipalDomainOrigin(subjectPrincipal, originUTF8);
1276 NS_ConvertUTF8toUTF16 originUTF16(originUTF8);
1277 nsAutoCString classInfoNameUTF8;
1278 if (aClassInfo) {
1279 aClassInfo->GetClassDescription(classInfoNameUTF8);
1281 if (classInfoNameUTF8.IsEmpty()) {
1282 classInfoNameUTF8.AssignLiteral("UnnamedClass");
1285 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
1286 if (NS_WARN_IF(!bundle)) {
1287 return NS_OK;
1290 NS_ConvertUTF8toUTF16 classInfoUTF16(classInfoNameUTF8);
1291 nsresult rv;
1292 nsAutoString errorMsg;
1293 if (originUTF16.IsEmpty()) {
1294 AutoTArray<nsString, 1> formatStrings = {classInfoUTF16};
1295 rv = bundle->FormatStringFromName("CreateWrapperDenied", formatStrings,
1296 errorMsg);
1297 } else {
1298 AutoTArray<nsString, 2> formatStrings = {classInfoUTF16, originUTF16};
1299 rv = bundle->FormatStringFromName("CreateWrapperDeniedForOrigin",
1300 formatStrings, errorMsg);
1302 NS_ENSURE_SUCCESS(rv, rv);
1304 SetPendingException(cx, errorMsg.get());
1305 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1308 NS_IMETHODIMP
1309 nsScriptSecurityManager::CanCreateInstance(JSContext* cx, const nsCID& aCID) {
1310 if (nsContentUtils::IsCallerChrome()) {
1311 return NS_OK;
1314 //-- Access denied, report an error
1315 nsAutoCString errorMsg("Permission denied to create instance of class. CID=");
1316 char cidStr[NSID_LENGTH];
1317 aCID.ToProvidedString(cidStr);
1318 errorMsg.Append(cidStr);
1319 SetPendingExceptionASCII(cx, errorMsg.get());
1320 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1323 NS_IMETHODIMP
1324 nsScriptSecurityManager::CanGetService(JSContext* cx, const nsCID& aCID) {
1325 if (nsContentUtils::IsCallerChrome()) {
1326 return NS_OK;
1329 //-- Access denied, report an error
1330 nsAutoCString errorMsg("Permission denied to get service. CID=");
1331 char cidStr[NSID_LENGTH];
1332 aCID.ToProvidedString(cidStr);
1333 errorMsg.Append(cidStr);
1334 SetPendingExceptionASCII(cx, errorMsg.get());
1335 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1338 const char sJSEnabledPrefName[] = "javascript.enabled";
1339 const char sFileOriginPolicyPrefName[] =
1340 "security.fileuri.strict_origin_policy";
1342 static const char* kObservedPrefs[] = {sJSEnabledPrefName,
1343 sFileOriginPolicyPrefName,
1344 "capability.policy.", nullptr};
1346 /////////////////////////////////////////////
1347 // Constructor, Destructor, Initialization //
1348 /////////////////////////////////////////////
1349 nsScriptSecurityManager::nsScriptSecurityManager(void)
1350 : mPrefInitialized(false), mIsJavaScriptEnabled(false) {
1351 static_assert(
1352 sizeof(intptr_t) == sizeof(void*),
1353 "intptr_t and void* have different lengths on this platform. "
1354 "This may cause a security failure with the SecurityLevel union.");
1357 nsresult nsScriptSecurityManager::Init() {
1358 nsresult rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
1359 NS_ENSURE_SUCCESS(rv, rv);
1361 InitPrefs();
1363 // Create our system principal singleton
1364 RefPtr<SystemPrincipal> system = SystemPrincipal::Create();
1366 mSystemPrincipal = system;
1368 return NS_OK;
1371 void nsScriptSecurityManager::InitJSCallbacks(JSContext* aCx) {
1372 //-- Register security check callback in the JS engine
1373 // Currently this is used to control access to function.caller
1375 static const JSSecurityCallbacks securityCallbacks = {
1376 ContentSecurityPolicyPermitsJSAction,
1377 JSPrincipalsSubsume,
1380 MOZ_ASSERT(!JS_GetSecurityCallbacks(aCx));
1381 JS_SetSecurityCallbacks(aCx, &securityCallbacks);
1382 JS_InitDestroyPrincipalsCallback(aCx, nsJSPrincipals::Destroy);
1384 JS_SetTrustedPrincipals(aCx, BasePrincipal::Cast(mSystemPrincipal));
1387 /* static */
1388 void nsScriptSecurityManager::ClearJSCallbacks(JSContext* aCx) {
1389 JS_SetSecurityCallbacks(aCx, nullptr);
1390 JS_SetTrustedPrincipals(aCx, nullptr);
1393 static StaticRefPtr<nsScriptSecurityManager> gScriptSecMan;
1395 nsScriptSecurityManager::~nsScriptSecurityManager(void) {
1396 Preferences::UnregisterPrefixCallbacks(
1397 nsScriptSecurityManager::ScriptSecurityPrefChanged, kObservedPrefs, this);
1398 if (mDomainPolicy) {
1399 mDomainPolicy->Deactivate();
1401 // ContentChild might hold a reference to the domain policy,
1402 // and it might release it only after the security manager is
1403 // gone. But we can still assert this for the main process.
1404 MOZ_ASSERT_IF(XRE_IsParentProcess(), !mDomainPolicy);
1407 void nsScriptSecurityManager::Shutdown() {
1408 NS_IF_RELEASE(sIOService);
1409 BundleHelper::Shutdown();
1412 nsScriptSecurityManager* nsScriptSecurityManager::GetScriptSecurityManager() {
1413 return gScriptSecMan;
1416 /* static */
1417 void nsScriptSecurityManager::InitStatics() {
1418 RefPtr<nsScriptSecurityManager> ssManager = new nsScriptSecurityManager();
1419 nsresult rv = ssManager->Init();
1420 if (NS_FAILED(rv)) {
1421 MOZ_CRASH("ssManager->Init() failed");
1424 ClearOnShutdown(&gScriptSecMan);
1425 gScriptSecMan = ssManager;
1428 // Currently this nsGenericFactory constructor is used only from FastLoad
1429 // (XPCOM object deserialization) code, when "creating" the system principal
1430 // singleton.
1431 already_AddRefed<SystemPrincipal>
1432 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1433 if (gScriptSecMan)
1434 return do_AddRef(gScriptSecMan->mSystemPrincipal)
1435 .downcast<SystemPrincipal>();
1436 return nullptr;
1439 struct IsWhitespace {
1440 static bool Test(char aChar) { return NS_IsAsciiWhitespace(aChar); };
1442 struct IsWhitespaceOrComma {
1443 static bool Test(char aChar) {
1444 return aChar == ',' || NS_IsAsciiWhitespace(aChar);
1448 template <typename Predicate>
1449 uint32_t SkipPast(const nsCString& str, uint32_t base) {
1450 while (base < str.Length() && Predicate::Test(str[base])) {
1451 ++base;
1453 return base;
1456 template <typename Predicate>
1457 uint32_t SkipUntil(const nsCString& str, uint32_t base) {
1458 while (base < str.Length() && !Predicate::Test(str[base])) {
1459 ++base;
1461 return base;
1464 // static
1465 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref,
1466 void* aSelf) {
1467 static_cast<nsScriptSecurityManager*>(aSelf)->ScriptSecurityPrefChanged(
1468 aPref);
1471 inline void nsScriptSecurityManager::ScriptSecurityPrefChanged(
1472 const char* aPref) {
1473 MOZ_ASSERT(mPrefInitialized);
1474 mIsJavaScriptEnabled =
1475 Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled);
1476 sStrictFileOriginPolicy =
1477 Preferences::GetBool(sFileOriginPolicyPrefName, false);
1478 mFileURIAllowlist.reset();
1481 void nsScriptSecurityManager::AddSitesToFileURIAllowlist(
1482 const nsCString& aSiteList) {
1483 for (uint32_t base = SkipPast<IsWhitespace>(aSiteList, 0), bound = 0;
1484 base < aSiteList.Length();
1485 base = SkipPast<IsWhitespace>(aSiteList, bound)) {
1486 // Grab the current site.
1487 bound = SkipUntil<IsWhitespace>(aSiteList, base);
1488 nsAutoCString site(Substring(aSiteList, base, bound - base));
1490 // Check if the URI is schemeless. If so, add both http and https.
1491 nsAutoCString unused;
1492 if (NS_FAILED(sIOService->ExtractScheme(site, unused))) {
1493 AddSitesToFileURIAllowlist(NS_LITERAL_CSTRING("http://") + site);
1494 AddSitesToFileURIAllowlist(NS_LITERAL_CSTRING("https://") + site);
1495 continue;
1498 // Convert it to a URI and add it to our list.
1499 nsCOMPtr<nsIURI> uri;
1500 nsresult rv = NS_NewURI(getter_AddRefs(uri), site);
1501 if (NS_SUCCEEDED(rv)) {
1502 mFileURIAllowlist.ref().AppendElement(uri);
1503 } else {
1504 nsCOMPtr<nsIConsoleService> console(
1505 do_GetService("@mozilla.org/consoleservice;1"));
1506 if (console) {
1507 nsAutoString msg =
1508 NS_LITERAL_STRING(
1509 "Unable to to add site to file:// URI allowlist: ") +
1510 NS_ConvertASCIItoUTF16(site);
1511 console->LogStringMessage(msg.get());
1517 nsresult nsScriptSecurityManager::InitPrefs() {
1518 nsIPrefBranch* branch = Preferences::GetRootBranch();
1519 NS_ENSURE_TRUE(branch, NS_ERROR_FAILURE);
1521 mPrefInitialized = true;
1523 // Set the initial value of the "javascript.enabled" prefs
1524 ScriptSecurityPrefChanged();
1526 // set observer callbacks in case the value of the prefs change
1527 Preferences::RegisterPrefixCallbacks(
1528 nsScriptSecurityManager::ScriptSecurityPrefChanged, kObservedPrefs, this);
1530 return NS_OK;
1533 NS_IMETHODIMP
1534 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv) {
1535 *aRv = !!mDomainPolicy;
1536 return NS_OK;
1539 NS_IMETHODIMP
1540 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy** aRv) {
1541 if (!XRE_IsParentProcess()) {
1542 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1545 return ActivateDomainPolicyInternal(aRv);
1548 NS_IMETHODIMP
1549 nsScriptSecurityManager::ActivateDomainPolicyInternal(nsIDomainPolicy** aRv) {
1550 // We only allow one domain policy at a time. The holder of the previous
1551 // policy must explicitly deactivate it first.
1552 if (mDomainPolicy) {
1553 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1556 mDomainPolicy = new DomainPolicy();
1557 nsCOMPtr<nsIDomainPolicy> ptr = mDomainPolicy;
1558 ptr.forget(aRv);
1559 return NS_OK;
1562 // Intentionally non-scriptable. Script must have a reference to the
1563 // nsIDomainPolicy to deactivate it.
1564 void nsScriptSecurityManager::DeactivateDomainPolicy() {
1565 mDomainPolicy = nullptr;
1568 void nsScriptSecurityManager::CloneDomainPolicy(DomainPolicyClone* aClone) {
1569 MOZ_ASSERT(aClone);
1570 if (mDomainPolicy) {
1571 mDomainPolicy->CloneDomainPolicy(aClone);
1572 } else {
1573 aClone->active() = false;
1577 NS_IMETHODIMP
1578 nsScriptSecurityManager::PolicyAllowsScript(nsIURI* aURI, bool* aRv) {
1579 nsresult rv;
1581 // Compute our rule. If we don't have any domain policy set up that might
1582 // provide exceptions to this rule, we're done.
1583 *aRv = mIsJavaScriptEnabled;
1584 if (!mDomainPolicy) {
1585 return NS_OK;
1588 // We have a domain policy. Grab the appropriate set of exceptions to the
1589 // rule (either the blocklist or the allowlist, depending on whether script
1590 // is enabled or disabled by default).
1591 nsCOMPtr<nsIDomainSet> exceptions;
1592 nsCOMPtr<nsIDomainSet> superExceptions;
1593 if (*aRv) {
1594 mDomainPolicy->GetBlocklist(getter_AddRefs(exceptions));
1595 mDomainPolicy->GetSuperBlocklist(getter_AddRefs(superExceptions));
1596 } else {
1597 mDomainPolicy->GetAllowlist(getter_AddRefs(exceptions));
1598 mDomainPolicy->GetSuperAllowlist(getter_AddRefs(superExceptions));
1601 bool contains;
1602 rv = exceptions->Contains(aURI, &contains);
1603 NS_ENSURE_SUCCESS(rv, rv);
1604 if (contains) {
1605 *aRv = !*aRv;
1606 return NS_OK;
1608 rv = superExceptions->ContainsSuperDomain(aURI, &contains);
1609 NS_ENSURE_SUCCESS(rv, rv);
1610 if (contains) {
1611 *aRv = !*aRv;
1614 return NS_OK;
1617 const nsTArray<nsCOMPtr<nsIURI>>&
1618 nsScriptSecurityManager::EnsureFileURIAllowlist() {
1619 if (mFileURIAllowlist.isSome()) {
1620 return mFileURIAllowlist.ref();
1624 // Rebuild the set of principals for which we allow file:// URI loads. This
1625 // implements a small subset of an old pref-based CAPS people that people
1626 // have come to depend on. See bug 995943.
1629 mFileURIAllowlist.emplace();
1630 nsAutoCString policies;
1631 mozilla::Preferences::GetCString("capability.policy.policynames", policies);
1632 for (uint32_t base = SkipPast<IsWhitespaceOrComma>(policies, 0), bound = 0;
1633 base < policies.Length();
1634 base = SkipPast<IsWhitespaceOrComma>(policies, bound)) {
1635 // Grab the current policy name.
1636 bound = SkipUntil<IsWhitespaceOrComma>(policies, base);
1637 auto policyName = Substring(policies, base, bound - base);
1639 // Figure out if this policy allows loading file:// URIs. If not, we can
1640 // skip it.
1641 nsCString checkLoadURIPrefName =
1642 NS_LITERAL_CSTRING("capability.policy.") + policyName +
1643 NS_LITERAL_CSTRING(".checkloaduri.enabled");
1644 nsAutoString value;
1645 nsresult rv = Preferences::GetString(checkLoadURIPrefName.get(), value);
1646 if (NS_FAILED(rv) || !value.LowerCaseEqualsLiteral("allaccess")) {
1647 continue;
1650 // Grab the list of domains associated with this policy.
1651 nsCString domainPrefName = NS_LITERAL_CSTRING("capability.policy.") +
1652 policyName + NS_LITERAL_CSTRING(".sites");
1653 nsAutoCString siteList;
1654 Preferences::GetCString(domainPrefName.get(), siteList);
1655 AddSitesToFileURIAllowlist(siteList);
1658 return mFileURIAllowlist.ref();