Files
palemoon27/caps/BasePrincipal.cpp
T
roytam1 37dc78596e import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1203058 - Set the paint sync id on the top-level window rather than the tab's window, because then it won't get lost during page unload. r=rbarker (977f8909e2)
- Bug 1199283 - nsContentUtils::sIsFrameTimingPrefEnabled should default to false. r=smaug (510c4c4ed1)
- Bug 1237714.  Make nsContentUtils::IsCustomElementName faster in the common case of a non-custom-element name.  r=smaug (397409f308)
- Bug 1237831 - Use a non-format argument in LogMessageToConsole. r=jst (cc9d2cd390)
- Bug 1208517 - Use the legacy opt-out in CanAccessNativeAnon for now to avoid crashes. r=me (79bd55b387)
- Bug 1230353: P1. Ensure type and subtype of MIME are lowercase. r=bz (09f9a067a6)
- Bug 1230353: P2. Update webref test expected results. r=karlt (4c10a9604c)
- Bug 1227906 - Use unicode flag in pattern attribute. r=jst (d5b4fbae46)
- Bug 1223041 - Emit console warning when document.execCommand('copy'/'cut') is triggered outside of a short-lived user-initiated event, r=bz (b590f3eb86)
- Bug 1235159 - Report pattern compliation failure to web console. r=jst,jorendorff (f4b1ddd863)
- Bug 1000004 - Part a: Remove the unused nsContentUtils::HasPluginWithUncontrolledEventDispatch(nsIDocument*) function; r=jst (d873b1a93e)
- Bug 1000004 - Part b: Inline CheckForWindowedPlugins in its only caller; r=jst (f9a2e5cf64)
- Bug 583170 - Handling IPv6 literal address differently to other browsers r=bz (92abdd56ac)
- Bug 1225829 - Use a temporary string to avoid string type confusion via references. r=jimm (47ae4a8b37)
- Bug 1209841 - Support mouse long tap in SendMouseEvent(). r=smaug (23f308d336)
- Bug 1230563 - Part 1: Cookie permissions should override the CookiesL ifetimePolicy, r=ehsan (d7ecd5e7e0)
- Bug 1230563 - Part 2: Test for corrected cookie permission behavior, r=ehsan (f22ef46565)
- Bug 1241078 - Only treat items as backface hidden if they are 3D-transformed. r=tlee (c52f6804cc)
- Bug 1233098 - Refactor CSP upgrade insecure requests flag within loadInfo (r=sicking) (816d36e5d8)
- remove specific PM hack (a0ed71f7f4)
- Bug 1239397: Send Internal ContentPolicyType to CSP and MixedContent (r=sicking) (7c8da2f1df)
- Bug 1236258 part 1. Remove the unused nsDOMAttributeMap::RemoveAttribute. r=smaug (968d788197)
- Bug 1236258 part 3. Remove the unused aNsAware argument of nsDOMAttributeMap::GetAttribute. r=smaug (224d2e1e91)
- Bug 1236258 part 4. Change nsDOMAttributeMap::SetNamedItemNS to not remove the existing attribute when there is one. r=smaug (f1176918a6)
- Bug 1222079. Fix the behavior of Object.getOwnPropertyNames for nsDOMAttributeMap. r=bzbarsky (3b649bf948)
- Bug 1237580. NamedNodeMap should only claim to support a name if that name has no uppercase ASCII chars, for HTML elements in HTML documents. r=bkelly (216aa3ead6)
- just enable visibilityAPI (3df2d50b5d)
- bits of Bug 1153322 (85ba6268b4)
- Bug 1220160 - part 1: add chromeonly getter for documenturi that returns the original document when on an error page, r=bz (d0c256c29f)
- Bug 1219861 - Remove not-allowed cursor on disabled buttons on in-content pages. r=dao (fa9b2ef2d0)
- Bug 1207146 - Add a link to expert technical information in the cert error page. r=Gijs,keeler (c3292b3fc7)
- Bug 1224433 - Part 3: Compute the invalidation area for preserve-3d layers by accumulating the leaves. r=roc (fffc5a7dfb)
- Bug 1245306: Devirtualize RefreshCompartmentPrincipal. r=smaug (4fa906b7fe)
- Bug 1205298 - Date.parse() should accept a wider range of potential formats; r=jandem (11a0377372)
- Bug 1247807 - Fix Mixed Content UI when using upgrade-insecure-requests (r=bz) (10a0aba8d4)
- Bug 1224694 - Unify and clean up initialization of CSP (r=sicking) (45b6f0a865)
- Bug 1190093 - Stop throttling frame requests for loading pages by checking Hidden(), not isShowing. r=tnikkel (343d2b39fd)
- Bug 1234554 - verify pointer validity and if valid dereference it otherwise use default value. r=jst (8c3265ef33)
- Bug 1240283 - Slim down JSDate instances by not caching cheaply-computed values. r=Waldo (0148f646a2)
- Bug 1217049 - Make Date.prototype.toString.call(<primitive value>) throw a TypeError. r=arai (e8ec69b296)
- Bug 1187233 part 1 - Date constructor should create a copy when called with a Date object. Original patch by Giovanni Sferro. r=jwalden (6a3125c081)
- Bug 1187233 part 2 - Fix test_networkstats_service_proxy.js to not rely on the old behavior. r=jwalden (86461c8aa0)
- Bug 1208023 - Avoid using a bad initial-scale when computing the CSS viewport. r=botond (42e370ce6a)
- Bug 1234025 - Part 1: Move ObjectBox::isModuleBox definition to ParseNode.cpp. (ac4454c20a)
- Bug 1234025 - Part 2: Remove unused functions from ScriptedDirectProxyHandler.cpp. (0ea17c2395)
- Bug 1234025 - Part 3: Remove unused constant from Statistics.cpp (8986c23751)
2023-11-23 23:57:50 +08:00

