Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 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 "nsAboutProtocolUtils.h"
#include "nsArray.h"
#include "nsContentSecurityManager.h"
#include "nsContentSecurityUtils.h"
#include "nsContentPolicyUtils.h"
#include "nsEscape.h"
#include "nsDataHandler.h"
#include "nsIChannel.h"
#include "nsIContentPolicy.h"
#include "nsIHttpChannelInternal.h"
#include "nsINode.h"
#include "nsIStreamListener.h"
#include "nsILoadInfo.h"
#include "nsIMIMEService.h"
#include "nsIOService.h"
#include "nsContentUtils.h"
#include "nsCORSListenerProxy.h"
#include "nsIParentChannel.h"
#include "nsIRedirectHistoryEntry.h"
#include "nsIXULRuntime.h"
#include "nsNetUtil.h"
#include "nsReadableUtils.h"
#include "nsSandboxFlags.h"
#include "nsScriptSecurityManager.h"
#include "nsIXPConnect.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/CmdLineAndEnvUtils.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/nsMixedContentBlocker.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/extensions/WebExtensionPolicy.h"
#include "mozilla/glean/GleanMetrics.h"
#include "mozilla/Components.h"
#include "mozilla/ExtensionPolicyService.h"
#include "mozilla/Logging.h"
#include "mozilla/Maybe.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_security.h"
#include "xpcpublic.h"
#include "nsMimeTypes.h"
#include "jsapi.h"
#include "js/RegExp.h"
using namespace mozilla;
using namespace mozilla::dom;
NS_IMPL_ISUPPORTS(nsContentSecurityManager, nsIContentSecurityManager,
nsIChannelEventSink)
mozilla::LazyLogModule sCSMLog("CSMLog");
mozilla::LazyLogModule sUELLog("UnexpectedLoad");
// These first two are used for off-the-main-thread checks of
// general.config.filename
// (which can't be checked off-main-thread).
Atomic<bool, mozilla::Relaxed> sJSHacksChecked(false);
Atomic<bool, mozilla::Relaxed> sJSHacksPresent(false);
Atomic<bool, mozilla::Relaxed> sCSSHacksChecked(false);
Atomic<bool, mozilla::Relaxed> sCSSHacksPresent(false);
/* static */
bool nsContentSecurityManager::AllowTopLevelNavigationToDataURI(
nsIChannel* aChannel) {
// Let's block all toplevel document navigations to a data: URI.
// In all cases where the toplevel document is navigated to a
// data: URI the triggeringPrincipal is a contentPrincipal, or
// a NullPrincipal. In other cases, e.g. typing a data: URL into
// the URL-Bar, the triggeringPrincipal is a SystemPrincipal;
// we don't want to block those loads. Only exception, loads coming
// from an external applicaton (e.g. Thunderbird) don't load
// using a contentPrincipal, but we want to block those loads.
if (!StaticPrefs::security_data_uri_block_toplevel_data_uri_navigations()) {
return true;
}
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
if (loadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_DOCUMENT) {
return true;
}
if (loadInfo->GetForceAllowDataURI()) {
// if the loadinfo explicitly allows the data URI navigation, let's allow it
// now
return true;
}
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, true);
bool isDataURI = uri->SchemeIs("data");
if (!isDataURI) {
return true;
}
nsAutoCString spec;
rv = uri->GetSpec(spec);
NS_ENSURE_SUCCESS(rv, true);
nsAutoCString contentType;
bool base64;
rv = nsDataHandler::ParseURI(spec, contentType, nullptr, base64, nullptr);
NS_ENSURE_SUCCESS(rv, true);
// Allow data: images as long as they are not SVGs
if (StringBeginsWith(contentType, "image/"_ns) &&
!contentType.EqualsLiteral(IMAGE_SVG_XML)) {
return true;
}
// Allow all data: PDFs. or JSON documents
if (contentType.EqualsLiteral(APPLICATION_JSON) ||
contentType.EqualsLiteral(TEXT_JSON) ||
contentType.EqualsLiteral(APPLICATION_PDF)) {
return true;
}
// Redirecting to a toplevel data: URI is not allowed, hence we make
// sure the RedirectChain is empty.
if (!loadInfo->GetLoadTriggeredFromExternal() &&
loadInfo->TriggeringPrincipal()->IsSystemPrincipal() &&
loadInfo->RedirectChain().IsEmpty()) {
return true;
}
ReportBlockedDataURI(uri, loadInfo);
return false;
}
void nsContentSecurityManager::ReportBlockedDataURI(nsIURI* aURI,
nsILoadInfo* aLoadInfo,
bool aIsRedirect) {
// We're going to block the request, construct the localized error message to
// report to the console.
nsAutoCString dataSpec;
aURI->GetSpec(dataSpec);
if (dataSpec.Length() > 50) {
dataSpec.Truncate(50);
dataSpec.AppendLiteral("...");
}
AutoTArray<nsString, 1> params;
CopyUTF8toUTF16(NS_UnescapeURL(dataSpec), *params.AppendElement());
nsAutoString errorText;
const char* stringID =
aIsRedirect ? "BlockRedirectToDataURI" : "BlockTopLevelDataURINavigation";
nsresult rv = nsContentUtils::FormatLocalizedString(
nsContentUtils::eSECURITY_PROPERTIES, stringID, params, errorText);
if (NS_FAILED(rv)) {
return;
}
// Report the localized error message to the console for the loading
// BrowsingContext's current inner window.
RefPtr<BrowsingContext> target = aLoadInfo->GetBrowsingContext();
nsContentUtils::ReportToConsoleByWindowID(
errorText, nsIScriptError::warningFlag, "DATA_URI_BLOCKED"_ns,
target ? target->GetCurrentInnerWindowId() : 0);
}
/* static */
bool nsContentSecurityManager::AllowInsecureRedirectToDataURI(
nsIChannel* aNewChannel) {
nsCOMPtr<nsILoadInfo> loadInfo = aNewChannel->LoadInfo();
if (loadInfo->GetExternalContentPolicyType() !=
ExtContentPolicy::TYPE_SCRIPT) {
return true;
}
nsCOMPtr<nsIURI> newURI;
nsresult rv = NS_GetFinalChannelURI(aNewChannel, getter_AddRefs(newURI));
if (NS_FAILED(rv) || !newURI) {
return true;
}
bool isDataURI = newURI->SchemeIs("data");
if (!isDataURI) {
return true;
}
// Web Extensions are exempt from that restriction and are allowed to redirect
// a channel to a data: URI. When a web extension redirects a channel, we set
// a flag on the loadInfo which allows us to identify such redirects here.
if (loadInfo->GetAllowInsecureRedirectToDataURI()) {
return true;
}
ReportBlockedDataURI(newURI, loadInfo, true);
return false;
}
static nsresult ValidateSecurityFlags(nsILoadInfo* aLoadInfo) {
nsSecurityFlags securityMode = aLoadInfo->GetSecurityMode();
// We should never perform a security check on a loadInfo that uses the flag
// SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, because that is only used for
// temporary loadInfos used for explicit nsIContentPolicy checks, but never be
// set as a security flag on an actual channel.
if (securityMode !=
nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT &&
securityMode != nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED &&
securityMode !=
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT &&
securityMode != nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL &&
securityMode != nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT) {
MOZ_ASSERT(
false,
"need one securityflag from nsILoadInfo to perform security checks");
return NS_ERROR_FAILURE;
}
// all good, found the right security flags
return NS_OK;
}
static already_AddRefed<nsIPrincipal> GetExtensionSandboxPrincipal(
nsILoadInfo* aLoadInfo) {
// An extension is allowed to load resources from itself when its pages are
// loaded into a sandboxed frame. Extension resources in a sandbox have
// a null principal and no access to extension APIs. See "sandbox" in
// MDN extension docs for more information.
if (!aLoadInfo->TriggeringPrincipal()->GetIsNullPrincipal()) {
return nullptr;
}
RefPtr<Document> doc;
aLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
if (!doc || !(doc->GetSandboxFlags() & SANDBOXED_ORIGIN)) {
return nullptr;
}
// node principal is also a null principal here, so we need to
// create a principal using documentURI, which is the moz-extension
// uri for the page if this is an extension sandboxed page.
nsCOMPtr<nsIPrincipal> docPrincipal = BasePrincipal::CreateContentPrincipal(
doc->GetDocumentURI(), doc->NodePrincipal()->OriginAttributesRef());
if (!BasePrincipal::Cast(docPrincipal)->AddonPolicy()) {
return nullptr;
}
return docPrincipal.forget();
}
static bool IsImageLoadInEditorAppType(nsILoadInfo* aLoadInfo) {
// Editor apps get special treatment here, editors can load images
// from anywhere. This allows editor to insert images from file://
// into documents that are being edited.
nsContentPolicyType type = aLoadInfo->InternalContentPolicyType();
if (type != nsIContentPolicy::TYPE_INTERNAL_IMAGE &&
type != nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD &&
type != nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON &&
type != nsIContentPolicy::TYPE_IMAGESET) {
return false;
}
auto appType = nsIDocShell::APP_TYPE_UNKNOWN;
nsINode* node = aLoadInfo->LoadingNode();
if (!node) {
return false;
}
Document* doc = node->OwnerDoc();
if (!doc) {
return false;
}
nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = doc->GetDocShell();
if (!docShellTreeItem) {
return false;
}
nsCOMPtr<nsIDocShellTreeItem> root;
docShellTreeItem->GetInProcessRootTreeItem(getter_AddRefs(root));
nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(root));
if (docShell) {
appType = docShell->GetAppType();
}
return appType == nsIDocShell::APP_TYPE_EDITOR;
}
static nsresult DoCheckLoadURIChecks(nsIURI* aURI, nsILoadInfo* aLoadInfo) {
// In practice, these DTDs are just used for localization, so applying the
// same principal check as Fluent.
if (aLoadInfo->InternalContentPolicyType() ==
nsIContentPolicy::TYPE_INTERNAL_DTD) {
RefPtr<Document> doc;
aLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
bool allowed = false;
aLoadInfo->TriggeringPrincipal()->IsL10nAllowed(
doc ? doc->GetDocumentURI() : nullptr, &allowed);
return allowed ? NS_OK : NS_ERROR_DOM_BAD_URI;
}
// This is used in order to allow a privileged DOMParser to parse documents
// that need to access localization DTDs. We just allow through
// TYPE_INTERNAL_FORCE_ALLOWED_DTD no matter what the triggering principal is.
if (aLoadInfo->InternalContentPolicyType() ==
nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD) {
return NS_OK;
}
if (IsImageLoadInEditorAppType(aLoadInfo)) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> triggeringPrincipal = aLoadInfo->TriggeringPrincipal();
nsCOMPtr<nsIPrincipal> addonPrincipal =
GetExtensionSandboxPrincipal(aLoadInfo);
if (addonPrincipal) {
// call CheckLoadURIWithPrincipal() as below to continue other checks, but
// with the addon principal.
triggeringPrincipal = addonPrincipal;
}
// Only call CheckLoadURIWithPrincipal() using the TriggeringPrincipal and not
// the LoadingPrincipal when SEC_ALLOW_CROSS_ORIGIN_* security flags are set,
// to allow, e.g. user stylesheets to load chrome:// URIs.
return nsContentUtils::GetSecurityManager()->CheckLoadURIWithPrincipal(
triggeringPrincipal, aURI, aLoadInfo->CheckLoadURIFlags(),
aLoadInfo->GetInnerWindowID());
}
static bool URIHasFlags(nsIURI* aURI, uint32_t aURIFlags) {
bool hasFlags;
nsresult rv = NS_URIChainHasFlags(aURI, aURIFlags, &hasFlags);
NS_ENSURE_SUCCESS(rv, false);
return hasFlags;
}
static nsresult DoSOPChecks(nsIURI* aURI, nsILoadInfo* aLoadInfo,
nsIChannel* aChannel) {
if (aLoadInfo->GetAllowChrome() &&
(URIHasFlags(aURI, nsIProtocolHandler::URI_IS_UI_RESOURCE) ||
nsContentUtils::SchemeIs(aURI, "moz-safe-about"))) {
// UI resources are allowed.
return DoCheckLoadURIChecks(aURI, aLoadInfo);
}
if (NS_HasBeenCrossOrigin(aChannel, true)) {
NS_SetRequestBlockingReason(aLoadInfo,
nsILoadInfo::BLOCKING_REASON_NOT_SAME_ORIGIN);
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
static nsresult DoCORSChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo,
nsCOMPtr<nsIStreamListener>& aInAndOutListener) {
MOZ_RELEASE_ASSERT(aInAndOutListener,
"can not perform CORS checks without a listener");
// No need to set up CORS if TriggeringPrincipal is the SystemPrincipal.
if (aLoadInfo->TriggeringPrincipal()->IsSystemPrincipal()) {
return NS_OK;
}
// We use the triggering principal here, rather than the loading principal
// to ensure that anonymous CORS content in the browser resources and in
// WebExtensions is allowed to load.
nsIPrincipal* principal = aLoadInfo->TriggeringPrincipal();
RefPtr<nsCORSListenerProxy> corsListener = new nsCORSListenerProxy(
aInAndOutListener, principal,
aLoadInfo->GetCookiePolicy() == nsILoadInfo::SEC_COOKIES_INCLUDE);
// XXX: @arg: DataURIHandling::Allow
// lets use DataURIHandling::Allow for now and then decide on callsite basis.
// see also:
nsresult rv = corsListener->Init(aChannel, DataURIHandling::Allow);
NS_ENSURE_SUCCESS(rv, rv);
aInAndOutListener = corsListener;
return NS_OK;
}
static nsresult DoContentSecurityChecks(nsIChannel* aChannel,
nsILoadInfo* aLoadInfo) {
ExtContentPolicyType contentPolicyType =
aLoadInfo->GetExternalContentPolicyType();
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
switch (contentPolicyType) {
case ExtContentPolicy::TYPE_XMLHTTPREQUEST: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
"type_xml requires requestingContext of type Document");
}
#endif
break;
}
case ExtContentPolicy::TYPE_OBJECT_SUBREQUEST: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(
!node || node->NodeType() == nsINode::ELEMENT_NODE,
"type_subrequest requires requestingContext of type Element");
}
#endif
break;
}
case ExtContentPolicy::TYPE_DTD: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
"type_dtd requires requestingContext of type Document");
}
#endif
break;
}
case ExtContentPolicy::TYPE_MEDIA: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(!node || node->NodeType() == nsINode::ELEMENT_NODE,
"type_media requires requestingContext of type Element");
}
#endif
break;
}
case ExtContentPolicy::TYPE_WEBSOCKET: {
// Websockets have to use the proxied URI:
// ws:// instead of http:// for CSP checks
nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
do_QueryInterface(aChannel);
MOZ_ASSERT(httpChannelInternal);
if (httpChannelInternal) {
rv = httpChannelInternal->GetProxyURI(getter_AddRefs(uri));
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
break;
}
case ExtContentPolicy::TYPE_XSLT: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
"type_xslt requires requestingContext of type Document");
}
#endif
break;
}
case ExtContentPolicy::TYPE_BEACON: {
#ifdef DEBUG
{
nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
"type_beacon requires requestingContext of type Document");
}
#endif
break;
}
case ExtContentPolicy::TYPE_OTHER:
case ExtContentPolicy::TYPE_SCRIPT:
case ExtContentPolicy::TYPE_IMAGE:
case ExtContentPolicy::TYPE_STYLESHEET:
case ExtContentPolicy::TYPE_OBJECT:
case ExtContentPolicy::TYPE_DOCUMENT:
case ExtContentPolicy::TYPE_SUBDOCUMENT:
case ExtContentPolicy::TYPE_PING:
case ExtContentPolicy::TYPE_FONT:
case ExtContentPolicy::TYPE_UA_FONT:
case ExtContentPolicy::TYPE_CSP_REPORT:
case ExtContentPolicy::TYPE_WEB_MANIFEST:
case ExtContentPolicy::TYPE_FETCH:
case ExtContentPolicy::TYPE_IMAGESET:
case ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD:
case ExtContentPolicy::TYPE_SPECULATIVE:
case ExtContentPolicy::TYPE_PROXIED_WEBRTC_MEDIA:
case ExtContentPolicy::TYPE_WEB_TRANSPORT:
case ExtContentPolicy::TYPE_WEB_IDENTITY:
case ExtContentPolicy::TYPE_JSON:
break;
case ExtContentPolicy::TYPE_INVALID:
MOZ_ASSERT(false,
"can not perform security check without a valid contentType");
// Do not add default: so that compilers can catch the missing case.
}
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
rv = NS_CheckContentLoadPolicy(uri, aLoadInfo, &shouldLoad,
nsContentUtils::GetContentPolicy());
if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
NS_SetRequestBlockingReasonIfNull(
aLoadInfo, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_GENERAL);
if (NS_SUCCEEDED(rv) &&
(contentPolicyType == ExtContentPolicy::TYPE_DOCUMENT ||
contentPolicyType == ExtContentPolicy::TYPE_SUBDOCUMENT)) {
if (shouldLoad == nsIContentPolicy::REJECT_TYPE) {
// for docshell loads we might have to return SHOW_ALT.
return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT;
}
if (shouldLoad == nsIContentPolicy::REJECT_POLICY) {
return NS_ERROR_BLOCKED_BY_POLICY;
}
}
return NS_ERROR_CONTENT_BLOCKED;
}
return NS_OK;
}
static void LogHTTPSOnlyInfo(nsILoadInfo* aLoadInfo) {
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" httpsOnlyFirstStatus:"));
uint32_t httpsOnlyStatus = aLoadInfo->GetHttpsOnlyStatus();
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_UNINITIALIZED) {
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" - HTTPS_ONLY_UNINITIALIZED"));
}
if (httpsOnlyStatus &
nsILoadInfo::HTTPS_ONLY_UPGRADED_LISTENER_NOT_REGISTERED) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_UPGRADED_LISTENER_NOT_REGISTERED"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_UPGRADED_LISTENER_REGISTERED) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_UPGRADED_LISTENER_REGISTERED"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_EXEMPT) {
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" - HTTPS_ONLY_EXEMPT"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_TOP_LEVEL_LOAD_IN_PROGRESS) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_TOP_LEVEL_LOAD_IN_PROGRESS"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_DOWNLOAD_IN_PROGRESS) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_DOWNLOAD_IN_PROGRESS"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_DO_NOT_LOG_TO_CONSOLE) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_DO_NOT_LOG_TO_CONSOLE"));
}
if (httpsOnlyStatus & nsILoadInfo::HTTPS_ONLY_UPGRADED_HTTPS_FIRST) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" - HTTPS_ONLY_UPGRADED_HTTPS_FIRST"));
}
}
static void LogPrincipal(nsIPrincipal* aPrincipal,
const nsAString& aPrincipalName,
const uint8_t& aNestingLevel) {
nsPrintfCString aIndentationString("%*s", aNestingLevel * 2, "");
if (aPrincipal && aPrincipal->IsSystemPrincipal()) {
MOZ_LOG(sCSMLog, LogLevel::Debug,
("%s%s: SystemPrincipal\n", aIndentationString.get(),
NS_ConvertUTF16toUTF8(aPrincipalName).get()));
return;
}
if (aPrincipal) {
if (aPrincipal->GetIsNullPrincipal()) {
MOZ_LOG(sCSMLog, LogLevel::Debug,
("%s%s: NullPrincipal\n", aIndentationString.get(),
NS_ConvertUTF16toUTF8(aPrincipalName).get()));
return;
}
if (aPrincipal->GetIsExpandedPrincipal()) {
nsCOMPtr<nsIExpandedPrincipal> expanded(do_QueryInterface(aPrincipal));
nsAutoCString origin;
origin.AssignLiteral("[Expanded Principal [");
StringJoinAppend(origin, ", "_ns, expanded->AllowList(),
[](nsACString& dest, nsIPrincipal* principal) {
nsAutoCString subOrigin;
DebugOnly<nsresult> rv =
principal->GetOrigin(subOrigin);
MOZ_ASSERT(NS_SUCCEEDED(rv));
dest.Append(subOrigin);
});
origin.AppendLiteral("]]");
MOZ_LOG(sCSMLog, LogLevel::Debug,
("%s%s: %s\n", aIndentationString.get(),
NS_ConvertUTF16toUTF8(aPrincipalName).get(), origin.get()));
return;
}
nsAutoCString principalSpec;
aPrincipal->GetAsciiSpec(principalSpec);
if (aPrincipalName.IsEmpty()) {
MOZ_LOG(sCSMLog, LogLevel::Debug,
("%s - \"%s\"\n", aIndentationString.get(), principalSpec.get()));
} else {
MOZ_LOG(
sCSMLog, LogLevel::Debug,
("%s%s: \"%s\"\n", aIndentationString.get(),
NS_ConvertUTF16toUTF8(aPrincipalName).get(), principalSpec.get()));
}
return;
}
MOZ_LOG(sCSMLog, LogLevel::Debug,
("%s%s: nullptr\n", aIndentationString.get(),
NS_ConvertUTF16toUTF8(aPrincipalName).get()));
}
static void LogSecurityFlags(nsSecurityFlags securityFlags) {
struct DebugSecFlagType {
unsigned long secFlag;
char secTypeStr[128];
};
static const DebugSecFlagType secTypes[] = {
{nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK,
"SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK"},
{nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT,
"SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT"},
{nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
"SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED"},
{nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT,
"SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT"},
{nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
"SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL"},
{nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT,
"SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT"},
{nsILoadInfo::SEC_COOKIES_DEFAULT, "SEC_COOKIES_DEFAULT"},
{nsILoadInfo::SEC_COOKIES_INCLUDE, "SEC_COOKIES_INCLUDE"},
{nsILoadInfo::SEC_COOKIES_SAME_ORIGIN, "SEC_COOKIES_SAME_ORIGIN"},
{nsILoadInfo::SEC_COOKIES_OMIT, "SEC_COOKIES_OMIT"},
{nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL, "SEC_FORCE_INHERIT_PRINCIPAL"},
{nsILoadInfo::SEC_ABOUT_BLANK_INHERITS, "SEC_ABOUT_BLANK_INHERITS"},
{nsILoadInfo::SEC_ALLOW_CHROME, "SEC_ALLOW_CHROME"},
{nsILoadInfo::SEC_DISALLOW_SCRIPT, "SEC_DISALLOW_SCRIPT"},
{nsILoadInfo::SEC_DONT_FOLLOW_REDIRECTS, "SEC_DONT_FOLLOW_REDIRECTS"},
{nsILoadInfo::SEC_LOAD_ERROR_PAGE, "SEC_LOAD_ERROR_PAGE"},
{nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER,
"SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER"}};
for (const DebugSecFlagType& flag : secTypes) {
if (securityFlags & flag.secFlag) {
// the logging level should be in sync with the logging level in
// DebugDoContentSecurityCheck()
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" - %s\n", flag.secTypeStr));
}
}
}
static void DebugDoContentSecurityCheck(nsIChannel* aChannel,
nsILoadInfo* aLoadInfo) {
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel));
MOZ_LOG(sCSMLog, LogLevel::Debug, ("\n#DebugDoContentSecurityCheck Begin\n"));
// we only log http channels, unless loglevel is 5.
if (httpChannel || MOZ_LOG_TEST(sCSMLog, LogLevel::Verbose)) {
MOZ_LOG(sCSMLog, LogLevel::Verbose, ("doContentSecurityCheck:\n"));
nsAutoCString remoteType;
if (XRE_IsParentProcess()) {
nsCOMPtr<nsIParentChannel> parentChannel;
NS_QueryNotificationCallbacks(aChannel, parentChannel);
if (parentChannel) {
parentChannel->GetRemoteType(remoteType);
}
} else {
remoteType.Assign(
mozilla::dom::ContentChild::GetSingleton()->GetRemoteType());
}
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" processType: \"%s\"\n", remoteType.get()));
nsCOMPtr<nsIURI> channelURI;
nsAutoCString channelSpec;
nsAutoCString channelMethod;
NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
if (channelURI) {
channelURI->GetSpec(channelSpec);
}
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" channelURI: \"%s\"\n", channelSpec.get()));
// Log HTTP-specific things
if (httpChannel) {
nsresult rv;
rv = httpChannel->GetRequestMethod(channelMethod);
if (!NS_FAILED(rv)) {
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" httpMethod: %s\n", channelMethod.get()));
}
}
// Log Principals
nsCOMPtr<nsIPrincipal> requestPrincipal = aLoadInfo->TriggeringPrincipal();
LogPrincipal(aLoadInfo->GetLoadingPrincipal(), u"loadingPrincipal"_ns, 1);
LogPrincipal(requestPrincipal, u"triggeringPrincipal"_ns, 1);
LogPrincipal(aLoadInfo->PrincipalToInherit(), u"principalToInherit"_ns, 1);
// Log Redirect Chain
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" redirectChain:\n"));
for (nsIRedirectHistoryEntry* redirectHistoryEntry :
aLoadInfo->RedirectChain()) {
nsCOMPtr<nsIPrincipal> principal;
redirectHistoryEntry->GetPrincipal(getter_AddRefs(principal));
LogPrincipal(principal, u""_ns, 2);
}
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" internalContentPolicyType: %s\n",
NS_CP_ContentTypeName(aLoadInfo->InternalContentPolicyType())));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" externalContentPolicyType: %s\n",
NS_CP_ContentTypeName(aLoadInfo->GetExternalContentPolicyType())));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" upgradeInsecureRequests: %s\n",
aLoadInfo->GetUpgradeInsecureRequests() ? "true" : "false"));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" initialSecurityChecksDone: %s\n",
aLoadInfo->GetInitialSecurityCheckDone() ? "true" : "false"));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" allowDeprecatedSystemRequests: %s\n",
aLoadInfo->GetAllowDeprecatedSystemRequests() ? "true" : "false"));
MOZ_LOG(sCSMLog, LogLevel::Verbose,
(" schemelessInput: %d\n", aLoadInfo->GetSchemelessInput()));
// Log CSPrequestPrincipal
nsCOMPtr<nsIContentSecurityPolicy> csp = aLoadInfo->GetCsp();
MOZ_LOG(sCSMLog, LogLevel::Debug, (" CSP:"));
if (csp) {
nsAutoString parsedPolicyStr;
uint32_t count = 0;
csp->GetPolicyCount(&count);
for (uint32_t i = 0; i < count; ++i) {
csp->GetPolicyString(i, parsedPolicyStr);
// we need to add quotation marks, as otherwise yaml parsers may fail
// with CSP directives
// no need to escape quote marks in the parsed policy string, as URLs in
// there are already encoded
MOZ_LOG(sCSMLog, LogLevel::Debug,
(" - \"%s\"\n", NS_ConvertUTF16toUTF8(parsedPolicyStr).get()));
}
}
// Security Flags
MOZ_LOG(sCSMLog, LogLevel::Verbose, (" securityFlags:"));
LogSecurityFlags(aLoadInfo->GetSecurityFlags());
// HTTPS-Only
LogHTTPSOnlyInfo(aLoadInfo);
MOZ_LOG(sCSMLog, LogLevel::Debug, ("\n#DebugDoContentSecurityCheck End\n"));
}
}
/* static */
void nsContentSecurityManager::MeasureUnexpectedPrivilegedLoads(
nsILoadInfo* aLoadInfo, nsIURI* aFinalURI, const nsACString& aRemoteType) {
if (!StaticPrefs::dom_security_unexpected_system_load_telemetry_enabled()) {
return;
}
nsContentSecurityUtils::DetectJsHacks();
nsContentSecurityUtils::DetectCssHacks();
// The detection only work on the main-thread.
// To avoid races and early reports, we need to ensure the checks actually
// happened.
if (MOZ_UNLIKELY(sJSHacksPresent || !sJSHacksChecked || sCSSHacksPresent ||
!sCSSHacksChecked)) {
return;
}
ExtContentPolicyType contentPolicyType =
aLoadInfo->GetExternalContentPolicyType();
// restricting reported types to script, styles and documents
// to be continued in follow-ups of bug 1697163.
if (contentPolicyType != ExtContentPolicyType::TYPE_SCRIPT &&
contentPolicyType != ExtContentPolicyType::TYPE_STYLESHEET &&
contentPolicyType != ExtContentPolicyType::TYPE_DOCUMENT) {
return;
}
// Gather redirected schemes in string
nsAutoCString loggedRedirects;
const nsTArray<nsCOMPtr<nsIRedirectHistoryEntry>>& redirects =
aLoadInfo->RedirectChain();
if (!redirects.IsEmpty()) {
nsCOMPtr<nsIRedirectHistoryEntry> end = redirects.LastElement();
for (nsIRedirectHistoryEntry* entry : redirects) {
nsCOMPtr<nsIPrincipal> principal;
entry->GetPrincipal(getter_AddRefs(principal));
if (principal) {
nsAutoCString scheme;
principal->GetScheme(scheme);
loggedRedirects.Append(scheme);
if (entry != end) {
loggedRedirects.AppendLiteral(", ");
}
}
}
}
nsAutoCString uriString;
if (aFinalURI) {
aFinalURI->GetAsciiSpec(uriString);
}
FilenameTypeAndDetails fileNameTypeAndDetails =
nsContentSecurityUtils::FilenameToFilenameType(uriString, true);
nsCString loggedFileDetails = "unknown"_ns;
if (fileNameTypeAndDetails.second.isSome()) {
loggedFileDetails.Assign(fileNameTypeAndDetails.second.value());
}
// sanitize remoteType because it may contain sensitive
// info, like URLs. e.g. `webIsolated=https://example.com`
nsAutoCString loggedRemoteType(dom::RemoteTypePrefix(aRemoteType));
nsAutoCString loggedContentType(NS_CP_ContentTypeName(contentPolicyType));
MOZ_LOG(sUELLog, LogLevel::Debug, ("UnexpectedPrivilegedLoadTelemetry:\n"));
MOZ_LOG(sUELLog, LogLevel::Debug,
("- contentType: %s\n", loggedContentType.get()));
MOZ_LOG(sUELLog, LogLevel::Debug,
("- URL (not to be reported): %s\n", uriString.get()));
MOZ_LOG(sUELLog, LogLevel::Debug,
("- remoteType: %s\n", loggedRemoteType.get()));
MOZ_LOG(sUELLog, LogLevel::Debug,
("- fileInfo: %s\n", fileNameTypeAndDetails.first.get()));
MOZ_LOG(sUELLog, LogLevel::Debug,
("- fileDetails: %s\n", loggedFileDetails.get()));