Bumping manifests a=b2g-bump
[gecko.git] / caps / nsScriptSecurityManager.cpp
blob18c31a34d514648255b0d80e68e2e1da84c62e65
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* vim: set ts=4 et sw=4 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"
11 #include "js/OldDebugAPI.h"
12 #include "xpcprivate.h"
13 #include "XPCWrapper.h"
14 #include "nsIAppsService.h"
15 #include "nsILoadContext.h"
16 #include "nsIServiceManager.h"
17 #include "nsIScriptObjectPrincipal.h"
18 #include "nsIScriptContext.h"
19 #include "nsIURL.h"
20 #include "nsINestedURI.h"
21 #include "nspr.h"
22 #include "nsJSPrincipals.h"
23 #include "nsSystemPrincipal.h"
24 #include "nsPrincipal.h"
25 #include "nsNullPrincipal.h"
26 #include "DomainPolicy.h"
27 #include "nsXPIDLString.h"
28 #include "nsCRT.h"
29 #include "nsCRTGlue.h"
30 #include "nsError.h"
31 #include "nsDOMCID.h"
32 #include "nsIXPConnect.h"
33 #include "nsTextFormatter.h"
34 #include "nsIStringBundle.h"
35 #include "nsNetUtil.h"
36 #include "nsIEffectiveTLDService.h"
37 #include "nsIProperties.h"
38 #include "nsDirectoryServiceDefs.h"
39 #include "nsIFile.h"
40 #include "nsIFileURL.h"
41 #include "nsIZipReader.h"
42 #include "nsIXPConnect.h"
43 #include "nsIScriptGlobalObject.h"
44 #include "nsPIDOMWindow.h"
45 #include "nsIDocShell.h"
46 #include "nsIPrompt.h"
47 #include "nsIWindowWatcher.h"
48 #include "nsIConsoleService.h"
49 #include "nsIJSRuntimeService.h"
50 #include "nsIObserverService.h"
51 #include "nsIContent.h"
52 #include "nsAutoPtr.h"
53 #include "nsDOMJSUtils.h"
54 #include "nsAboutProtocolUtils.h"
55 #include "nsIClassInfo.h"
56 #include "nsIURIFixup.h"
57 #include "nsCDefaultURIFixup.h"
58 #include "nsIChromeRegistry.h"
59 #include "nsIContentSecurityPolicy.h"
60 #include "nsIAsyncVerifyRedirectCallback.h"
61 #include "mozIApplication.h"
62 #include "mozilla/Preferences.h"
63 #include "mozilla/dom/BindingUtils.h"
64 #include <stdint.h>
65 #include "mozilla/dom/ScriptSettings.h"
66 #include "mozilla/ClearOnShutdown.h"
67 #include "mozilla/StaticPtr.h"
68 #include "nsContentUtils.h"
69 #include "nsJSUtils.h"
70 #include "nsILoadInfo.h"
72 // This should be probably defined on some other place... but I couldn't find it
73 #define WEBAPPS_PERM_NAME "webapps-manage"
75 using namespace mozilla;
76 using namespace mozilla::dom;
78 nsIIOService *nsScriptSecurityManager::sIOService = nullptr;
79 nsIStringBundle *nsScriptSecurityManager::sStrBundle = nullptr;
80 JSRuntime *nsScriptSecurityManager::sRuntime = 0;
81 bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
83 ///////////////////////////
84 // Convenience Functions //
85 ///////////////////////////
87 class nsAutoInPrincipalDomainOriginSetter {
88 public:
89 nsAutoInPrincipalDomainOriginSetter() {
90 ++sInPrincipalDomainOrigin;
92 ~nsAutoInPrincipalDomainOriginSetter() {
93 --sInPrincipalDomainOrigin;
95 static uint32_t sInPrincipalDomainOrigin;
97 uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
99 static
100 nsresult
101 GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin)
103 if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin > 1) {
104 // Allow a single recursive call to GetPrincipalDomainOrigin, since that
105 // might be happening on a different principal from the first call. But
106 // after that, cut off the recursion; it just indicates that something
107 // we're doing in this method causes us to reenter a security check here.
108 return NS_ERROR_NOT_AVAILABLE;
111 nsAutoInPrincipalDomainOriginSetter autoSetter;
113 nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI);
114 NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
116 nsAutoCString hostPort;
118 nsresult rv = uri->GetHostPort(hostPort);
119 if (NS_SUCCEEDED(rv)) {
120 nsAutoCString scheme;
121 rv = uri->GetScheme(scheme);
122 NS_ENSURE_SUCCESS(rv, rv);
123 aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort;
125 else {
126 // Some URIs (e.g., nsSimpleURI) don't support host. Just
127 // get the full spec.
128 rv = uri->GetSpec(aOrigin);
129 NS_ENSURE_SUCCESS(rv, rv);
132 return NS_OK;
135 static
136 nsresult
137 GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
138 nsACString& aOrigin)
141 nsCOMPtr<nsIURI> uri;
142 aPrincipal->GetDomain(getter_AddRefs(uri));
143 if (!uri) {
144 aPrincipal->GetURI(getter_AddRefs(uri));
146 NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
148 return GetOriginFromURI(uri, aOrigin);
151 inline void SetPendingException(JSContext *cx, const char *aMsg)
153 JS_ReportError(cx, "%s", aMsg);
156 inline void SetPendingException(JSContext *cx, const char16_t *aMsg)
158 JS_ReportError(cx, "%hs", aMsg);
161 // Helper class to get stuff from the ClassInfo and not waste extra time with
162 // virtual method calls for things it has already gotten
163 class ClassInfoData
165 public:
166 ClassInfoData(nsIClassInfo *aClassInfo, const char *aName)
167 : mClassInfo(aClassInfo),
168 mName(const_cast<char *>(aName)),
169 mDidGetFlags(false),
170 mMustFreeName(false)
174 ~ClassInfoData()
176 if (mMustFreeName)
177 nsMemory::Free(mName);
180 uint32_t GetFlags()
182 if (!mDidGetFlags) {
183 if (mClassInfo) {
184 nsresult rv = mClassInfo->GetFlags(&mFlags);
185 if (NS_FAILED(rv)) {
186 mFlags = 0;
188 } else {
189 mFlags = 0;
192 mDidGetFlags = true;
195 return mFlags;
198 bool IsDOMClass()
200 return !!(GetFlags() & nsIClassInfo::DOM_OBJECT);
203 const char* GetName()
205 if (!mName) {
206 if (mClassInfo) {
207 mClassInfo->GetClassDescription(&mName);
210 if (mName) {
211 mMustFreeName = true;
212 } else {
213 mName = const_cast<char *>("UnnamedClass");
217 return mName;
220 private:
221 nsIClassInfo *mClassInfo; // WEAK
222 uint32_t mFlags;
223 char *mName;
224 bool mDidGetFlags;
225 bool mMustFreeName;
228 JSContext *
229 nsScriptSecurityManager::GetCurrentJSContext()
231 // Get JSContext from stack.
232 return nsXPConnect::XPConnect()->GetCurrentJSContext();
235 JSContext *
236 nsScriptSecurityManager::GetSafeJSContext()
238 // Get JSContext from stack.
239 return nsXPConnect::XPConnect()->GetSafeJSContext();
242 /* static */
243 bool
244 nsScriptSecurityManager::SecurityCompareURIs(nsIURI* aSourceURI,
245 nsIURI* aTargetURI)
247 return NS_SecurityCompareURIs(aSourceURI, aTargetURI, sStrictFileOriginPolicy);
250 // SecurityHashURI is consistent with SecurityCompareURIs because NS_SecurityHashURI
251 // is consistent with NS_SecurityCompareURIs. See nsNetUtil.h.
252 uint32_t
253 nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI)
255 return NS_SecurityHashURI(aURI);
258 uint16_t
259 nsScriptSecurityManager::AppStatusForPrincipal(nsIPrincipal *aPrin)
261 uint32_t appId = aPrin->GetAppId();
262 bool inMozBrowser = aPrin->GetIsInBrowserElement();
263 NS_WARN_IF_FALSE(appId != nsIScriptSecurityManager::UNKNOWN_APP_ID,
264 "Asking for app status on a principal with an unknown app id");
265 // Installed apps have a valid app id (not NO_APP_ID or UNKNOWN_APP_ID)
266 // and they are not inside a mozbrowser.
267 if (appId == nsIScriptSecurityManager::NO_APP_ID ||
268 appId == nsIScriptSecurityManager::UNKNOWN_APP_ID || inMozBrowser)
270 return nsIPrincipal::APP_STATUS_NOT_INSTALLED;
273 nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID);
274 NS_ENSURE_TRUE(appsService, nsIPrincipal::APP_STATUS_NOT_INSTALLED);
276 nsCOMPtr<mozIApplication> app;
277 appsService->GetAppByLocalId(appId, getter_AddRefs(app));
278 NS_ENSURE_TRUE(app, nsIPrincipal::APP_STATUS_NOT_INSTALLED);
280 uint16_t status = nsIPrincipal::APP_STATUS_INSTALLED;
281 NS_ENSURE_SUCCESS(app->GetAppStatus(&status),
282 nsIPrincipal::APP_STATUS_NOT_INSTALLED);
284 nsAutoCString origin;
285 NS_ENSURE_SUCCESS(aPrin->GetOrigin(getter_Copies(origin)),
286 nsIPrincipal::APP_STATUS_NOT_INSTALLED);
287 nsString appOrigin;
288 NS_ENSURE_SUCCESS(app->GetOrigin(appOrigin),
289 nsIPrincipal::APP_STATUS_NOT_INSTALLED);
291 // We go from string -> nsIURI -> origin to be sure we
292 // compare two punny-encoded origins.
293 nsCOMPtr<nsIURI> appURI;
294 NS_ENSURE_SUCCESS(NS_NewURI(getter_AddRefs(appURI), appOrigin),
295 nsIPrincipal::APP_STATUS_NOT_INSTALLED);
297 nsAutoCString appOriginPunned;
298 NS_ENSURE_SUCCESS(nsPrincipal::GetOriginForURI(appURI, getter_Copies(appOriginPunned)),
299 nsIPrincipal::APP_STATUS_NOT_INSTALLED);
301 if (!appOriginPunned.Equals(origin)) {
302 return nsIPrincipal::APP_STATUS_NOT_INSTALLED;
305 return status;
309 NS_IMETHODIMP
310 nsScriptSecurityManager::GetChannelPrincipal(nsIChannel* aChannel,
311 nsIPrincipal** aPrincipal)
313 NS_PRECONDITION(aChannel, "Must have channel!");
314 nsCOMPtr<nsISupports> owner;
315 aChannel->GetOwner(getter_AddRefs(owner));
316 if (owner) {
317 CallQueryInterface(owner, aPrincipal);
318 if (*aPrincipal) {
319 return NS_OK;
323 // Check whether we have an nsILoadInfo that says what we should do.
324 nsCOMPtr<nsILoadInfo> loadInfo;
325 aChannel->GetLoadInfo(getter_AddRefs(loadInfo));
326 if (loadInfo) {
327 if (loadInfo->GetLoadingSandboxed()) {
328 nsRefPtr<nsNullPrincipal> prin =
329 nsNullPrincipal::CreateWithInheritedAttributes(loadInfo->LoadingPrincipal());
330 NS_ENSURE_TRUE(prin, NS_ERROR_FAILURE);
331 prin.forget(aPrincipal);
332 return NS_OK;
335 if (loadInfo->GetForceInheritPrincipal()) {
336 NS_ADDREF(*aPrincipal = loadInfo->LoadingPrincipal());
337 return NS_OK;
341 // OK, get the principal from the URI. Make sure this does the same thing
342 // as nsDocument::Reset and XULDocument::StartDocumentLoad.
343 nsCOMPtr<nsIURI> uri;
344 nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
345 NS_ENSURE_SUCCESS(rv, rv);
348 nsCOMPtr<nsILoadContext> loadContext;
349 NS_QueryNotificationCallbacks(aChannel, loadContext);
351 if (loadContext) {
352 return GetLoadContextCodebasePrincipal(uri, loadContext, aPrincipal);
355 return GetCodebasePrincipalInternal(uri, UNKNOWN_APP_ID,
356 /* isInBrowserElement */ false, aPrincipal);
359 NS_IMETHODIMP
360 nsScriptSecurityManager::IsSystemPrincipal(nsIPrincipal* aPrincipal,
361 bool* aIsSystem)
363 *aIsSystem = (aPrincipal == mSystemPrincipal);
364 return NS_OK;
367 /////////////////////////////
368 // nsScriptSecurityManager //
369 /////////////////////////////
371 ////////////////////////////////////
372 // Methods implementing ISupports //
373 ////////////////////////////////////
374 NS_IMPL_ISUPPORTS(nsScriptSecurityManager,
375 nsIScriptSecurityManager,
376 nsIChannelEventSink,
377 nsIObserver)
379 ///////////////////////////////////////////////////
380 // Methods implementing nsIScriptSecurityManager //
381 ///////////////////////////////////////////////////
383 ///////////////// Security Checks /////////////////
385 bool
386 nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx)
388 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
389 nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
390 nsCOMPtr<nsIContentSecurityPolicy> csp;
391 nsresult rv = subjectPrincipal->GetCsp(getter_AddRefs(csp));
392 NS_ASSERTION(NS_SUCCEEDED(rv), "CSP: Failed to get CSP from principal.");
394 // don't do anything unless there's a CSP
395 if (!csp)
396 return true;
398 bool evalOK = true;
399 bool reportViolation = false;
400 rv = csp->GetAllowsEval(&reportViolation, &evalOK);
402 if (NS_FAILED(rv))
404 NS_WARNING("CSP: failed to get allowsEval");
405 return true; // fail open to not break sites.
408 if (reportViolation) {
409 nsAutoString fileName;
410 unsigned lineNum = 0;
411 NS_NAMED_LITERAL_STRING(scriptSample, "call to eval() or related function blocked by CSP");
413 JS::AutoFilename scriptFilename;
414 if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum)) {
415 if (const char *file = scriptFilename.get()) {
416 CopyUTF8toUTF16(nsDependentCString(file), fileName);
419 csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
420 fileName,
421 scriptSample,
422 lineNum,
423 EmptyString(),
424 EmptyString());
427 return evalOK;
430 // static
431 bool
432 nsScriptSecurityManager::JSPrincipalsSubsume(JSPrincipals *first,
433 JSPrincipals *second)
435 return nsJSPrincipals::get(first)->Subsumes(nsJSPrincipals::get(second));
438 NS_IMETHODIMP
439 nsScriptSecurityManager::CheckSameOrigin(JSContext* cx,
440 nsIURI* aTargetURI)
442 MOZ_ASSERT_IF(cx, cx == nsContentUtils::GetCurrentJSContext());
444 // Get a principal from the context
445 nsIPrincipal* sourcePrincipal = nsContentUtils::SubjectPrincipal();
446 if (sourcePrincipal == mSystemPrincipal)
448 // This is a system (chrome) script, so allow access
449 return NS_OK;
452 // Get the original URI from the source principal.
453 // This has the effect of ignoring any change to document.domain
454 // which must be done to avoid DNS spoofing (bug 154930)
455 nsCOMPtr<nsIURI> sourceURI;
456 sourcePrincipal->GetDomain(getter_AddRefs(sourceURI));
457 if (!sourceURI) {
458 sourcePrincipal->GetURI(getter_AddRefs(sourceURI));
459 NS_ENSURE_TRUE(sourceURI, NS_ERROR_FAILURE);
462 // Compare origins
463 if (!SecurityCompareURIs(sourceURI, aTargetURI))
465 ReportError(cx, NS_LITERAL_STRING("CheckSameOriginError"), sourceURI, aTargetURI);
466 return NS_ERROR_DOM_BAD_URI;
468 return NS_OK;
471 NS_IMETHODIMP
472 nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
473 nsIURI* aTargetURI,
474 bool reportError)
476 if (!SecurityCompareURIs(aSourceURI, aTargetURI))
478 if (reportError) {
479 ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"),
480 aSourceURI, aTargetURI);
482 return NS_ERROR_DOM_BAD_URI;
484 return NS_OK;
487 /*static*/ uint32_t
488 nsScriptSecurityManager::HashPrincipalByOrigin(nsIPrincipal* aPrincipal)
490 nsCOMPtr<nsIURI> uri;
491 aPrincipal->GetDomain(getter_AddRefs(uri));
492 if (!uri)
493 aPrincipal->GetURI(getter_AddRefs(uri));
494 return SecurityHashURI(uri);
497 /* static */ bool
498 nsScriptSecurityManager::AppAttributesEqual(nsIPrincipal* aFirst,
499 nsIPrincipal* aSecond)
501 MOZ_ASSERT(aFirst && aSecond, "Don't pass null pointers!");
503 uint32_t firstAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
504 if (!aFirst->GetUnknownAppId()) {
505 firstAppId = aFirst->GetAppId();
508 uint32_t secondAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
509 if (!aSecond->GetUnknownAppId()) {
510 secondAppId = aSecond->GetAppId();
513 return ((firstAppId == secondAppId) &&
514 (aFirst->GetIsInBrowserElement() == aSecond->GetIsInBrowserElement()));
517 NS_IMETHODIMP
518 nsScriptSecurityManager::CheckLoadURIFromScript(JSContext *cx, nsIURI *aURI)
520 // Get principal of currently executing script.
521 MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
522 nsIPrincipal* principal = nsContentUtils::SubjectPrincipal();
523 nsresult rv = CheckLoadURIWithPrincipal(principal, aURI,
524 nsIScriptSecurityManager::STANDARD);
525 if (NS_SUCCEEDED(rv)) {
526 // OK to load
527 return NS_OK;
530 // See if we're attempting to load a file: URI. If so, let a
531 // UniversalXPConnect capability trump the above check.
532 bool isFile = false;
533 bool isRes = false;
534 if (NS_FAILED(aURI->SchemeIs("file", &isFile)) ||
535 NS_FAILED(aURI->SchemeIs("resource", &isRes)))
536 return NS_ERROR_FAILURE;
537 if (isFile || isRes)
539 if (nsContentUtils::IsCallerChrome())
540 return NS_OK;
543 // Report error.
544 nsAutoCString spec;
545 if (NS_FAILED(aURI->GetAsciiSpec(spec)))
546 return NS_ERROR_FAILURE;
547 nsAutoCString msg("Access to '");
548 msg.Append(spec);
549 msg.AppendLiteral("' from script denied");
550 SetPendingException(cx, msg.get());
551 return NS_ERROR_DOM_BAD_URI;
555 * Helper method to handle cases where a flag passed to
556 * CheckLoadURIWithPrincipal means denying loading if the given URI has certain
557 * nsIProtocolHandler flags set.
558 * @return if success, access is allowed. Otherwise, deny access
560 static nsresult
561 DenyAccessIfURIHasFlags(nsIURI* aURI, uint32_t aURIFlags)
563 NS_PRECONDITION(aURI, "Must have URI!");
565 bool uriHasFlags;
566 nsresult rv =
567 NS_URIChainHasFlags(aURI, aURIFlags, &uriHasFlags);
568 NS_ENSURE_SUCCESS(rv, rv);
570 if (uriHasFlags) {
571 return NS_ERROR_DOM_BAD_URI;
574 return NS_OK;
577 static bool
578 EqualOrSubdomain(nsIURI* aProbeArg, nsIURI* aBase)
580 // Make a clone of the incoming URI, because we're going to mutate it.
581 nsCOMPtr<nsIURI> probe;
582 nsresult rv = aProbeArg->Clone(getter_AddRefs(probe));
583 NS_ENSURE_SUCCESS(rv, false);
585 nsCOMPtr<nsIEffectiveTLDService> tldService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
586 NS_ENSURE_TRUE(tldService, false);
587 while (true) {
588 if (nsScriptSecurityManager::SecurityCompareURIs(probe, aBase)) {
589 return true;
592 nsAutoCString host, newHost;
593 nsresult rv = probe->GetHost(host);
594 NS_ENSURE_SUCCESS(rv, false);
596 rv = tldService->GetNextSubDomain(host, newHost);
597 if (rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
598 return false;
600 NS_ENSURE_SUCCESS(rv, false);
601 rv = probe->SetHost(newHost);
602 NS_ENSURE_SUCCESS(rv, false);
606 NS_IMETHODIMP
607 nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal* aPrincipal,
608 nsIURI *aTargetURI,
609 uint32_t aFlags)
611 NS_PRECONDITION(aPrincipal, "CheckLoadURIWithPrincipal must have a principal");
612 // If someone passes a flag that we don't understand, we should
613 // fail, because they may need a security check that we don't
614 // provide.
615 NS_ENSURE_FALSE(aFlags & ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
616 nsIScriptSecurityManager::ALLOW_CHROME |
617 nsIScriptSecurityManager::DISALLOW_SCRIPT |
618 nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL |
619 nsIScriptSecurityManager::DONT_REPORT_ERRORS),
620 NS_ERROR_UNEXPECTED);
621 NS_ENSURE_ARG_POINTER(aPrincipal);
622 NS_ENSURE_ARG_POINTER(aTargetURI);
624 // If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
625 // would do such inheriting. That would be URIs that do not have their own
626 // security context. We do this even for the system principal.
627 if (aFlags & nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL) {
628 nsresult rv =
629 DenyAccessIfURIHasFlags(aTargetURI,
630 nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT);
631 NS_ENSURE_SUCCESS(rv, rv);
634 if (aPrincipal == mSystemPrincipal) {
635 // Allow access
636 return NS_OK;
639 nsCOMPtr<nsIURI> sourceURI;
640 aPrincipal->GetURI(getter_AddRefs(sourceURI));
641 if (!sourceURI) {
642 nsCOMPtr<nsIExpandedPrincipal> expanded = do_QueryInterface(aPrincipal);
643 if (expanded) {
644 nsTArray< nsCOMPtr<nsIPrincipal> > *whiteList;
645 expanded->GetWhiteList(&whiteList);
646 for (uint32_t i = 0; i < whiteList->Length(); ++i) {
647 nsresult rv = CheckLoadURIWithPrincipal((*whiteList)[i],
648 aTargetURI,
649 aFlags);
650 if (NS_SUCCEEDED(rv)) {
651 // Allow access if it succeeded with one of the white listed principals
652 return NS_OK;
655 // None of our whitelisted principals worked.
656 return NS_ERROR_DOM_BAD_URI;
658 NS_ERROR("Non-system principals or expanded principal passed to CheckLoadURIWithPrincipal "
659 "must have a URI!");
660 return NS_ERROR_UNEXPECTED;
663 // Automatic loads are not allowed from certain protocols.
664 if (aFlags & nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT) {
665 nsresult rv =
666 DenyAccessIfURIHasFlags(sourceURI,
667 nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT);
668 NS_ENSURE_SUCCESS(rv, rv);
671 // If either URI is a nested URI, get the base URI
672 nsCOMPtr<nsIURI> sourceBaseURI = NS_GetInnermostURI(sourceURI);
673 nsCOMPtr<nsIURI> targetBaseURI = NS_GetInnermostURI(aTargetURI);
675 //-- get the target scheme
676 nsAutoCString targetScheme;
677 nsresult rv = targetBaseURI->GetScheme(targetScheme);
678 if (NS_FAILED(rv)) return rv;
680 //-- Some callers do not allow loading javascript:
681 if ((aFlags & nsIScriptSecurityManager::DISALLOW_SCRIPT) &&
682 targetScheme.EqualsLiteral("javascript"))
684 return NS_ERROR_DOM_BAD_URI;
687 NS_NAMED_LITERAL_STRING(errorTag, "CheckLoadURIError");
688 bool reportErrors = !(aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS);
690 // Check for uris that are only loadable by principals that subsume them
691 bool hasFlags;
692 rv = NS_URIChainHasFlags(targetBaseURI,
693 nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS,
694 &hasFlags);
695 NS_ENSURE_SUCCESS(rv, rv);
697 if (hasFlags) {
698 return aPrincipal->CheckMayLoad(targetBaseURI, true, false);
701 //-- get the source scheme
702 nsAutoCString sourceScheme;
703 rv = sourceBaseURI->GetScheme(sourceScheme);
704 if (NS_FAILED(rv)) return rv;
706 if (sourceScheme.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME)) {
707 // A null principal can target its own URI.
708 if (sourceURI == aTargetURI) {
709 return NS_OK;
712 else if (targetScheme.Equals(sourceScheme,
713 nsCaseInsensitiveCStringComparator()))
715 // every scheme can access another URI from the same scheme,
716 // as long as they don't represent null principals...
717 // Or they don't require an special permission to do so
718 // See bug#773886
720 bool hasFlags;
721 rv = NS_URIChainHasFlags(targetBaseURI,
722 nsIProtocolHandler::URI_CROSS_ORIGIN_NEEDS_WEBAPPS_PERM,
723 &hasFlags);
724 NS_ENSURE_SUCCESS(rv, rv);
726 if (hasFlags) {
727 // Let apps load the whitelisted theme resources even if they don't
728 // have the webapps-manage permission but have the themeable one.
729 // Resources from the theme origin are also allowed to load from
730 // the theme origin (eg. stylesheets using images from the theme).
731 auto themeOrigin = Preferences::GetCString("b2g.theme.origin");
732 if (themeOrigin) {
733 nsAutoCString targetOrigin;
734 nsPrincipal::GetOriginForURI(targetBaseURI, getter_Copies(targetOrigin));
735 if (targetOrigin.Equals(themeOrigin)) {
736 nsAutoCString pOrigin;
737 aPrincipal->GetOrigin(getter_Copies(pOrigin));
738 return nsContentUtils::IsExactSitePermAllow(aPrincipal, "themeable") ||
739 pOrigin.Equals(themeOrigin)
740 ? NS_OK : NS_ERROR_DOM_BAD_URI;
743 // In this case, we allow opening only if the source and target URIS
744 // are on the same domain, or the opening URI has the webapps
745 // permision granted
746 if (!SecurityCompareURIs(sourceBaseURI, targetBaseURI) &&
747 !nsContentUtils::IsExactSitePermAllow(aPrincipal, WEBAPPS_PERM_NAME)) {
748 return NS_ERROR_DOM_BAD_URI;
751 return NS_OK;
754 // If the schemes don't match, the policy is specified by the protocol
755 // flags on the target URI. Note that the order of policy checks here is
756 // very important! We start from most restrictive and work our way down.
757 // Note that since we're working with the innermost URI, we can just use
758 // the methods that work on chains of nested URIs and they will only look
759 // at the flags for our one URI.
761 // Check for system target URI
762 rv = DenyAccessIfURIHasFlags(targetBaseURI,
763 nsIProtocolHandler::URI_DANGEROUS_TO_LOAD);
764 if (NS_FAILED(rv)) {
765 // Deny access, since the origin principal is not system
766 if (reportErrors) {
767 ReportError(nullptr, errorTag, sourceURI, aTargetURI);
769 return rv;
772 // Check for chrome target URI
773 rv = NS_URIChainHasFlags(targetBaseURI,
774 nsIProtocolHandler::URI_IS_UI_RESOURCE,
775 &hasFlags);
776 NS_ENSURE_SUCCESS(rv, rv);
777 if (hasFlags) {
778 if (aFlags & nsIScriptSecurityManager::ALLOW_CHROME) {
779 if (!targetScheme.EqualsLiteral("chrome")) {
780 // for now don't change behavior for resource: or moz-icon:
781 return NS_OK;
784 // allow load only if chrome package is whitelisted
785 nsCOMPtr<nsIXULChromeRegistry> reg(do_GetService(
786 NS_CHROMEREGISTRY_CONTRACTID));
787 if (reg) {
788 bool accessAllowed = false;
789 reg->AllowContentToAccess(targetBaseURI, &accessAllowed);
790 if (accessAllowed) {
791 return NS_OK;
796 // resource: and chrome: are equivalent, securitywise
797 // That's bogus!! Fix this. But watch out for
798 // the view-source stylesheet?
799 bool sourceIsChrome;
800 rv = NS_URIChainHasFlags(sourceBaseURI,
801 nsIProtocolHandler::URI_IS_UI_RESOURCE,
802 &sourceIsChrome);
803 NS_ENSURE_SUCCESS(rv, rv);
804 if (sourceIsChrome) {
805 return NS_OK;
807 if (reportErrors) {
808 ReportError(nullptr, errorTag, sourceURI, aTargetURI);
810 return NS_ERROR_DOM_BAD_URI;
813 // Check for target URI pointing to a file
814 rv = NS_URIChainHasFlags(targetBaseURI,
815 nsIProtocolHandler::URI_IS_LOCAL_FILE,
816 &hasFlags);
817 NS_ENSURE_SUCCESS(rv, rv);
818 if (hasFlags) {
819 // Allow domains that were whitelisted in the prefs. In 99.9% of cases,
820 // this array is empty.
821 for (size_t i = 0; i < mFileURIWhitelist.Length(); ++i) {
822 if (EqualOrSubdomain(sourceURI, mFileURIWhitelist[i])) {
823 return NS_OK;
827 // resource: and chrome: are equivalent, securitywise
828 // That's bogus!! Fix this. But watch out for
829 // the view-source stylesheet?
830 bool sourceIsChrome;
831 rv = NS_URIChainHasFlags(sourceURI,
832 nsIProtocolHandler::URI_IS_UI_RESOURCE,
833 &sourceIsChrome);
834 NS_ENSURE_SUCCESS(rv, rv);
835 if (sourceIsChrome) {
836 return NS_OK;
839 if (reportErrors) {
840 ReportError(nullptr, errorTag, sourceURI, aTargetURI);
842 return NS_ERROR_DOM_BAD_URI;
845 // OK, everyone is allowed to load this, since unflagged handlers are
846 // deprecated but treated as URI_LOADABLE_BY_ANYONE. But check whether we
847 // need to warn. At some point we'll want to make this warning into an
848 // error and treat unflagged handlers as URI_DANGEROUS_TO_LOAD.
849 rv = NS_URIChainHasFlags(targetBaseURI,
850 nsIProtocolHandler::URI_LOADABLE_BY_ANYONE,
851 &hasFlags);
852 NS_ENSURE_SUCCESS(rv, rv);
853 if (!hasFlags) {
854 nsXPIDLString message;
855 NS_ConvertASCIItoUTF16 ucsTargetScheme(targetScheme);
856 const char16_t* formatStrings[] = { ucsTargetScheme.get() };
857 rv = sStrBundle->
858 FormatStringFromName(MOZ_UTF16("ProtocolFlagError"),
859 formatStrings,
860 ArrayLength(formatStrings),
861 getter_Copies(message));
862 if (NS_SUCCEEDED(rv)) {
863 nsCOMPtr<nsIConsoleService> console(
864 do_GetService("@mozilla.org/consoleservice;1"));
865 NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
867 console->LogStringMessage(message.get());
871 return NS_OK;
874 nsresult
875 nsScriptSecurityManager::ReportError(JSContext* cx, const nsAString& messageTag,
876 nsIURI* aSource, nsIURI* aTarget)
878 nsresult rv;
879 NS_ENSURE_TRUE(aSource && aTarget, NS_ERROR_NULL_POINTER);
881 // Get the source URL spec
882 nsAutoCString sourceSpec;
883 rv = aSource->GetAsciiSpec(sourceSpec);
884 NS_ENSURE_SUCCESS(rv, rv);
886 // Get the target URL spec
887 nsAutoCString targetSpec;
888 rv = aTarget->GetAsciiSpec(targetSpec);
889 NS_ENSURE_SUCCESS(rv, rv);
891 // Localize the error message
892 nsXPIDLString message;
893 NS_ConvertASCIItoUTF16 ucsSourceSpec(sourceSpec);
894 NS_ConvertASCIItoUTF16 ucsTargetSpec(targetSpec);
895 const char16_t *formatStrings[] = { ucsSourceSpec.get(), ucsTargetSpec.get() };
896 rv = sStrBundle->FormatStringFromName(PromiseFlatString(messageTag).get(),
897 formatStrings,
898 ArrayLength(formatStrings),
899 getter_Copies(message));
900 NS_ENSURE_SUCCESS(rv, rv);
902 // If a JS context was passed in, set a JS exception.
903 // Otherwise, print the error message directly to the JS console
904 // and to standard output
905 if (cx)
907 SetPendingException(cx, message.get());
909 else // Print directly to the console
911 nsCOMPtr<nsIConsoleService> console(
912 do_GetService("@mozilla.org/consoleservice;1"));
913 NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
915 console->LogStringMessage(message.get());
917 return NS_OK;
920 NS_IMETHODIMP
921 nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(nsIPrincipal* aPrincipal,
922 const nsACString& aTargetURIStr,
923 uint32_t aFlags)
925 nsresult rv;
926 nsCOMPtr<nsIURI> target;
927 rv = NS_NewURI(getter_AddRefs(target), aTargetURIStr,
928 nullptr, nullptr, sIOService);
929 NS_ENSURE_SUCCESS(rv, rv);
931 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags);
932 if (rv == NS_ERROR_DOM_BAD_URI) {
933 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
934 // return values.
935 return rv;
937 NS_ENSURE_SUCCESS(rv, rv);
939 // Now start testing fixup -- since aTargetURIStr is a string, not
940 // an nsIURI, we may well end up fixing it up before loading.
941 // Note: This needs to stay in sync with the nsIURIFixup api.
942 nsCOMPtr<nsIURIFixup> fixup = do_GetService(NS_URIFIXUP_CONTRACTID);
943 if (!fixup) {
944 return rv;
947 uint32_t flags[] = {
948 nsIURIFixup::FIXUP_FLAG_NONE,
949 nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS,
950 nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP,
951 nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI,
952 nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP |
953 nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI
956 for (uint32_t i = 0; i < ArrayLength(flags); ++i) {
957 rv = fixup->CreateFixupURI(aTargetURIStr, flags[i], nullptr,
958 getter_AddRefs(target));
959 NS_ENSURE_SUCCESS(rv, rv);
961 rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags);
962 if (rv == NS_ERROR_DOM_BAD_URI) {
963 // Don't warn because NS_ERROR_DOM_BAD_URI is one of the expected
964 // return values.
965 return rv;
967 NS_ENSURE_SUCCESS(rv, rv);
970 return rv;
973 bool
974 nsScriptSecurityManager::ScriptAllowed(JSObject *aGlobal)
976 MOZ_ASSERT(aGlobal);
977 MOZ_ASSERT(JS_IsGlobalObject(aGlobal) || js::IsOuterObject(aGlobal));
979 // Check the bits on the compartment private.
980 return xpc::Scriptability::Get(aGlobal).Allowed();
983 ///////////////// Principals ///////////////////////
985 NS_IMETHODIMP
986 nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **result)
988 NS_ADDREF(*result = mSystemPrincipal);
990 return NS_OK;
993 nsresult
994 nsScriptSecurityManager::CreateCodebasePrincipal(nsIURI* aURI, uint32_t aAppId,
995 bool aInMozBrowser,
996 nsIPrincipal **result)
998 // I _think_ it's safe to not create null principals here based on aURI.
999 // At least all the callers would do the right thing in those cases, as far
1000 // as I can tell. --bz
1002 nsCOMPtr<nsIURIWithPrincipal> uriPrinc = do_QueryInterface(aURI);
1003 if (uriPrinc) {
1004 nsCOMPtr<nsIPrincipal> principal;
1005 uriPrinc->GetPrincipal(getter_AddRefs(principal));
1006 if (!principal || principal == mSystemPrincipal) {
1007 return CallCreateInstance(NS_NULLPRINCIPAL_CONTRACTID, result);
1010 principal.forget(result);
1012 return NS_OK;
1015 nsRefPtr<nsPrincipal> codebase = new nsPrincipal();
1016 if (!codebase)
1017 return NS_ERROR_OUT_OF_MEMORY;
1019 nsresult rv = codebase->Init(aURI, aAppId, aInMozBrowser);
1020 if (NS_FAILED(rv))
1021 return rv;
1023 NS_ADDREF(*result = codebase);
1025 return NS_OK;
1028 NS_IMETHODIMP
1029 nsScriptSecurityManager::GetSimpleCodebasePrincipal(nsIURI* aURI,
1030 nsIPrincipal** aPrincipal)
1032 return GetCodebasePrincipalInternal(aURI,
1033 nsIScriptSecurityManager::UNKNOWN_APP_ID,
1034 false, aPrincipal);
1037 NS_IMETHODIMP
1038 nsScriptSecurityManager::GetNoAppCodebasePrincipal(nsIURI* aURI,
1039 nsIPrincipal** aPrincipal)
1041 return GetCodebasePrincipalInternal(aURI, nsIScriptSecurityManager::NO_APP_ID,
1042 false, aPrincipal);
1045 NS_IMETHODIMP
1046 nsScriptSecurityManager::GetCodebasePrincipal(nsIURI* aURI,
1047 nsIPrincipal** aPrincipal)
1049 return GetNoAppCodebasePrincipal(aURI, aPrincipal);
1052 NS_IMETHODIMP
1053 nsScriptSecurityManager::GetAppCodebasePrincipal(nsIURI* aURI,
1054 uint32_t aAppId,
1055 bool aInMozBrowser,
1056 nsIPrincipal** aPrincipal)
1058 NS_ENSURE_TRUE(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID,
1059 NS_ERROR_INVALID_ARG);
1061 return GetCodebasePrincipalInternal(aURI, aAppId, aInMozBrowser, aPrincipal);
1064 NS_IMETHODIMP
1065 nsScriptSecurityManager::
1066 GetLoadContextCodebasePrincipal(nsIURI* aURI,
1067 nsILoadContext* aLoadContext,
1068 nsIPrincipal** aPrincipal)
1070 uint32_t appId;
1071 aLoadContext->GetAppId(&appId);
1072 bool isInBrowserElement;
1073 aLoadContext->GetIsInBrowserElement(&isInBrowserElement);
1074 return GetCodebasePrincipalInternal(aURI,
1075 appId,
1076 isInBrowserElement,
1077 aPrincipal);
1080 NS_IMETHODIMP
1081 nsScriptSecurityManager::GetDocShellCodebasePrincipal(nsIURI* aURI,
1082 nsIDocShell* aDocShell,
1083 nsIPrincipal** aPrincipal)
1085 return GetCodebasePrincipalInternal(aURI,
1086 aDocShell->GetAppId(),
1087 aDocShell->GetIsInBrowserElement(),
1088 aPrincipal);
1091 nsresult
1092 nsScriptSecurityManager::GetCodebasePrincipalInternal(nsIURI *aURI,
1093 uint32_t aAppId,
1094 bool aInMozBrowser,
1095 nsIPrincipal **result)
1097 NS_ENSURE_ARG(aURI);
1099 bool inheritsPrincipal;
1100 nsresult rv =
1101 NS_URIChainHasFlags(aURI,
1102 nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
1103 &inheritsPrincipal);
1104 if (NS_FAILED(rv) || inheritsPrincipal) {
1105 return CallCreateInstance(NS_NULLPRINCIPAL_CONTRACTID, result);
1108 nsCOMPtr<nsIPrincipal> principal;
1109 rv = CreateCodebasePrincipal(aURI, aAppId, aInMozBrowser,
1110 getter_AddRefs(principal));
1111 NS_ENSURE_SUCCESS(rv, rv);
1112 NS_IF_ADDREF(*result = principal);
1114 return NS_OK;
1117 // static
1118 nsIPrincipal*
1119 nsScriptSecurityManager::doGetObjectPrincipal(JSObject *aObj)
1121 JSCompartment *compartment = js::GetObjectCompartment(aObj);
1122 JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
1123 return nsJSPrincipals::get(principals);
1126 NS_IMETHODIMP
1127 nsScriptSecurityManager::CanCreateWrapper(JSContext *cx,
1128 const nsIID &aIID,
1129 nsISupports *aObj,
1130 nsIClassInfo *aClassInfo)
1132 // XXX Special case for nsIXPCException ?
1133 ClassInfoData objClassInfo = ClassInfoData(aClassInfo, nullptr);
1134 if (objClassInfo.IsDOMClass())
1136 return NS_OK;
1139 // We give remote-XUL whitelisted domains a free pass here. See bug 932906.
1140 if (!xpc::AllowContentXBLScope(js::GetContextCompartment(cx)))
1142 return NS_OK;
1145 if (nsContentUtils::IsCallerChrome())
1147 return NS_OK;
1150 //-- Access denied, report an error
1151 NS_ConvertUTF8toUTF16 strName("CreateWrapperDenied");
1152 nsAutoCString origin;
1153 nsIPrincipal* subjectPrincipal = nsContentUtils::SubjectPrincipal();
1154 GetPrincipalDomainOrigin(subjectPrincipal, origin);
1155 NS_ConvertUTF8toUTF16 originUnicode(origin);
1156 NS_ConvertUTF8toUTF16 classInfoName(objClassInfo.GetName());
1157 const char16_t* formatStrings[] = {
1158 classInfoName.get(),
1159 originUnicode.get()
1161 uint32_t length = ArrayLength(formatStrings);
1162 if (originUnicode.IsEmpty()) {
1163 --length;
1164 } else {
1165 strName.AppendLiteral("ForOrigin");
1167 nsXPIDLString errorMsg;
1168 nsresult rv = sStrBundle->FormatStringFromName(strName.get(),
1169 formatStrings,
1170 length,
1171 getter_Copies(errorMsg));
1172 NS_ENSURE_SUCCESS(rv, rv);
1174 SetPendingException(cx, errorMsg.get());
1175 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1178 NS_IMETHODIMP
1179 nsScriptSecurityManager::CanCreateInstance(JSContext *cx,
1180 const nsCID &aCID)
1182 if (nsContentUtils::IsCallerChrome()) {
1183 return NS_OK;
1186 //-- Access denied, report an error
1187 nsAutoCString errorMsg("Permission denied to create instance of class. CID=");
1188 char cidStr[NSID_LENGTH];
1189 aCID.ToProvidedString(cidStr);
1190 errorMsg.Append(cidStr);
1191 SetPendingException(cx, errorMsg.get());
1192 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1195 NS_IMETHODIMP
1196 nsScriptSecurityManager::CanGetService(JSContext *cx,
1197 const nsCID &aCID)
1199 if (nsContentUtils::IsCallerChrome()) {
1200 return NS_OK;
1203 //-- Access denied, report an error
1204 nsAutoCString errorMsg("Permission denied to get service. CID=");
1205 char cidStr[NSID_LENGTH];
1206 aCID.ToProvidedString(cidStr);
1207 errorMsg.Append(cidStr);
1208 SetPendingException(cx, errorMsg.get());
1209 return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
1212 /////////////////////////////////////////////
1213 // Method implementing nsIChannelEventSink //
1214 /////////////////////////////////////////////
1215 NS_IMETHODIMP
1216 nsScriptSecurityManager::AsyncOnChannelRedirect(nsIChannel* oldChannel,
1217 nsIChannel* newChannel,
1218 uint32_t redirFlags,
1219 nsIAsyncVerifyRedirectCallback *cb)
1221 nsCOMPtr<nsIPrincipal> oldPrincipal;
1222 GetChannelPrincipal(oldChannel, getter_AddRefs(oldPrincipal));
1224 nsCOMPtr<nsIURI> newURI;
1225 newChannel->GetURI(getter_AddRefs(newURI));
1226 nsCOMPtr<nsIURI> newOriginalURI;
1227 newChannel->GetOriginalURI(getter_AddRefs(newOriginalURI));
1229 NS_ENSURE_STATE(oldPrincipal && newURI && newOriginalURI);
1231 const uint32_t flags =
1232 nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
1233 nsIScriptSecurityManager::DISALLOW_SCRIPT;
1234 nsresult rv = CheckLoadURIWithPrincipal(oldPrincipal, newURI, flags);
1235 if (NS_SUCCEEDED(rv) && newOriginalURI != newURI) {
1236 rv = CheckLoadURIWithPrincipal(oldPrincipal, newOriginalURI, flags);
1239 if (NS_FAILED(rv))
1240 return rv;
1242 cb->OnRedirectVerifyCallback(NS_OK);
1243 return NS_OK;
1247 /////////////////////////////////////
1248 // Method implementing nsIObserver //
1249 /////////////////////////////////////
1250 const char sJSEnabledPrefName[] = "javascript.enabled";
1251 const char sFileOriginPolicyPrefName[] =
1252 "security.fileuri.strict_origin_policy";
1254 static const char* kObservedPrefs[] = {
1255 sJSEnabledPrefName,
1256 sFileOriginPolicyPrefName,
1257 "capability.policy.",
1258 nullptr
1262 NS_IMETHODIMP
1263 nsScriptSecurityManager::Observe(nsISupports* aObject, const char* aTopic,
1264 const char16_t* aMessage)
1266 ScriptSecurityPrefChanged();
1267 return NS_OK;
1270 /////////////////////////////////////////////
1271 // Constructor, Destructor, Initialization //
1272 /////////////////////////////////////////////
1273 nsScriptSecurityManager::nsScriptSecurityManager(void)
1274 : mPrefInitialized(false)
1275 , mIsJavaScriptEnabled(false)
1277 static_assert(sizeof(intptr_t) == sizeof(void*),
1278 "intptr_t and void* have different lengths on this platform. "
1279 "This may cause a security failure with the SecurityLevel union.");
1282 nsresult nsScriptSecurityManager::Init()
1284 nsresult rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
1285 NS_ENSURE_SUCCESS(rv, rv);
1287 InitPrefs();
1289 nsCOMPtr<nsIStringBundleService> bundleService =
1290 mozilla::services::GetStringBundleService();
1291 if (!bundleService)
1292 return NS_ERROR_FAILURE;
1294 rv = bundleService->CreateBundle("chrome://global/locale/security/caps.properties", &sStrBundle);
1295 NS_ENSURE_SUCCESS(rv, rv);
1297 // Create our system principal singleton
1298 nsRefPtr<nsSystemPrincipal> system = new nsSystemPrincipal();
1299 NS_ENSURE_TRUE(system, NS_ERROR_OUT_OF_MEMORY);
1301 mSystemPrincipal = system;
1303 //-- Register security check callback in the JS engine
1304 // Currently this is used to control access to function.caller
1305 rv = nsXPConnect::XPConnect()->GetRuntime(&sRuntime);
1306 NS_ENSURE_SUCCESS(rv, rv);
1308 static const JSSecurityCallbacks securityCallbacks = {
1309 ContentSecurityPolicyPermitsJSAction,
1310 JSPrincipalsSubsume,
1313 MOZ_ASSERT(!JS_GetSecurityCallbacks(sRuntime));
1314 JS_SetSecurityCallbacks(sRuntime, &securityCallbacks);
1315 JS_InitDestroyPrincipalsCallback(sRuntime, nsJSPrincipals::Destroy);
1317 JS_SetTrustedPrincipals(sRuntime, system);
1319 return NS_OK;
1322 static StaticRefPtr<nsScriptSecurityManager> gScriptSecMan;
1324 nsScriptSecurityManager::~nsScriptSecurityManager(void)
1326 Preferences::RemoveObservers(this, kObservedPrefs);
1327 if (mDomainPolicy)
1328 mDomainPolicy->Deactivate();
1329 MOZ_ASSERT(!mDomainPolicy);
1332 void
1333 nsScriptSecurityManager::Shutdown()
1335 if (sRuntime) {
1336 JS_SetSecurityCallbacks(sRuntime, nullptr);
1337 JS_SetTrustedPrincipals(sRuntime, nullptr);
1338 sRuntime = nullptr;
1341 NS_IF_RELEASE(sIOService);
1342 NS_IF_RELEASE(sStrBundle);
1345 nsScriptSecurityManager *
1346 nsScriptSecurityManager::GetScriptSecurityManager()
1348 return gScriptSecMan;
1351 /* static */ void
1352 nsScriptSecurityManager::InitStatics()
1354 nsRefPtr<nsScriptSecurityManager> ssManager = new nsScriptSecurityManager();
1355 nsresult rv = ssManager->Init();
1356 if (NS_FAILED(rv)) {
1357 MOZ_CRASH();
1360 ClearOnShutdown(&gScriptSecMan);
1361 gScriptSecMan = ssManager;
1364 // Currently this nsGenericFactory constructor is used only from FastLoad
1365 // (XPCOM object deserialization) code, when "creating" the system principal
1366 // singleton.
1367 nsSystemPrincipal *
1368 nsScriptSecurityManager::SystemPrincipalSingletonConstructor()
1370 nsIPrincipal *sysprin = nullptr;
1371 if (gScriptSecMan)
1372 NS_ADDREF(sysprin = gScriptSecMan->mSystemPrincipal);
1373 return static_cast<nsSystemPrincipal*>(sysprin);
1376 struct IsWhitespace {
1377 static bool Test(char aChar) { return NS_IsAsciiWhitespace(aChar); };
1379 struct IsWhitespaceOrComma {
1380 static bool Test(char aChar) { return aChar == ',' || NS_IsAsciiWhitespace(aChar); };
1383 template <typename Predicate>
1384 uint32_t SkipPast(const nsCString& str, uint32_t base)
1386 while (base < str.Length() && Predicate::Test(str[base])) {
1387 ++base;
1389 return base;
1392 template <typename Predicate>
1393 uint32_t SkipUntil(const nsCString& str, uint32_t base)
1395 while (base < str.Length() && !Predicate::Test(str[base])) {
1396 ++base;
1398 return base;
1401 inline void
1402 nsScriptSecurityManager::ScriptSecurityPrefChanged()
1404 MOZ_ASSERT(mPrefInitialized);
1405 mIsJavaScriptEnabled =
1406 Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled);
1407 sStrictFileOriginPolicy =
1408 Preferences::GetBool(sFileOriginPolicyPrefName, false);
1411 // Rebuild the set of principals for which we allow file:// URI loads. This
1412 // implements a small subset of an old pref-based CAPS people that people
1413 // have come to depend on. See bug 995943.
1416 mFileURIWhitelist.Clear();
1417 auto policies = mozilla::Preferences::GetCString("capability.policy.policynames");
1418 for (uint32_t base = SkipPast<IsWhitespaceOrComma>(policies, 0), bound = 0;
1419 base < policies.Length();
1420 base = SkipPast<IsWhitespaceOrComma>(policies, bound))
1422 // Grab the current policy name.
1423 bound = SkipUntil<IsWhitespaceOrComma>(policies, base);
1424 auto policyName = Substring(policies, base, bound - base);
1426 // Figure out if this policy allows loading file:// URIs. If not, we can skip it.
1427 nsCString checkLoadURIPrefName = NS_LITERAL_CSTRING("capability.policy.") +
1428 policyName +
1429 NS_LITERAL_CSTRING(".checkloaduri.enabled");
1430 if (!Preferences::GetString(checkLoadURIPrefName.get()).LowerCaseEqualsLiteral("allaccess")) {
1431 continue;
1434 // Grab the list of domains associated with this policy.
1435 nsCString domainPrefName = NS_LITERAL_CSTRING("capability.policy.") +
1436 policyName +
1437 NS_LITERAL_CSTRING(".sites");
1438 auto siteList = Preferences::GetCString(domainPrefName.get());
1439 AddSitesToFileURIWhitelist(siteList);
1443 void
1444 nsScriptSecurityManager::AddSitesToFileURIWhitelist(const nsCString& aSiteList)
1446 for (uint32_t base = SkipPast<IsWhitespace>(aSiteList, 0), bound = 0;
1447 base < aSiteList.Length();
1448 base = SkipPast<IsWhitespace>(aSiteList, bound))
1450 // Grab the current site.
1451 bound = SkipUntil<IsWhitespace>(aSiteList, base);
1452 nsAutoCString site(Substring(aSiteList, base, bound - base));
1454 // Check if the URI is schemeless. If so, add both http and https.
1455 nsAutoCString unused;
1456 if (NS_FAILED(sIOService->ExtractScheme(site, unused))) {
1457 AddSitesToFileURIWhitelist(NS_LITERAL_CSTRING("http://") + site);
1458 AddSitesToFileURIWhitelist(NS_LITERAL_CSTRING("https://") + site);
1459 continue;
1462 // Convert it to a URI and add it to our list.
1463 nsCOMPtr<nsIURI> uri;
1464 nsresult rv = NS_NewURI(getter_AddRefs(uri), site, nullptr, nullptr, sIOService);
1465 if (NS_SUCCEEDED(rv)) {
1466 mFileURIWhitelist.AppendElement(uri);
1467 } else {
1468 nsCOMPtr<nsIConsoleService> console(do_GetService("@mozilla.org/consoleservice;1"));
1469 if (console) {
1470 nsAutoString msg = NS_LITERAL_STRING("Unable to to add site to file:// URI whitelist: ") +
1471 NS_ConvertASCIItoUTF16(site);
1472 console->LogStringMessage(msg.get());
1478 nsresult
1479 nsScriptSecurityManager::InitPrefs()
1481 nsIPrefBranch* branch = Preferences::GetRootBranch();
1482 NS_ENSURE_TRUE(branch, NS_ERROR_FAILURE);
1484 mPrefInitialized = true;
1486 // Set the initial value of the "javascript.enabled" prefs
1487 ScriptSecurityPrefChanged();
1489 // set observer callbacks in case the value of the prefs change
1490 Preferences::AddStrongObservers(this, kObservedPrefs);
1492 return NS_OK;
1495 namespace mozilla {
1497 void
1498 GetJarPrefix(uint32_t aAppId, bool aInMozBrowser, nsACString& aJarPrefix)
1500 MOZ_ASSERT(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID);
1502 if (aAppId == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
1503 aAppId = nsIScriptSecurityManager::NO_APP_ID;
1506 aJarPrefix.Truncate();
1508 // Fallback.
1509 if (aAppId == nsIScriptSecurityManager::NO_APP_ID && !aInMozBrowser) {
1510 return;
1513 // aJarPrefix = appId + "+" + { 't', 'f' } + "+";
1514 aJarPrefix.AppendInt(aAppId);
1515 aJarPrefix.Append('+');
1516 aJarPrefix.Append(aInMozBrowser ? 't' : 'f');
1517 aJarPrefix.Append('+');
1519 return;
1522 } // namespace mozilla
1524 NS_IMETHODIMP
1525 nsScriptSecurityManager::GetJarPrefix(uint32_t aAppId,
1526 bool aInMozBrowser,
1527 nsACString& aJarPrefix)
1529 MOZ_ASSERT(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID);
1531 mozilla::GetJarPrefix(aAppId, aInMozBrowser, aJarPrefix);
1532 return NS_OK;
1535 NS_IMETHODIMP
1536 nsScriptSecurityManager::GetDomainPolicyActive(bool *aRv)
1538 *aRv = !!mDomainPolicy;
1539 return NS_OK;
1542 NS_IMETHODIMP
1543 nsScriptSecurityManager::ActivateDomainPolicy(nsIDomainPolicy** aRv)
1545 // We only allow one domain policy at a time. The holder of the previous
1546 // policy must explicitly deactivate it first.
1547 if (mDomainPolicy) {
1548 return NS_ERROR_SERVICE_NOT_AVAILABLE;
1551 mDomainPolicy = new DomainPolicy();
1552 nsCOMPtr<nsIDomainPolicy> ptr = mDomainPolicy;
1553 ptr.forget(aRv);
1554 return NS_OK;
1557 // Intentionally non-scriptable. Script must have a reference to the
1558 // nsIDomainPolicy to deactivate it.
1559 void
1560 nsScriptSecurityManager::DeactivateDomainPolicy()
1562 mDomainPolicy = nullptr;
1565 NS_IMETHODIMP
1566 nsScriptSecurityManager::PolicyAllowsScript(nsIURI* aURI, bool *aRv)
1568 nsresult rv;
1570 // Compute our rule. If we don't have any domain policy set up that might
1571 // provide exceptions to this rule, we're done.
1572 *aRv = mIsJavaScriptEnabled;
1573 if (!mDomainPolicy) {
1574 return NS_OK;
1577 // We have a domain policy. Grab the appropriate set of exceptions to the
1578 // rule (either the blacklist or the whitelist, depending on whether script
1579 // is enabled or disabled by default).
1580 nsCOMPtr<nsIDomainSet> exceptions;
1581 nsCOMPtr<nsIDomainSet> superExceptions;
1582 if (*aRv) {
1583 mDomainPolicy->GetBlacklist(getter_AddRefs(exceptions));
1584 mDomainPolicy->GetSuperBlacklist(getter_AddRefs(superExceptions));
1585 } else {
1586 mDomainPolicy->GetWhitelist(getter_AddRefs(exceptions));
1587 mDomainPolicy->GetSuperWhitelist(getter_AddRefs(superExceptions));
1590 bool contains;
1591 rv = exceptions->Contains(aURI, &contains);
1592 NS_ENSURE_SUCCESS(rv, rv);
1593 if (contains) {
1594 *aRv = !*aRv;
1595 return NS_OK;
1597 rv = superExceptions->ContainsSuperDomain(aURI, &contains);
1598 NS_ENSURE_SUCCESS(rv, rv);
1599 if (contains) {
1600 *aRv = !*aRv;
1603 return NS_OK;