517 lines
13 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/BasePrincipal.h"
#include "nsDocShell.h"
#include "nsIAddonPolicyService.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsPrincipal.h"
#include "nsNetUtil.h"
#include "nsIURIWithPrincipal.h"
#include "nsNullPrincipal.h"
#include "nsScriptSecurityManager.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/CSPDictionariesBinding.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/URLSearchParams.h"
namespace mozilla {
using dom::URLParams;
void OriginAttributes::InheritFromDocShellParent(const OriginAttributes& aParent)
{
mAppId = aParent.mAppId;
mInBrowser = aParent.mInBrowser;
mUserContextId = aParent.mUserContextId;
mSignedPkg = aParent.mSignedPkg;
}
bool OriginAttributes::CopyFromLoadContext(nsILoadContext* aLoadContext)
{
OriginAttributes attrs;
bool result = aLoadContext->GetOriginAttributes(attrs);
NS_ENSURE_TRUE(result, false);
mAppId = attrs.mAppId;
mInBrowser = attrs.mInBrowser;
mAddonId = attrs.mAddonId;
mUserContextId = attrs.mUserContextId;
mSignedPkg = attrs.mSignedPkg;
return true;
}
void
OriginAttributes::CreateSuffix(nsACString& aStr) const
{
UniquePtr<URLParams> params(new URLParams());
nsAutoString value;
//
// Important: While serializing any string-valued attributes, perform a
// release-mode assertion to make sure that they don't contain characters that
// will break the quota manager when it uses the serialization for file
// naming (see addonId below).
//
if (mAppId != nsIScriptSecurityManager::NO_APP_ID) {
value.AppendInt(mAppId);
params->Set(NS_LITERAL_STRING("appId"), value);
}
if (mInBrowser) {
params->Set(NS_LITERAL_STRING("inBrowser"), NS_LITERAL_STRING("1"));
}
if (!mAddonId.IsEmpty()) {
MOZ_RELEASE_ASSERT(mAddonId.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) == kNotFound);
params->Set(NS_LITERAL_STRING("addonId"), mAddonId);
}
if (mUserContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
value.Truncate();
value.AppendInt(mUserContextId);
params->Set(NS_LITERAL_STRING("userContextId"), value);
}
if (!mSignedPkg.IsEmpty()) {
params->Set(NS_LITERAL_STRING("signedPkg"), mSignedPkg);
}
aStr.Truncate();
params->Serialize(value);
if (!value.IsEmpty()) {
aStr.AppendLiteral("^");
aStr.Append(NS_ConvertUTF16toUTF8(value));
}
// In debug builds, check the whole string for illegal characters too (just in case).
#ifdef DEBUG
nsAutoCString str;
str.Assign(aStr);
MOZ_ASSERT(str.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) == kNotFound);
#endif
}
namespace {
class MOZ_STACK_CLASS PopulateFromSuffixIterator final
: public URLParams::ForEachIterator
{
public:
explicit PopulateFromSuffixIterator(OriginAttributes* aOriginAttributes)
: mOriginAttributes(aOriginAttributes)
{
MOZ_ASSERT(aOriginAttributes);
}
bool URLParamsIterator(const nsString& aName,
const nsString& aValue) override
{
if (aName.EqualsLiteral("appId")) {
nsresult rv;
int64_t val = aValue.ToInteger64(&rv);
NS_ENSURE_SUCCESS(rv, false);
NS_ENSURE_TRUE(val <= UINT32_MAX, false);
mOriginAttributes->mAppId = static_cast<uint32_t>(val);
return true;
}
if (aName.EqualsLiteral("inBrowser")) {
if (!aValue.EqualsLiteral("1")) {
return false;
}
mOriginAttributes->mInBrowser = true;
return true;
}
if (aName.EqualsLiteral("addonId")) {
MOZ_RELEASE_ASSERT(mOriginAttributes->mAddonId.IsEmpty());
mOriginAttributes->mAddonId.Assign(aValue);
return true;
}
if (aName.EqualsLiteral("userContextId")) {
nsresult rv;
int64_t val = aValue.ToInteger64(&rv);
NS_ENSURE_SUCCESS(rv, false);
NS_ENSURE_TRUE(val <= UINT32_MAX, false);
mOriginAttributes->mUserContextId = static_cast<uint32_t>(val);
return true;
}
if (aName.EqualsLiteral("signedPkg")) {
MOZ_RELEASE_ASSERT(mOriginAttributes->mSignedPkg.IsEmpty());
mOriginAttributes->mSignedPkg.Assign(aValue);
return true;
}
// No other attributes are supported.
return false;
}
private:
OriginAttributes* mOriginAttributes;
};
} // namespace
bool
OriginAttributes::PopulateFromSuffix(const nsACString& aStr)
{
if (aStr.IsEmpty()) {
return true;
}
if (aStr[0] != '^') {
return false;
}
UniquePtr<URLParams> params(new URLParams());
params->ParseInput(Substring(aStr, 1, aStr.Length() - 1));
PopulateFromSuffixIterator iterator(this);
return params->ForEach(iterator);
}
bool
OriginAttributes::PopulateFromOrigin(const nsACString& aOrigin,
nsACString& aOriginNoSuffix)
{
// RFindChar is only available on nsCString.
nsCString origin(aOrigin);
int32_t pos = origin.RFindChar('^');
if (pos == kNotFound) {
aOriginNoSuffix = origin;
return true;
}
aOriginNoSuffix = Substring(origin, 0, pos);
return PopulateFromSuffix(Substring(origin, pos));
}
BasePrincipal::BasePrincipal()
{}
BasePrincipal::~BasePrincipal()
{}
NS_IMETHODIMP
BasePrincipal::GetOrigin(nsACString& aOrigin)
{
return GetOriginInternal(aOrigin);
}
bool
BasePrincipal::Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration)
{
MOZ_ASSERT(aOther);
return SubsumesInternal(aOther, aConsideration);
}
NS_IMETHODIMP
BasePrincipal::Equals(nsIPrincipal *aOther, bool *aResult)
{
NS_ENSURE_TRUE(aOther, NS_ERROR_INVALID_ARG);
*aResult = Subsumes(aOther, DontConsiderDocumentDomain) &&
Cast(aOther)->Subsumes(this, DontConsiderDocumentDomain);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::EqualsConsideringDomain(nsIPrincipal *aOther, bool *aResult)
{
NS_ENSURE_TRUE(aOther, NS_ERROR_INVALID_ARG);
*aResult = Subsumes(aOther, ConsiderDocumentDomain) &&
Cast(aOther)->Subsumes(this, ConsiderDocumentDomain);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::Subsumes(nsIPrincipal *aOther, bool *aResult)
{
NS_ENSURE_TRUE(aOther, NS_ERROR_INVALID_ARG);
*aResult = Subsumes(aOther, DontConsiderDocumentDomain);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::SubsumesConsideringDomain(nsIPrincipal *aOther, bool *aResult)
{
NS_ENSURE_TRUE(aOther, NS_ERROR_INVALID_ARG);
*aResult = Subsumes(aOther, ConsiderDocumentDomain);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::CheckMayLoad(nsIURI* aURI, bool aReport, bool aAllowIfInheritsPrincipal)
{
// Check the internal method first, which allows us to quickly approve loads
// for the System Principal.
if (MayLoadInternal(aURI)) {
return NS_OK;
}
nsresult rv;
if (aAllowIfInheritsPrincipal) {
// If the caller specified to allow loads of URIs that inherit
// our principal, allow the load if this URI inherits its principal.
bool doesInheritSecurityContext;
rv = NS_URIChainHasFlags(aURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
&doesInheritSecurityContext);
if (NS_SUCCEEDED(rv) && doesInheritSecurityContext) {
return NS_OK;
}
}
bool fetchableByAnyone;
rv = NS_URIChainHasFlags(aURI, nsIProtocolHandler::URI_FETCHABLE_BY_ANYONE, &fetchableByAnyone);
if (NS_SUCCEEDED(rv) && fetchableByAnyone) {
return NS_OK;
}
if (aReport) {
nsCOMPtr<nsIURI> prinURI;
rv = GetURI(getter_AddRefs(prinURI));
if (NS_SUCCEEDED(rv) && prinURI) {
nsScriptSecurityManager::ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"), prinURI, aURI);
}
}
return NS_ERROR_DOM_BAD_URI;
}
NS_IMETHODIMP
BasePrincipal::GetCsp(nsIContentSecurityPolicy** aCsp)
{
NS_IF_ADDREF(*aCsp = mCSP);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::EnsureCSP(nsIDOMDocument* aDocument,
nsIContentSecurityPolicy** aCSP)
{
if (mCSP) {
// if there is a CSP already associated with this principal
// then just return that - do not overwrite it!!!
NS_IF_ADDREF(*aCSP = mCSP);
return NS_OK;
}
nsresult rv = NS_OK;
mCSP = do_CreateInstance("@mozilla.org/cspcontext;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Store the request context for violation reports
rv = aDocument ? mCSP->SetRequestContext(aDocument, nullptr)
: mCSP->SetRequestContext(nullptr, this);
NS_ENSURE_SUCCESS(rv, rv);
NS_IF_ADDREF(*aCSP = mCSP);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetPreloadCsp(nsIContentSecurityPolicy** aPreloadCSP)
{
NS_IF_ADDREF(*aPreloadCSP = mPreloadCSP);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::EnsurePreloadCSP(nsIDOMDocument* aDocument,
nsIContentSecurityPolicy** aPreloadCSP)
{
if (mPreloadCSP) {
// if there is a speculative CSP already associated with this principal
// then just return that - do not overwrite it!!!
NS_IF_ADDREF(*aPreloadCSP = mPreloadCSP);
return NS_OK;
}
nsresult rv = NS_OK;
mPreloadCSP = do_CreateInstance("@mozilla.org/cspcontext;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Store the request context for violation reports
rv = aDocument ? mPreloadCSP->SetRequestContext(aDocument, nullptr)
: mPreloadCSP->SetRequestContext(nullptr, this);
NS_ENSURE_SUCCESS(rv, rv);
NS_IF_ADDREF(*aPreloadCSP = mPreloadCSP);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetCspJSON(nsAString& outCSPinJSON)
{
outCSPinJSON.Truncate();
dom::CSPPolicies jsonPolicies;
if (!mCSP) {
jsonPolicies.ToJSON(outCSPinJSON);
return NS_OK;
}
return mCSP->ToJSON(outCSPinJSON);
}
NS_IMETHODIMP
BasePrincipal::GetIsNullPrincipal(bool* aResult)
{
*aResult = Kind() == eNullPrincipal;
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetIsCodebasePrincipal(bool* aResult)
{
*aResult = Kind() == eCodebasePrincipal;
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetIsExpandedPrincipal(bool* aResult)
{
*aResult = Kind() == eExpandedPrincipal;
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetIsSystemPrincipal(bool* aResult)
{
*aResult = Kind() == eSystemPrincipal;
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetJarPrefix(nsACString& aJarPrefix)
{
mozilla::GetJarPrefix(mOriginAttributes.mAppId, mOriginAttributes.mInBrowser, aJarPrefix);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetOriginAttributes(JSContext* aCx, JS::MutableHandle<JS::Value> aVal)
{
if (NS_WARN_IF(!ToJSValue(aCx, mOriginAttributes, aVal))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetOriginSuffix(nsACString& aOriginAttributes)
{
mOriginAttributes.CreateSuffix(aOriginAttributes);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetAppStatus(uint16_t* aAppStatus)
{
if (AppId() == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
NS_WARNING("Asking for app status on a principal with an unknown app id");
*aAppStatus = nsIPrincipal::APP_STATUS_NOT_INSTALLED;
return NS_OK;
}
*aAppStatus = nsScriptSecurityManager::AppStatusForPrincipal(this);
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetAppId(uint32_t* aAppId)
{
if (AppId() == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
MOZ_ASSERT(false);
*aAppId = nsIScriptSecurityManager::NO_APP_ID;
return NS_OK;
}
*aAppId = AppId();
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetUserContextId(uint32_t* aUserContextId)
{
*aUserContextId = UserContextId();
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetIsInBrowserElement(bool* aIsInBrowserElement)
{
*aIsInBrowserElement = IsInBrowserElement();
return NS_OK;
}
NS_IMETHODIMP
BasePrincipal::GetUnknownAppId(bool* aUnknownAppId)
{
*aUnknownAppId = AppId() == nsIScriptSecurityManager::UNKNOWN_APP_ID;
return NS_OK;
}
already_AddRefed<BasePrincipal>
BasePrincipal::CreateCodebasePrincipal(nsIURI* aURI, const OriginAttributes& aAttrs)
{
// If the URI is supposed to inherit the security context of whoever loads it,
// we shouldn't make a codebase principal for it.
bool inheritsPrincipal;
nsresult rv = NS_URIChainHasFlags(aURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
&inheritsPrincipal);
nsCOMPtr<nsIPrincipal> principal;
if (NS_FAILED(rv) || inheritsPrincipal) {
return nsNullPrincipal::Create();
}
// Check whether the URI knows what its principal is supposed to be.
nsCOMPtr<nsIURIWithPrincipal> uriPrinc = do_QueryInterface(aURI);
if (uriPrinc) {
nsCOMPtr<nsIPrincipal> principal;
uriPrinc->GetPrincipal(getter_AddRefs(principal));
if (!principal) {
return nsNullPrincipal::Create();
}
RefPtr<BasePrincipal> concrete = Cast(principal);
return concrete.forget();
}
// Mint a codebase principal.
RefPtr<nsPrincipal> codebase = new nsPrincipal();
rv = codebase->Init(aURI, aAttrs);
NS_ENSURE_SUCCESS(rv, nullptr);
return codebase.forget();
}
bool
BasePrincipal::AddonAllowsLoad(nsIURI* aURI)
{
if (mOriginAttributes.mAddonId.IsEmpty()) {
return false;
}
nsCOMPtr<nsIAddonPolicyService> aps = do_GetService("@mozilla.org/addons/policy-service;1");
NS_ENSURE_TRUE(aps, false);
bool allowed = false;
nsresult rv = aps->AddonMayLoadURI(mOriginAttributes.mAddonId, aURI, &allowed);
return NS_SUCCEEDED(rv) && allowed;
}
} // namespace mozilla