Bug 1647875 [wpt PR 24320] - [AspectRatio] Add an in-flow test for computing a block...
[gecko.git] / caps / nsScriptSecurityManager.cpp
blob99742118c8ee2c0d6e93033306580797bac60ec3
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/nsCSPContext.h"
61 #include "mozilla/dom/ScriptSettings.h"
62 #include "mozilla/ClearOnShutdown.h"
63 #include "mozilla/StaticPtr.h"
64 #include "mozilla/dom/WorkerCommon.h"
65 #include "mozilla/dom/WorkerPrivate.h"
66 #include "nsContentUtils.h"
67 #include "nsJSUtils.h"
68 #include "nsILoadInfo.h"
70 // This should be probably defined on some other place... but I couldn't find it
71 #define WEBAPPS_PERM_NAME "webapps-manage"
73 using namespace mozilla;
74 using namespace mozilla::dom;
76 nsIIOService* nsScriptSecurityManager::sIOService = nullptr;
77 bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
79 namespace {
81 class BundleHelper {
82 public:
83 NS_INLINE_DECL_REFCOUNTING(BundleHelper)
85 static nsIStringBundle* GetOrCreate() {
86 MOZ_ASSERT(!sShutdown);
88 // Already shutting down. Nothing should require the use of the string
89 // bundle when shutting down.
90 if (sShutdown) {
91 return nullptr;
94 if (!sSelf) {
95 sSelf = new BundleHelper();
98 return sSelf->GetOrCreateInternal();
101 static void Shutdown() {
102 sSelf = nullptr;
103 sShutdown = true;
106 private:
107 ~BundleHelper() = default;
109 nsIStringBundle* GetOrCreateInternal() {
110 if (!mBundle) {
111 nsCOMPtr<nsIStringBundleService> bundleService =
112 mozilla::services::GetStringBundleService();
113 if (NS_WARN_IF(!bundleService)) {
114 return nullptr;
117 nsresult rv = bundleService->CreateBundle(
118 "chrome://global/locale/security/caps.properties",
119 getter_AddRefs(mBundle));
120 if (NS_WARN_IF(NS_FAILED(rv))) {
121 return nullptr;
125 return mBundle;
128 nsCOMPtr<nsIStringBundle> mBundle;
130 static StaticRefPtr<BundleHelper> sSelf;
131 static bool sShutdown;
134 StaticRefPtr<BundleHelper> BundleHelper::sSelf;
135 bool BundleHelper::sShutdown = false;
137 } // namespace
139 ///////////////////////////
140 // Convenience Functions //
141 ///////////////////////////
143 class nsAutoInPrincipalDomainOriginSetter {
144 public:
145 nsAutoInPrincipalDomainOriginSetter() { ++sInPrincipalDomainOrigin; }
146 ~nsAutoInPrincipalDomainOriginSetter() { --sInPrincipalDomainOrigin; }
147 static uint32_t sInPrincipalDomainOrigin;
149 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
151 static nsresult GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin) {
152 if (!aURI) {
153 return NS_ERROR_NULL_POINTER;
155 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin > 1) {
156 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
157 // might be happening on a different principal from the first call. But
158 // after that, cut off the recursion; it just indicates that something
159 // we're doing in this method causes us to reenter a security check here.
160 return NS_ERROR_NOT_AVAILABLE;
163 nsAutoInPrincipalDomainOriginSetter autoSetter;
165 nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI);
166 NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
168 nsAutoCString hostPort;
170 nsresult rv = uri->GetHostPort(hostPort);
171 if (NS_SUCCEEDED(rv)) {
172 nsAutoCString scheme;
173 rv = uri->GetScheme(scheme);
174 NS_ENSURE_SUCCESS(rv, rv);
175 aOrigin = scheme + "://"_ns + hostPort;
176 } else {
177 // Some URIs (e.g., nsSimpleURI) don't support host. Just
178 // get the full spec.
179 rv = uri->GetSpec(aOrigin);
180 NS_ENSURE_SUCCESS(rv, rv);
183 return NS_OK;
186 static nsresult GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
187 nsACString& aOrigin) {
188 aOrigin.Truncate();
189 nsCOMPtr<nsIURI> uri;
190 aPrincipal->GetDomain(getter_AddRefs(uri));
191 nsresult rv = GetOriginFromURI(uri, aOrigin);
192 if (NS_SUCCEEDED(rv)) {
193 return rv;
195 // If there is no Domain fallback to the Principals Origin
196 return aPrincipal->GetOriginNoSuffix(aOrigin);
199 inline void SetPendingExceptionASCII(JSContext* cx, const char* aMsg) {
200 JS_ReportErrorASCII(cx, "%s", aMsg);
203 inline void SetPendingException(JSContext* cx, const char16_t* aMsg) {
204 NS_ConvertUTF16toUTF8 msg(aMsg);
205 JS_ReportErrorUTF8(cx, "%s", msg.get());
208 /* static */
209 bool nsScriptSecurityManager::SecurityCompareURIs(nsIURI* aSourceURI,
210 nsIURI* aTargetURI) {
211 return NS_SecurityCompareURIs(aSourceURI, aTargetURI,
212 sStrictFileOriginPolicy);
215 // SecurityHashURI is consistent with SecurityCompareURIs because
216 // NS_SecurityHashURI is consistent with NS_SecurityCompareURIs. See
217 // nsNetUtil.h.
218 uint32_t nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI) {
219 return NS_SecurityHashURI(aURI);
223 * GetChannelResultPrincipal will return the principal that the resource
224 * returned by this channel will use. For example, if the resource is in
225 * a sandbox, it will return the nullprincipal. If the resource is forced
226 * to inherit principal, it will return the principal of its parent. If
227 * the load doesn't require sandboxing or inheriting, it will return the same
228 * principal as GetChannelURIPrincipal. Namely the principal of the URI
229 * that is being loaded.
231 NS_IMETHODIMP
232 nsScriptSecurityManager::GetChannelResultPrincipal(nsIChannel* aChannel,
233 nsIPrincipal** aPrincipal) {
234 return GetChannelResultPrincipal(aChannel, aPrincipal,
235 /*aIgnoreSandboxing*/ false);
238 nsresult nsScriptSecurityManager::GetChannelResultPrincipalIfNotSandboxed(
239 nsIChannel* aChannel, nsIPrincipal** aPrincipal) {
240 return GetChannelResultPrincipal(aChannel, aPrincipal,
241 /*aIgnoreSandboxing*/ true);
244 NS_IMETHODIMP
245 nsScriptSecurityManager::GetChannelResultStoragePrincipal(
246 nsIChannel* aChannel, nsIPrincipal** aPrincipal) {
247 nsCOMPtr<nsIPrincipal> principal;
248 nsresult rv = GetChannelResultPrincipal(aChannel, getter_AddRefs(principal),
249 /*aIgnoreSandboxing*/ false);
250 if (NS_WARN_IF(NS_FAILED(rv))) {
251 return rv;
254 return StoragePrincipalHelper::Create(
255 aChannel, principal, /* aForceIsolation */ false, aPrincipal);
258 NS_IMETHODIMP
259 nsScriptSecurityManager::GetChannelResultPrincipals(
260 nsIChannel* aChannel, nsIPrincipal** aPrincipal,
261 nsIPrincipal** aPartitionedPrincipal) {
262 nsresult rv = GetChannelResultPrincipal(aChannel, aPrincipal,
263 /*aIgnoreSandboxing*/ false);
264 if (NS_WARN_IF(NS_FAILED(rv))) {
265 return rv;
268 if (!(*aPrincipal)->GetIsContentPrincipal()) {
269 // If for some reason we don't have a content principal here, just reuse our
270 // principal for the storage principal too, since attempting to create a
271 // storage principal would fail anyway.
272 nsCOMPtr<nsIPrincipal> copy = *aPrincipal;
273 copy.forget(aPartitionedPrincipal);
274 return NS_OK;
277 return StoragePrincipalHelper::Create(
278 aChannel, *aPrincipal, /* aForceIsolation */ true, aPartitionedPrincipal);
281 nsresult nsScriptSecurityManager::GetChannelResultPrincipal(
282 nsIChannel* aChannel, nsIPrincipal** aPrincipal, bool aIgnoreSandboxing) {
283 MOZ_ASSERT(aChannel, "Must have channel!");
285 // Check whether we have an nsILoadInfo that says what we should do.
286 nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
287 if (loadInfo->GetForceInheritPrincipalOverruleOwner()) {
288 nsCOMPtr<nsIPrincipal> principalToInherit =
289 loadInfo->FindPrincipalToInherit(aChannel);
290 principalToInherit.forget(aPrincipal);
291 return NS_OK;
294 nsCOMPtr<nsISupports> owner;
295 aChannel->GetOwner(getter_AddRefs(owner));
296 if (owner) {
297 CallQueryInterface(owner, aPrincipal);
298 if (*aPrincipal) {
299 return NS_OK;
303 if (!aIgnoreSandboxing && loadInfo->GetLoadingSandboxed()) {
304 nsCOMPtr<nsIPrincipal> sandboxedLoadingPrincipal =
305 loadInfo->GetSandboxedLoadingPrincipal();
306 MOZ_ASSERT(sandboxedLoadingPrincipal);
307 sandboxedLoadingPrincipal.forget(aPrincipal);
308 return NS_OK;
311 bool forceInherit = loadInfo->GetForceInheritPrincipal();
312 if (aIgnoreSandboxing && !forceInherit) {
313 // Check if SEC_FORCE_INHERIT_PRINCIPAL was dropped because of
314 // sandboxing:
315 if (loadInfo->GetLoadingSandboxed() &&
316 loadInfo->GetForceInheritPrincipalDropped()) {
317 forceInherit = true;
320 if (forceInherit) {
321 nsCOMPtr<nsIPrincipal> principalToInherit =
322 loadInfo->FindPrincipalToInherit(aChannel);
323 principalToInherit.forget(aPrincipal);
324 return NS_OK;
327 auto securityMode = loadInfo->GetSecurityMode();
328 // The data: inheritance flags should only apply to the initial load,
329 // not to loads that it might have redirected to.
330 if (loadInfo->RedirectChain().IsEmpty() &&
331 (securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS ||
332 securityMode == nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS ||
333 securityMode == nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS)) {
334 nsCOMPtr<nsIURI> uri;
335 nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
336 NS_ENSURE_SUCCESS(rv, rv);
338 nsCOMPtr<nsIPrincipal> principalToInherit =
339 loadInfo->FindPrincipalToInherit(aChannel);
340 bool inheritForAboutBlank = loadInfo->GetAboutBlankInherits();
342 if (nsContentUtils::ChannelShouldInheritPrincipal(
343 principalToInherit, uri, inheritForAboutBlank, false)) {
344 principalToInherit.forget(aPrincipal);
345 return NS_OK;
348 return GetChannelURIPrincipal(aChannel, aPrincipal);
351 /* The principal of the URI that this channel is loading. This is never
352 * affected by things like sandboxed loads, or loads where we forcefully
353 * inherit the principal. Think of this as the principal of the server
354 * which this channel is loading from. Most callers should use
355 * GetChannelResultPrincipal instead of GetChannelURIPrincipal. Only
356 * call GetChannelURIPrincipal if you are sure that you want the
357 * principal that matches the uri, even in cases when the load is
358 * sandboxed or when the load could be a blob or data uri (i.e even when
359 * you encounter loads that may or may not be sandboxed and loads
360 * that may or may not inherit)."
362 NS_IMETHODIMP
363 nsScriptSecurityManager::GetChannelURIPrincipal(nsIChannel* aChannel,
364 nsIPrincipal** aPrincipal) {
365 MOZ_ASSERT(aChannel, "Must have channel!");
367 // Get the principal from the URI. Make sure this does the same thing
368 // as Document::Reset and PrototypeDocumentContentSink::Init.
369 nsCOMPtr<nsIURI> uri;
370 nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
371 NS_ENSURE_SUCCESS(rv, rv);
373 nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
375 // Inherit the origin attributes from loadInfo.
376 // If this is a top-level document load, the origin attributes of the
377 // loadInfo will be set from nsDocShell::DoURILoad.
378 // For subresource loading, the origin attributes of the loadInfo is from
379 // its loadingPrincipal.
380 OriginAttributes attrs = loadInfo->GetOriginAttributes();
382 nsCOMPtr<nsIPrincipal> prin =
383 BasePrincipal::CreateContentPrincipal(uri, attrs);
384 prin.forget(aPrincipal);
385 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
388 /////////////////////////////
389 // nsScriptSecurityManager //
390 /////////////////////////////
392 ////////////////////////////////////
393 // Methods implementing ISupports //
394 ////////////////////////////////////
395 NS_IMPL_ISUPPORTS(nsScriptSecurityManager, nsIScriptSecurityManager)
397 ///////////////////////////////////////////////////
398 // Methods implementing nsIScriptSecurityManager //
399 ///////////////////////////////////////////////////
401 ///////////////// Security Checks /////////////////
403 bool nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(
404 JSContext* cx, JS::HandleString aCode) {
405 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
407 // Get the window, if any, corresponding to the current global
408 nsCOMPtr<nsIContentSecurityPolicy> csp;
409 if (nsGlobalWindowInner* win = xpc::CurrentWindowOrNull(cx)) {
410 csp = win->GetCsp();
413 nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
414 if (!csp) {
415 if (!StaticPrefs::extensions_content_script_csp_enabled()) {
416 return true;
418 // Get the CSP for addon sandboxes. If the principal is expanded and has a
419 // csp, we're probably in luck.
420 auto* basePrin = BasePrincipal::Cast(subjectPrincipal);
421 // ContentScriptAddonPolicy means it is also an expanded principal, thus
422 // this is in a sandbox used as a content script.
423 if (basePrin->ContentScriptAddonPolicy()) {
424 basePrin->As<ExpandedPrincipal>()->GetCsp(getter_AddRefs(csp));
426 // don't do anything unless there's a CSP
427 if (!csp) {
428 return true;
432 nsCOMPtr<nsICSPEventListener> cspEventListener;
433 if (!NS_IsMainThread()) {
434 WorkerPrivate* workerPrivate =
435 mozilla::dom::GetWorkerPrivateFromContext(cx);
436 if (workerPrivate) {
437 cspEventListener = workerPrivate->CSPEventListener();
441 bool evalOK = true;
442 bool reportViolation = false;
443 nsresult rv = csp->GetAllowsEval(&reportViolation, &evalOK);
445 // A little convoluted. We want the scriptSample for a) reporting a violation
446 // or b) passing it to AssertEvalNotUsingSystemPrincipal or c) we're in the
447 // parent process. So do the work to get it if either of those cases is true.
448 nsAutoJSString scriptSample;
449 if (reportViolation || subjectPrincipal->IsSystemPrincipal() ||
450 XRE_IsE10sParentProcess()) {
451 if (NS_WARN_IF(!scriptSample.init(cx, aCode))) {
452 JS_ClearPendingException(cx);
453 return false;
457 #if !defined(ANDROID)
458 if (!nsContentSecurityUtils::IsEvalAllowed(
459 cx, subjectPrincipal->IsSystemPrincipal(), scriptSample)) {
460 return false;
462 #endif
464 if (NS_FAILED(rv)) {
465 NS_WARNING("CSP: failed to get allowsEval");
466 return true; // fail open to not break sites.
469 if (reportViolation) {
470 JS::AutoFilename scriptFilename;
471 nsAutoString fileName;
472 unsigned lineNum = 0;
473 unsigned columnNum = 0;
474 if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum, &columnNum)) {
475 if (const char* file = scriptFilename.get()) {
476 CopyUTF8toUTF16(nsDependentCString(file), fileName);
478 } else {
479 MOZ_ASSERT(!JS_IsExceptionPending(cx));
481 csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
482 nullptr, // triggering element
483 cspEventListener, fileName, scriptSample, lineNum,
484 columnNum, EmptyString(), EmptyString());
487 return evalOK;
490 // static
491 bool nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals* first,
492 JSPrincipals* second) {
493 return nsJSPrincipals::get(first)->Subsumes(nsJSPrincipals::get(second));
496 NS_IMETHODIMP
497 nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
498 nsIURI* aTargetURI,
499 bool reportError,
500 bool aFromPrivateWindow) {
501 // Please note that aFromPrivateWindow is only 100% accurate if
502 // reportError is true.
503 if (!SecurityCompareURIs(aSourceURI, aTargetURI)) {
504 if (reportError) {
505 ReportError("CheckSameOriginError", aSourceURI, aTargetURI,
506 aFromPrivateWindow);
508 return NS_ERROR_DOM_BAD_URI;
510 return NS_OK;
513 NS_IMETHODIMP
514 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext* cx, nsIURI* aURI) {
515 // Get principal of currently executing script.
516 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
517 nsIPrincipal* principal = nsContentUtils::SubjectPrincipal();
518 nsresult rv = CheckLoadURIWithPrincipal(
519 // Passing 0 for the window ID here is OK, because we will report a
520 // script-visible exception anyway.
521 principal, aURI, nsIScriptSecurityManager::STANDARD, 0);
522 if (NS_SUCCEEDED(rv)) {
523 // OK to load
524 return NS_OK;
527 // Report error.
528 nsAutoCString spec;
529 if (NS_FAILED(aURI->GetAsciiSpec(spec))) return NS_ERROR_FAILURE;
530 nsAutoCString msg("Access to '");
531 msg.Append(spec);
532 msg.AppendLiteral("' from script denied");
533 SetPendingExceptionASCII(cx, msg.get());
534 return NS_ERROR_DOM_BAD_URI;
538 * Helper method to handle cases where a flag passed to
539 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
540 * nsIProtocolHandler flags set.
541 * @return if success, access is allowed. Otherwise, deny access
543 static nsresult DenyAccessIfURIHasFlags(nsIURI* aURI, uint32_t aURIFlags) {
544 MOZ_ASSERT(aURI, "Must have URI!");
546 bool uriHasFlags;
547 nsresult rv = NS_URIChainHasFlags(aURI, aURIFlags, &uriHasFlags);
548 NS_ENSURE_SUCCESS(rv, rv);
550 if (uriHasFlags) {
551 return NS_ERROR_DOM_BAD_URI;
554 return NS_OK;
557 static bool EqualOrSubdomain(nsIURI* aProbeArg, nsIURI* aBase) {
558 nsresult rv;
559 nsCOMPtr<nsIURI> probe = aProbeArg;
561 nsCOMPtr<nsIEffectiveTLDService> tldService =
562 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
563 NS_ENSURE_TRUE(tldService, false);
564 while (true) {
565 if (nsScriptSecurityManager::SecurityCompareURIs(probe, aBase)) {
566 return true;
569 nsAutoCString host, newHost;
570 rv = probe->GetHost(host);
571 NS_ENSURE_SUCCESS(rv, false);
573 rv = tldService->GetNextSubDomain(host, newHost);
574 if (rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
575 return false;
577 NS_ENSURE_SUCCESS(rv, false);
578 rv = NS_MutateURI(probe).SetHost(newHost).Finalize(probe);
579 NS_ENSURE_SUCCESS(rv, false);
583 NS_IMETHODIMP
584 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal* aPrincipal,
585 nsIURI* aTargetURI,
586 uint32_t aFlags,
587 uint64_t aInnerWindowID) {
588 MOZ_ASSERT(aPrincipal, "CheckLoadURIWithPrincipal must have a principal");
590 // If someone passes a flag that we don't understand, we should
591 // fail, because they may need a security check that we don't
592 // provide.
593 NS_ENSURE_FALSE(
594 aFlags &
595 ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
596 nsIScriptSecurityManager::ALLOW_CHROME |
597 nsIScriptSecurityManager::DISALLOW_SCRIPT |
598 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL |
599 nsIScriptSecurityManager::DONT_REPORT_ERRORS),
600 NS_ERROR_UNEXPECTED);
601 NS_ENSURE_ARG_POINTER(aPrincipal);
602 NS_ENSURE_ARG_POINTER(aTargetURI);
604 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
605 // would do such inheriting. That would be URIs that do not have their own
606 // security context. We do this even for the system principal.
607 if (aFlags & nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL) {
608 nsresult rv = DenyAccessIfURIHasFlags(
609 aTargetURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT);
610 NS_ENSURE_SUCCESS(rv, rv);
613 if (aPrincipal == mSystemPrincipal) {
614 // Allow access
615 return NS_OK;
618 nsCOMPtr<nsIURI> sourceURI;
619 auto* basePrin = BasePrincipal::Cast(aPrincipal);
620 basePrin->GetURI(getter_AddRefs(sourceURI));
621 if (!sourceURI) {
622 if (basePrin->Is<ExpandedPrincipal>()) {
623 auto expanded = basePrin->As<ExpandedPrincipal>();
624 for (auto& prin : expanded->AllowList()) {
625 nsresult rv =
626 CheckLoadURIWithPrincipal(prin, aTargetURI, aFlags, aInnerWindowID);
627 if (NS_SUCCEEDED(rv)) {
628 // Allow access if it succeeded with one of the allowlisted principals
629 return NS_OK;
632 // None of our allowlisted principals worked.
633 return NS_ERROR_DOM_BAD_URI;
635 NS_ERROR(
636 "Non-system principals or expanded principal passed to "
637 "CheckLoadURIWithPrincipal "
638 "must have a URI!");
639 return NS_ERROR_UNEXPECTED;
642 // Automatic loads are not allowed from certain protocols.
643 if (aFlags &
644 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT) {
645 nsresult rv = DenyAccessIfURIHasFlags(
646 sourceURI,
647 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT);
648 NS_ENSURE_SUCCESS(rv, rv);
651 // If either URI is a nested URI, get the base URI
652 nsCOMPtr<nsIURI> sourceBaseURI = NS_GetInnermostURI(sourceURI);
653 nsCOMPtr<nsIURI> targetBaseURI = NS_GetInnermostURI(aTargetURI);
655 //-- get the target scheme
656 nsAutoCString targetScheme;
657 nsresult rv = targetBaseURI->GetScheme(targetScheme);
658 if (NS_FAILED(rv)) return rv;
660 //-- Some callers do not allow loading javascript:
661 if ((aFlags & nsIScriptSecurityManager::DISALLOW_SCRIPT) &&
662 targetScheme.EqualsLiteral("javascript")) {
663 return NS_ERROR_DOM_BAD_URI;
666 // Check for uris that are only loadable by principals that subsume them
667 bool targetURIIsLoadableBySubsumers = false;
668 rv = NS_URIChainHasFlags(targetBaseURI,
669 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS,
670 &targetURIIsLoadableBySubsumers);
671 NS_ENSURE_SUCCESS(rv, rv);
673 if (targetURIIsLoadableBySubsumers) {
674 // check nothing else in the URI chain has flags that prevent
675 // access:
676 rv = CheckLoadURIFlags(
677 sourceURI, aTargetURI, sourceBaseURI, targetBaseURI, aFlags,
678 aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0,
679 aInnerWindowID);
680 NS_ENSURE_SUCCESS(rv, rv);
681 // Check the principal is allowed to load the target.
682 if (aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS) {
683 return aPrincipal->CheckMayLoad(targetBaseURI, false);
685 return aPrincipal->CheckMayLoadWithReporting(targetBaseURI, false,
686 aInnerWindowID);
689 //-- get the source scheme
690 nsAutoCString sourceScheme;
691 rv = sourceBaseURI->GetScheme(sourceScheme);
692 if (NS_FAILED(rv)) return rv;
694 if (sourceScheme.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME)) {
695 // A null principal can target its own URI.
696 if (sourceURI == aTargetURI) {
697 return NS_OK;
699 } else if (StaticPrefs::
700 security_view_source_reachable_from_inner_protocol() &&
701 sourceScheme.EqualsIgnoreCase(targetScheme.get()) &&
702 aTargetURI->SchemeIs("view-source")) {
703 // exception for foo: linking to view-source:foo for reftests...
704 return NS_OK;
705 } else if (sourceScheme.EqualsIgnoreCase("file") &&
706 targetScheme.EqualsIgnoreCase("moz-icon")) {
707 // exception for file: linking to moz-icon://.ext?size=...
708 // Note that because targetScheme is the base (innermost) URI scheme,
709 // this does NOT allow file -> moz-icon:file:///... links.
710 // This is intentional.
711 return NS_OK;
714 // Check for webextension
715 bool targetURIIsLoadableByExtensions = false;
716 rv = NS_URIChainHasFlags(aTargetURI,
717 nsIProtocolHandler::URI_LOADABLE_BY_EXTENSIONS,
718 &targetURIIsLoadableByExtensions);
719 NS_ENSURE_SUCCESS(rv, rv);
721 if (targetURIIsLoadableByExtensions &&
722 BasePrincipal::Cast(aPrincipal)->AddonPolicy()) {
723 return NS_OK;
726 // If we get here, check all the schemes can link to each other, from the top
727 // down:
728 nsCOMPtr<nsIURI> currentURI = sourceURI;
729 nsCOMPtr<nsIURI> currentOtherURI = aTargetURI;
731 bool denySameSchemeLinks = false;
732 rv = NS_URIChainHasFlags(aTargetURI,
733 nsIProtocolHandler::URI_SCHEME_NOT_SELF_LINKABLE,
734 &denySameSchemeLinks);
735 if (NS_FAILED(rv)) return rv;
737 while (currentURI && currentOtherURI) {
738 nsAutoCString scheme, otherScheme;
739 currentURI->GetScheme(scheme);
740 currentOtherURI->GetScheme(otherScheme);
742 bool schemesMatch =
743 scheme.Equals(otherScheme, nsCaseInsensitiveCStringComparator);
744 bool isSamePage = false;
745 // about: URIs are special snowflakes.
746 if (scheme.EqualsLiteral("about") && schemesMatch) {
747 nsAutoCString moduleName, otherModuleName;
748 // about: pages can always link to themselves:
749 isSamePage =
750 NS_SUCCEEDED(NS_GetAboutModuleName(currentURI, moduleName)) &&
751 NS_SUCCEEDED(
752 NS_GetAboutModuleName(currentOtherURI, otherModuleName)) &&
753 moduleName.Equals(otherModuleName);
754 if (!isSamePage) {
755 // We will have allowed the load earlier if the source page has
756 // system principal. So we know the source has a content
757 // principal, and it's trying to link to something else.
758 // Linkable about: pages are always reachable, even if we hit
759 // the CheckLoadURIFlags call below.
760 // We punch only 1 other hole: iff the source is unlinkable,
761 // we let them link to other pages explicitly marked SAFE
762 // for content. This avoids world-linkable about: pages linking
763 // to non-world-linkable about: pages.
764 nsCOMPtr<nsIAboutModule> module, otherModule;
765 bool knowBothModules =
766 NS_SUCCEEDED(
767 NS_GetAboutModule(currentURI, getter_AddRefs(module))) &&
768 NS_SUCCEEDED(NS_GetAboutModule(currentOtherURI,
769 getter_AddRefs(otherModule)));
770 uint32_t aboutModuleFlags = 0;
771 uint32_t otherAboutModuleFlags = 0;
772 knowBothModules =
773 knowBothModules &&
774 NS_SUCCEEDED(module->GetURIFlags(currentURI, &aboutModuleFlags)) &&
775 NS_SUCCEEDED(otherModule->GetURIFlags(currentOtherURI,
776 &otherAboutModuleFlags));
777 if (knowBothModules) {
778 isSamePage = !(aboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) &&
779 (otherAboutModuleFlags &
780 nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT);
781 if (isSamePage &&
782 otherAboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) {
783 // XXXgijs: this is a hack. The target will be nested
784 // (with innerURI of moz-safe-about:whatever), and
785 // the source isn't, so we won't pass if we finish
786 // the loop. We *should* pass, though, so return here.
787 // This hack can go away when bug 1228118 is fixed.
788 return NS_OK;
792 } else {
793 bool equalExceptRef = false;
794 rv = currentURI->EqualsExceptRef(currentOtherURI, &equalExceptRef);
795 isSamePage = NS_SUCCEEDED(rv) && equalExceptRef;
798 // If schemes are not equal, or they're equal but the target URI
799 // is different from the source URI and doesn't always allow linking
800 // from the same scheme, check if the URI flags of the current target
801 // URI allow the current source URI to link to it.
802 // The policy is specified by the protocol flags on both URIs.
803 if (!schemesMatch || (denySameSchemeLinks && !isSamePage)) {
804 return CheckLoadURIFlags(
805 currentURI, currentOtherURI, sourceBaseURI, targetBaseURI, aFlags,
806 aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0,
807 aInnerWindowID);
809 // Otherwise... check if we can nest another level:
810 nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(currentURI);
811 nsCOMPtr<nsINestedURI> nestedOtherURI = do_QueryInterface(currentOtherURI);
813 // If schemes match and neither URI is nested further, we're OK.
814 if (!nestedURI && !nestedOtherURI) {
815 return NS_OK;
817 // If one is nested and the other isn't, something is wrong.
818 if (!nestedURI != !nestedOtherURI) {
819 return NS_ERROR_DOM_BAD_URI;
821 // Otherwise, both should be nested and we'll go through the loop again.
822 nestedURI->GetInnerURI(getter_AddRefs(currentURI));
823 nestedOtherURI->GetInnerURI(getter_AddRefs(currentOtherURI));
826 // We should never get here. We should always return from inside the loop.
827 return NS_ERROR_DOM_BAD_URI;
831 * Helper method to check whether the target URI and its innermost ("base") URI
832 * has protocol flags that should stop it from being loaded by the source URI
833 * (and/or the source URI's innermost ("base") URI), taking into account any
834 * nsIScriptSecurityManager flags originally passed to
835 * CheckLoadURIWithPrincipal and friends.
837 * @return if success, access is allowed. Otherwise, deny access
839 nsresult nsScriptSecurityManager::CheckLoadURIFlags(
840 nsIURI* aSourceURI, nsIURI* aTargetURI, nsIURI* aSourceBaseURI,
841 nsIURI* aTargetBaseURI, uint32_t aFlags, bool aFromPrivateWindow,
842 uint64_t aInnerWindowID) {
843 // Note that the order of policy checks here is very important!
844 // We start from most restrictive and work our way down.
845 bool reportErrors = !(aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS);
846 const char* errorTag = "CheckLoadURIError";
848 nsAutoCString targetScheme;
849 nsresult rv = aTargetBaseURI->GetScheme(targetScheme);
850 if (NS_FAILED(rv)) return rv;
852 // Check for system target URI
853 rv = DenyAccessIfURIHasFlags(aTargetURI,
854 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD);
855 if (NS_FAILED(rv)) {
856 // Deny access, since the origin principal is not system
857 if (reportErrors) {
858 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
859 aInnerWindowID);
861 return rv;
864 // Used by ExtensionProtocolHandler to prevent loading extension resources
865 // in private contexts if the extension does not have permission.
866 if (aFromPrivateWindow) {
867 rv = DenyAccessIfURIHasFlags(
868 aTargetURI, nsIProtocolHandler::URI_DISALLOW_IN_PRIVATE_CONTEXT);
869 if (NS_FAILED(rv)) {
870 if (reportErrors) {
871 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
872 aInnerWindowID);
874 return rv;
878 // Check for chrome target URI
879 bool targetURIIsUIResource = false;
880 rv = NS_URIChainHasFlags(aTargetURI, nsIProtocolHandler::URI_IS_UI_RESOURCE,
881 &targetURIIsUIResource);
882 NS_ENSURE_SUCCESS(rv, rv);
883 if (targetURIIsUIResource) {
884 if (aFlags & nsIScriptSecurityManager::ALLOW_CHROME) {
885 // Allow a URI_IS_UI_RESOURCE source to link to a URI_IS_UI_RESOURCE
886 // target if ALLOW_CHROME is set.
888 // ALLOW_CHROME is a flag that we pass on all loads _except_ docshell
889 // loads (since docshell loads run the loaded content with its origin
890 // principal). So we're effectively allowing resource://, chrome://,
891 // and moz-icon:// source URIs to load resource://, chrome://, and
892 // moz-icon:// files, so long as they're not loading it as a document.
893 bool sourceIsUIResource;
894 rv = NS_URIChainHasFlags(aSourceBaseURI,
895 nsIProtocolHandler::URI_IS_UI_RESOURCE,
896 &sourceIsUIResource);
897 NS_ENSURE_SUCCESS(rv, rv);
898 if (sourceIsUIResource) {
899 return NS_OK;
902 if (targetScheme.EqualsLiteral("resource")) {
903 if (StaticPrefs::security_all_resource_uri_content_accessible()) {
904 return NS_OK;
907 nsCOMPtr<nsIProtocolHandler> ph;
908 rv = sIOService->GetProtocolHandler("resource", getter_AddRefs(ph));
909 NS_ENSURE_SUCCESS(rv, rv);
910 if (!ph) {
911 return NS_ERROR_DOM_BAD_URI;
914 nsCOMPtr<nsIResProtocolHandler> rph = do_QueryInterface(ph);
915 if (!rph) {
916 return NS_ERROR_DOM_BAD_URI;
919 bool accessAllowed = false;
920 rph->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
921 if (accessAllowed) {
922 return NS_OK;
924 } else if (targetScheme.EqualsLiteral("chrome")) {
925 // Allow the load only if the chrome package is allowlisted.
926 nsCOMPtr<nsIXULChromeRegistry> reg(
927 do_GetService(NS_CHROMEREGISTRY_CONTRACTID));
928 if (reg) {
929 bool accessAllowed = false;
930 reg->AllowContentToAccess(aTargetBaseURI, &accessAllowed);
931 if (accessAllowed) {
932 return NS_OK;
935 } else if (targetScheme.EqualsLiteral("moz-page-thumb")) {
936 if (XRE_IsParentProcess()) {
937 return NS_OK;
940 auto& remoteType = dom::ContentChild::GetSingleton()->GetRemoteType();
941 if (remoteType.EqualsLiteral(PRIVILEGEDABOUT_REMOTE_TYPE)) {
942 return NS_OK;
947 if (reportErrors) {
948 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
949 aInnerWindowID);
951 return NS_ERROR_DOM_BAD_URI;
954 // Check for target URI pointing to a file
955 bool targetURIIsLocalFile = false;
956 rv = NS_URIChainHasFlags(aTargetURI, nsIProtocolHandler::URI_IS_LOCAL_FILE,
957 &targetURIIsLocalFile);
958 NS_ENSURE_SUCCESS(rv, rv);
959 if (targetURIIsLocalFile) {
960 // Allow domains that were allowlisted in the prefs. In 99.9% of cases,
961 // this array is empty.
962 bool isAllowlisted;
963 MOZ_ALWAYS_SUCCEEDS(InFileURIAllowlist(aSourceURI, &isAllowlisted));
964 if (isAllowlisted) {
965 return NS_OK;
968 // Allow chrome://
969 if (aSourceBaseURI->SchemeIs("chrome")) {
970 return NS_OK;
973 // Nothing else.
974 if (reportErrors) {
975 ReportError(errorTag, aSourceURI, aTargetURI, aFromPrivateWindow,
976 aInnerWindowID);
978 return NS_ERROR_DOM_BAD_URI;
981 #ifdef DEBUG
983 // Everyone is allowed to load this. The case URI_LOADABLE_BY_SUBSUMERS
984 // is handled by the caller which is just delegating to us as a helper.
985 bool hasSubsumersFlag = false;
986 NS_URIChainHasFlags(aTargetBaseURI,
987 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS,
988 &hasSubsumersFlag);
989 bool hasLoadableByAnyone = false;
990 NS_URIChainHasFlags(aTargetBaseURI,
991 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE,
992 &hasLoadableByAnyone);
993 MOZ_ASSERT(hasLoadableByAnyone || hasSubsumersFlag,
994 "why do we get here and do not have any of the two flags set?");
996 #endif
998 return NS_OK;
1001 nsresult nsScriptSecurityManager::ReportError(const char* aMessageTag,
1002 const nsACString& aSourceSpec,
1003 const nsACString& aTargetSpec,
1004 bool aFromPrivateWindow,
1005 uint64_t aInnerWindowID) {
1006 if (aSourceSpec.IsEmpty() || aTargetSpec.IsEmpty()) {
1007 return NS_OK;
1010 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
1011 if (NS_WARN_IF(!bundle)) {
1012 return NS_OK;
1015 // Localize the error message
1016 nsAutoString message;
1017 AutoTArray<nsString, 2> formatStrings;
1018 CopyASCIItoUTF16(aSourceSpec, *formatStrings.AppendElement());
1019 CopyASCIItoUTF16(aTargetSpec, *formatStrings.AppendElement());
1020 nsresult rv =
1021 bundle->FormatStringFromName(aMessageTag, formatStrings, message);
1022 NS_ENSURE_SUCCESS(rv, rv);
1024 nsCOMPtr<nsIConsoleService> console(
1025 do_GetService(NS_CONSOLESERVICE_CONTRACTID));
1026 NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
1027 nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
1028 NS_ENSURE_TRUE(error, NS_ERROR_FAILURE);
1030 // using category of "SOP" so we can link to MDN
1031 if (aInnerWindowID != 0) {
1032 rv = error->InitWithWindowID(
1033 message, EmptyString(), EmptyString(), 0, 0, nsIScriptError::errorFlag,
1034 "SOP"_ns, aInnerWindowID, true /* From chrome context */);
1035 } else {
1036 rv = error->Init(message, EmptyString(), EmptyString(), 0, 0,
1037 nsIScriptError::errorFlag, "SOP", aFromPrivateWindow,
1038 true /* From chrome context */);
1040 NS_ENSURE_SUCCESS(rv, rv);
1041 console->LogMessage(error);
1042 return NS_OK;
1045 nsresult nsScriptSecurityManager::ReportError(const char* aMessageTag,
1046 nsIURI* aSource, nsIURI* aTarget,
1047 bool aFromPrivateWindow,
1048 uint64_t aInnerWindowID) {
1049 NS_ENSURE_TRUE(aSource && aTarget, NS_ERROR_NULL_POINTER);
1051 // Get the source URL spec
1052 nsAutoCString sourceSpec;
1053 nsresult rv = aSource->GetAsciiSpec(sourceSpec);
1054 NS_ENSURE_SUCCESS(rv, rv);
1056 // Get the target URL spec
1057 nsAutoCString targetSpec;
1058 rv = aTarget->GetAsciiSpec(targetSpec);
1059 NS_ENSURE_SUCCESS(rv, rv);
1061 return ReportError(aMessageTag, sourceSpec, targetSpec, aFromPrivateWindow,
1062 aInnerWindowID);
1065 NS_IMETHODIMP
1066 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
1067 nsIPrincipal* aPrincipal, const nsACString& aTargetURIStr,
1068 uint32_t aFlags) {
1069 nsresult rv;
1070 nsCOMPtr<nsIURI> target;
1071 rv = NS_NewURI(getter_AddRefs(target), aTargetURIStr);
1072 NS_ENSURE_SUCCESS(rv, rv);
1074 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags, 0);
1075 if (rv == NS_ERROR_DOM_BAD_URI) {
1076 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1077 // return values.
1078 return rv;
1080 NS_ENSURE_SUCCESS(rv, rv);
1082 // Now start testing fixup -- since aTargetURIStr is a string, not
1083 // an nsIURI, we may well end up fixing it up before loading.
1084 // Note: This needs to stay in sync with the nsIURIFixup api.
1085 nsCOMPtr<nsIURIFixup> fixup = components::URIFixup::Service();
1086 if (!fixup) {
1087 return rv;
1090 // URIFixup's keyword and alternate flags can only fixup to http/https, so we
1091 // can skip testing them. This simplifies our life because this code can be
1092 // invoked from the content process where the search service would not be
1093 // available.
1094 uint32_t flags[] = {nsIURIFixup::FIXUP_FLAG_NONE,
1095 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS};
1096 for (uint32_t i = 0; i < ArrayLength(flags); ++i) {
1097 uint32_t fixupFlags = flags[i];
1098 if (aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0) {
1099 fixupFlags |= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT;
1101 rv = fixup->CreateFixupURI(aTargetURIStr, fixupFlags, nullptr,
1102 getter_AddRefs(target));
1103 NS_ENSURE_SUCCESS(rv, rv);
1105 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags, 0);
1106 if (rv == NS_ERROR_DOM_BAD_URI) {
1107 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
1108 // return values.
1109 return rv;
1111 NS_ENSURE_SUCCESS(rv, rv);
1114 return rv;
1117 NS_IMETHODIMP
1118 nsScriptSecurityManager::InFileURIAllowlist(nsIURI* aUri, bool* aResult) {
1119 MOZ_ASSERT(aUri);
1120 MOZ_ASSERT(aResult);
1122 *aResult = false;
1123 for (nsIURI* uri : EnsureFileURIAllowlist()) {
1124 if (EqualOrSubdomain(aUri, uri)) {
1125 *aResult = true;
1126 return NS_OK;
1130 return NS_OK;
1133 ///////////////// Principals ///////////////////////
1135 NS_IMETHODIMP
1136 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal** result) {
1137 NS_ADDREF(*result = mSystemPrincipal);
1139 return NS_OK;
1142 NS_IMETHODIMP
1143 nsScriptSecurityManager::CreateContentPrincipal(
1144 nsIURI* aURI, JS::Handle<JS::Value> aOriginAttributes, JSContext* aCx,
1145 nsIPrincipal** aPrincipal) {
1146 OriginAttributes attrs;
1147 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1148 return NS_ERROR_INVALID_ARG;
1150 nsCOMPtr<nsIPrincipal> prin =
1151 BasePrincipal::CreateContentPrincipal(aURI, attrs);
1152 prin.forget(aPrincipal);
1153 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1156 NS_IMETHODIMP
1157 nsScriptSecurityManager::CreateContentPrincipalFromOrigin(
1158 const nsACString& aOrigin, nsIPrincipal** aPrincipal) {
1159 if (StringBeginsWith(aOrigin, "["_ns)) {
1160 return NS_ERROR_INVALID_ARG;
1163 if (StringBeginsWith(aOrigin,
1164 nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":"))) {
1165 return NS_ERROR_INVALID_ARG;
1168 nsCOMPtr<nsIPrincipal> prin = BasePrincipal::CreateContentPrincipal(aOrigin);
1169 prin.forget(aPrincipal);
1170 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1173 NS_IMETHODIMP
1174 nsScriptSecurityManager::PrincipalToJSON(nsIPrincipal* aPrincipal,
1175 nsACString& aJSON) {
1176 aJSON.Truncate();
1177 if (!aPrincipal) {
1178 return NS_ERROR_FAILURE;
1181 BasePrincipal::Cast(aPrincipal)->ToJSON(aJSON);
1183 if (aJSON.IsEmpty()) {
1184 return NS_ERROR_FAILURE;
1187 return NS_OK;
1190 NS_IMETHODIMP
1191 nsScriptSecurityManager::JSONToPrincipal(const nsACString& aJSON,
1192 nsIPrincipal** aPrincipal) {
1193 if (aJSON.IsEmpty()) {
1194 return NS_ERROR_FAILURE;
1197 nsCOMPtr<nsIPrincipal> principal = BasePrincipal::FromJSON(aJSON);
1199 if (!principal) {
1200 return NS_ERROR_FAILURE;
1203 principal.forget(aPrincipal);
1204 return NS_OK;
1207 NS_IMETHODIMP
1208 nsScriptSecurityManager::CreateNullPrincipal(
1209 JS::Handle<JS::Value> aOriginAttributes, JSContext* aCx,
1210 nsIPrincipal** aPrincipal) {
1211 OriginAttributes attrs;
1212 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1213 return NS_ERROR_INVALID_ARG;
1215 nsCOMPtr<nsIPrincipal> prin = NullPrincipal::Create(attrs);
1216 prin.forget(aPrincipal);
1217 return NS_OK;
1220 NS_IMETHODIMP
1221 nsScriptSecurityManager::GetLoadContextContentPrincipal(
1222 nsIURI* aURI, nsILoadContext* aLoadContext, nsIPrincipal** aPrincipal) {
1223 NS_ENSURE_STATE(aLoadContext);
1224 OriginAttributes docShellAttrs;
1225 aLoadContext->GetOriginAttributes(docShellAttrs);
1227 nsCOMPtr<nsIPrincipal> prin =
1228 BasePrincipal::CreateContentPrincipal(aURI, docShellAttrs);
1229 prin.forget(aPrincipal);
1230 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1233 NS_IMETHODIMP
1234 nsScriptSecurityManager::GetDocShellContentPrincipal(
1235 nsIURI* aURI, nsIDocShell* aDocShell, nsIPrincipal** aPrincipal) {
1236 nsCOMPtr<nsIPrincipal> prin = BasePrincipal::CreateContentPrincipal(
1237 aURI, nsDocShell::Cast(aDocShell)->GetOriginAttributes());
1238 prin.forget(aPrincipal);
1239 return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
1242 NS_IMETHODIMP
1243 nsScriptSecurityManager::PrincipalWithOA(
1244 nsIPrincipal* aPrincipal, JS::Handle<JS::Value> aOriginAttributes,
1245 JSContext* aCx, nsIPrincipal** aReturnPrincipal) {
1246 if (!aPrincipal) {
1247 return NS_OK;
1249 if (aPrincipal->GetIsContentPrincipal()) {
1250 OriginAttributes attrs;
1251 if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
1252 return NS_ERROR_INVALID_ARG;
1254 RefPtr<ContentPrincipal> copy = new ContentPrincipal();
1255 auto* contentPrincipal = static_cast<ContentPrincipal*>(aPrincipal);
1256 nsresult rv = copy->Init(contentPrincipal, attrs);
1257 NS_ENSURE_SUCCESS(rv, rv);
1258 copy.forget(aReturnPrincipal);
1259 } else {
1260 // We do this for null principals, system principals (both fine)
1261 // ... and expanded principals, where we should probably do something
1262 // cleverer, but I also don't think we care too much.
1263 nsCOMPtr<nsIPrincipal> prin = aPrincipal;
1264 prin.forget(aReturnPrincipal);
1267 return *aReturnPrincipal ? NS_OK : NS_ERROR_FAILURE;
1270 NS_IMETHODIMP
1271 nsScriptSecurityManager::CanCreateWrapper(JSContext* cx, const nsIID& aIID,
1272 nsISupports* aObj,
1273 nsIClassInfo* aClassInfo) {
1274 // XXX Special case for Exception ?
1276 // We give remote-XUL allowlisted domains a free pass here. See bug 932906.
1277 JS::Rooted<JS::Realm*> contextRealm(cx, JS::GetCurrentRealmOrNull(cx));
1278 MOZ_RELEASE_ASSERT(contextRealm);
1279 if (!xpc::AllowContentXBLScope(contextRealm)) {
1280 return NS_OK;
1283 if (nsContentUtils::IsCallerChrome()) {
1284 return NS_OK;
1287 //-- Access denied, report an error
1288 nsAutoCString originUTF8;
1289 nsIPrincipal* subjectPrincipal = nsContentUtils::SubjectPrincipal();
1290 GetPrincipalDomainOrigin(subjectPrincipal, originUTF8);
1291 NS_ConvertUTF8toUTF16 originUTF16(originUTF8);
1292 nsAutoCString classInfoNameUTF8;
1293 if (aClassInfo) {
1294 aClassInfo->GetClassDescription(classInfoNameUTF8);
1296 if (classInfoNameUTF8.IsEmpty()) {
1297 classInfoNameUTF8.AssignLiteral("UnnamedClass");
1300 nsCOMPtr<nsIStringBundle> bundle = BundleHelper::GetOrCreate();
1301 if (NS_WARN_IF(!bundle)) {
1302 return NS_OK;
1305 NS_ConvertUTF8toUTF16 classInfoUTF16(classInfoNameUTF8);
1306 nsresult rv;
1307 nsAutoString errorMsg;
1308 if (originUTF16.IsEmpty()) {
1309 AutoTArray<nsString, 1> formatStrings = {classInfoUTF16};
1310 rv = bundle->FormatStringFromName("CreateWrapperDenied", formatStrings,
1311 errorMsg);
1312 } else {
1313 AutoTArray<nsString, 2> formatStrings = {classInfoUTF16, originUTF16};
1314 rv = bundle->FormatStringFromName("CreateWrapperDeniedForOrigin",
1315 formatStrings, errorMsg);
1317 NS_ENSURE_SUCCESS(rv, rv);
1319 SetPendingException(cx, errorMsg.get());
1320 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1323 NS_IMETHODIMP
1324 nsScriptSecurityManager::CanCreateInstance(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 create instance of class. 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 NS_IMETHODIMP
1339 nsScriptSecurityManager::CanGetService(JSContext* cx, const nsCID& aCID) {
1340 if (nsContentUtils::IsCallerChrome()) {
1341 return NS_OK;
1344 //-- Access denied, report an error
1345 nsAutoCString errorMsg("Permission denied to get service. CID=");
1346 char cidStr[NSID_LENGTH];
1347 aCID.ToProvidedString(cidStr);
1348 errorMsg.Append(cidStr);
1349 SetPendingExceptionASCII(cx, errorMsg.get());
1350 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1353 const char sJSEnabledPrefName[] = "javascript.enabled";
1354 const char sFileOriginPolicyPrefName[] =
1355 "security.fileuri.strict_origin_policy";
1357 static const char* kObservedPrefs[] = {sJSEnabledPrefName,
1358 sFileOriginPolicyPrefName,
1359 "capability.policy.", nullptr};
1361 /////////////////////////////////////////////
1362 // Constructor, Destructor, Initialization //
1363 /////////////////////////////////////////////
1364 nsScriptSecurityManager::nsScriptSecurityManager(void)
1365 : mPrefInitialized(false), mIsJavaScriptEnabled(false) {
1366 static_assert(
1367 sizeof(intptr_t) == sizeof(void*),
1368 "intptr_t and void* have different lengths on this platform. "
1369 "This may cause a security failure with the SecurityLevel union.");
1372 nsresult nsScriptSecurityManager::Init() {
1373 nsresult rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
1374 NS_ENSURE_SUCCESS(rv, rv);
1376 InitPrefs();
1378 // Create our system principal singleton
1379 RefPtr<SystemPrincipal> system = SystemPrincipal::Create();
1381 mSystemPrincipal = system;
1383 return NS_OK;
1386 void nsScriptSecurityManager::InitJSCallbacks(JSContext* aCx) {
1387 //-- Register security check callback in the JS engine
1388 // Currently this is used to control access to function.caller
1390 static const JSSecurityCallbacks securityCallbacks = {
1391 ContentSecurityPolicyPermitsJSAction,
1392 JSPrincipalsSubsume,
1395 MOZ_ASSERT(!JS_GetSecurityCallbacks(aCx));
1396 JS_SetSecurityCallbacks(aCx, &securityCallbacks);
1397 JS_InitDestroyPrincipalsCallback(aCx, nsJSPrincipals::Destroy);
1399 JS_SetTrustedPrincipals(aCx, BasePrincipal::Cast(mSystemPrincipal));
1402 /* static */
1403 void nsScriptSecurityManager::ClearJSCallbacks(JSContext* aCx) {
1404 JS_SetSecurityCallbacks(aCx, nullptr);
1405 JS_SetTrustedPrincipals(aCx, nullptr);
1408 static StaticRefPtr<nsScriptSecurityManager> gScriptSecMan;
1410 nsScriptSecurityManager::~nsScriptSecurityManager(void) {
1411 Preferences::UnregisterPrefixCallbacks(
1412 nsScriptSecurityManager::ScriptSecurityPrefChanged, kObservedPrefs, this);
1413 if (mDomainPolicy) {
1414 mDomainPolicy->Deactivate();
1416 // ContentChild might hold a reference to the domain policy,
1417 // and it might release it only after the security manager is
1418 // gone. But we can still assert this for the main process.
1419 MOZ_ASSERT_IF(XRE_IsParentProcess(), !mDomainPolicy);
1422 void nsScriptSecurityManager::Shutdown() {
1423 NS_IF_RELEASE(sIOService);
1424 BundleHelper::Shutdown();
1427 nsScriptSecurityManager* nsScriptSecurityManager::GetScriptSecurityManager() {
1428 return gScriptSecMan;
1431 /* static */
1432 void nsScriptSecurityManager::InitStatics() {
1433 RefPtr<nsScriptSecurityManager> ssManager = new nsScriptSecurityManager();
1434 nsresult rv = ssManager->Init();
1435 if (NS_FAILED(rv)) {
1436 MOZ_CRASH("ssManager->Init() failed");
1439 ClearOnShutdown(&gScriptSecMan);
1440 gScriptSecMan = ssManager;
1443 // Currently this nsGenericFactory constructor is used only from FastLoad
1444 // (XPCOM object deserialization) code, when "creating" the system principal
1445 // singleton.
1446 already_AddRefed<SystemPrincipal>
1447 nsScriptSecurityManager::SystemPrincipalSingletonConstructor() {
1448 if (gScriptSecMan)
1449 return do_AddRef(gScriptSecMan->mSystemPrincipal)
1450 .downcast<SystemPrincipal>();
1451 return nullptr;
1454 struct IsWhitespace {
1455 static bool Test(char aChar) { return NS_IsAsciiWhitespace(aChar); };
1457 struct IsWhitespaceOrComma {
1458 static bool Test(char aChar) {
1459 return aChar == ',' || NS_IsAsciiWhitespace(aChar);
1463 template <typename Predicate>
1464 uint32_t SkipPast(const nsCString& str, uint32_t base) {
1465 while (base < str.Length() && Predicate::Test(str[base])) {
1466 ++base;
1468 return base;
1471 template <typename Predicate>
1472 uint32_t SkipUntil(const nsCString& str, uint32_t base) {
1473 while (base < str.Length() && !Predicate::Test(str[base])) {
1474 ++base;
1476 return base;
1479 // static
1480 void nsScriptSecurityManager::ScriptSecurityPrefChanged(const char* aPref,
1481 void* aSelf) {
1482 static_cast<nsScriptSecurityManager*>(aSelf)->ScriptSecurityPrefChanged(
1483 aPref);
1486 inline void nsScriptSecurityManager::ScriptSecurityPrefChanged(
1487 const char* aPref) {
1488 MOZ_ASSERT(mPrefInitialized);
1489 mIsJavaScriptEnabled =
1490 Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled);
1491 sStrictFileOriginPolicy =
1492 Preferences::GetBool(sFileOriginPolicyPrefName, false);
1493 mFileURIAllowlist.reset();
1496 void nsScriptSecurityManager::AddSitesToFileURIAllowlist(
1497 const nsCString& aSiteList) {
1498 for (uint32_t base = SkipPast<IsWhitespace>(aSiteList, 0), bound = 0;
1499 base < aSiteList.Length();
1500 base = SkipPast<IsWhitespace>(aSiteList, bound)) {
1501 // Grab the current site.
1502 bound = SkipUntil<IsWhitespace>(aSiteList, base);
1503 nsAutoCString site(Substring(aSiteList, base, bound - base));
1505 // Check if the URI is schemeless. If so, add both http and https.
1506 nsAutoCString unused;
1507 if (NS_FAILED(sIOService->ExtractScheme(site, unused))) {
1508 AddSitesToFileURIAllowlist("http://"_ns + site);
1509 AddSitesToFileURIAllowlist("https://"_ns + site);
1510 continue;
1513 // Convert it to a URI and add it to our list.
1514 nsCOMPtr<nsIURI> uri;
1515 nsresult rv = NS_NewURI(getter_AddRefs(uri), site);
1516 if (NS_SUCCEEDED(rv)) {
1517 mFileURIAllowlist.ref().AppendElement(uri);
1518 } else {
1519 nsCOMPtr<nsIConsoleService> console(
1520 do_GetService("@mozilla.org/consoleservice;1"));
1521 if (console) {
1522 nsAutoString msg =
1523 u"Unable to to add site to file:// URI allowlist: "_ns +
1524 NS_ConvertASCIItoUTF16(site);
1525 console->LogStringMessage(msg.get());
1531 nsresult nsScriptSecurityManager::InitPrefs() {
1532 nsIPrefBranch* branch = Preferences::GetRootBranch();
1533 NS_ENSURE_TRUE(branch, NS_ERROR_FAILURE);
1535 mPrefInitialized = true;
1537 // Set the initial value of the "javascript.enabled" prefs
1538 ScriptSecurityPrefChanged();
1540 // set observer callbacks in case the value of the prefs change
1541 Preferences::RegisterPrefixCallbacks(
1542 nsScriptSecurityManager::ScriptSecurityPrefChanged, kObservedPrefs, this);
1544 return NS_OK;
1547 NS_IMETHODIMP
1548 nsScriptSecurityManager::GetDomainPolicyActive(bool* aRv) {
1549 *aRv = !!mDomainPolicy;
1550 return NS_OK;
1553 NS_IMETHODIMP
1554 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy** aRv) {
1555 if (!XRE_IsParentProcess()) {
1556 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1559 return ActivateDomainPolicyInternal(aRv);
1562 NS_IMETHODIMP
1563 nsScriptSecurityManager::ActivateDomainPolicyInternal(nsIDomainPolicy** aRv) {
1564 // We only allow one domain policy at a time. The holder of the previous
1565 // policy must explicitly deactivate it first.
1566 if (mDomainPolicy) {
1567 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1570 mDomainPolicy = new DomainPolicy();
1571 nsCOMPtr<nsIDomainPolicy> ptr = mDomainPolicy;
1572 ptr.forget(aRv);
1573 return NS_OK;
1576 // Intentionally non-scriptable. Script must have a reference to the
1577 // nsIDomainPolicy to deactivate it.
1578 void nsScriptSecurityManager::DeactivateDomainPolicy() {
1579 mDomainPolicy = nullptr;
1582 void nsScriptSecurityManager::CloneDomainPolicy(DomainPolicyClone* aClone) {
1583 MOZ_ASSERT(aClone);
1584 if (mDomainPolicy) {
1585 mDomainPolicy->CloneDomainPolicy(aClone);
1586 } else {
1587 aClone->active() = false;
1591 NS_IMETHODIMP
1592 nsScriptSecurityManager::PolicyAllowsScript(nsIURI* aURI, bool* aRv) {
1593 nsresult rv;
1595 // Compute our rule. If we don't have any domain policy set up that might
1596 // provide exceptions to this rule, we're done.
1597 *aRv = mIsJavaScriptEnabled;
1598 if (!mDomainPolicy) {
1599 return NS_OK;
1602 // We have a domain policy. Grab the appropriate set of exceptions to the
1603 // rule (either the blocklist or the allowlist, depending on whether script
1604 // is enabled or disabled by default).
1605 nsCOMPtr<nsIDomainSet> exceptions;
1606 nsCOMPtr<nsIDomainSet> superExceptions;
1607 if (*aRv) {
1608 mDomainPolicy->GetBlocklist(getter_AddRefs(exceptions));
1609 mDomainPolicy->GetSuperBlocklist(getter_AddRefs(superExceptions));
1610 } else {
1611 mDomainPolicy->GetAllowlist(getter_AddRefs(exceptions));
1612 mDomainPolicy->GetSuperAllowlist(getter_AddRefs(superExceptions));
1615 bool contains;
1616 rv = exceptions->Contains(aURI, &contains);
1617 NS_ENSURE_SUCCESS(rv, rv);
1618 if (contains) {
1619 *aRv = !*aRv;
1620 return NS_OK;
1622 rv = superExceptions->ContainsSuperDomain(aURI, &contains);
1623 NS_ENSURE_SUCCESS(rv, rv);
1624 if (contains) {
1625 *aRv = !*aRv;
1628 return NS_OK;
1631 const nsTArray<nsCOMPtr<nsIURI>>&
1632 nsScriptSecurityManager::EnsureFileURIAllowlist() {
1633 if (mFileURIAllowlist.isSome()) {
1634 return mFileURIAllowlist.ref();
1638 // Rebuild the set of principals for which we allow file:// URI loads. This
1639 // implements a small subset of an old pref-based CAPS people that people
1640 // have come to depend on. See bug 995943.
1643 mFileURIAllowlist.emplace();
1644 nsAutoCString policies;
1645 mozilla::Preferences::GetCString("capability.policy.policynames", policies);
1646 for (uint32_t base = SkipPast<IsWhitespaceOrComma>(policies, 0), bound = 0;
1647 base < policies.Length();
1648 base = SkipPast<IsWhitespaceOrComma>(policies, bound)) {
1649 // Grab the current policy name.
1650 bound = SkipUntil<IsWhitespaceOrComma>(policies, base);
1651 auto policyName = Substring(policies, base, bound - base);
1653 // Figure out if this policy allows loading file:// URIs. If not, we can
1654 // skip it.
1655 nsCString checkLoadURIPrefName =
1656 "capability.policy."_ns + policyName + ".checkloaduri.enabled"_ns;
1657 nsAutoString value;
1658 nsresult rv = Preferences::GetString(checkLoadURIPrefName.get(), value);
1659 if (NS_FAILED(rv) || !value.LowerCaseEqualsLiteral("allaccess")) {
1660 continue;
1663 // Grab the list of domains associated with this policy.
1664 nsCString domainPrefName =
1665 "capability.policy."_ns + policyName + ".sites"_ns;
1666 nsAutoCString siteList;
1667 Preferences::GetCString(domainPrefName.get(), siteList);
1668 AddSitesToFileURIAllowlist(siteList);
1671 return mFileURIAllowlist.ref();