1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
|
/* -*- 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 "IntegrityPolicy.h"
#include "mozilla/Logging.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/dom/RequestBinding.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/net/SFVService.h"
#include "nsCOMPtr.h"
#include "nsIClassInfoImpl.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsString.h"
using namespace mozilla;
static LazyLogModule sIntegrityPolicyLogModule("IntegrityPolicy");
#define LOG(fmt, ...) \
MOZ_LOG_FMT(sIntegrityPolicyLogModule, LogLevel::Debug, fmt, ##__VA_ARGS__)
namespace mozilla::dom {
IntegrityPolicy::~IntegrityPolicy() = default;
RequestDestination ContentTypeToDestination(nsContentPolicyType aType) {
// From SecFetch.cpp
// https://searchfox.org/mozilla-central/rev/f1e32fa7054859d37eea8804e220dfcc7fb53b03/dom/security/SecFetch.cpp#24-32
switch (aType) {
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
case nsIContentPolicy::TYPE_INTERNAL_MODULE:
case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
// We currently only support documents.
// case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
case nsIContentPolicy::TYPE_SCRIPT:
return RequestDestination::Script;
case nsIContentPolicy::TYPE_STYLESHEET:
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
return RequestDestination::Style;
default:
return RequestDestination::_empty;
}
}
Maybe<IntegrityPolicy::DestinationType> DOMRequestDestinationToDestinationType(
RequestDestination aDestination) {
switch (aDestination) {
case RequestDestination::Script:
return Some(IntegrityPolicy::DestinationType::Script);
case RequestDestination::Style:
return StaticPrefs::security_integrity_policy_stylesheet_enabled()
? Some(IntegrityPolicy::DestinationType::Style)
: Nothing{};
default:
return Nothing{};
}
}
Maybe<IntegrityPolicy::DestinationType>
IntegrityPolicy::ContentTypeToDestinationType(nsContentPolicyType aType) {
return DOMRequestDestinationToDestinationType(
ContentTypeToDestination(aType));
}
nsresult GetStringsFromInnerList(nsISFVInnerList* aList, bool aIsToken,
nsTArray<nsCString>& aStrings) {
nsTArray<RefPtr<nsISFVItem>> items;
nsresult rv = aList->GetItems(items);
NS_ENSURE_SUCCESS(rv, rv);
for (auto& item : items) {
nsCOMPtr<nsISFVBareItem> value;
rv = item->GetValue(getter_AddRefs(value));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString itemStr;
if (aIsToken) {
nsCOMPtr<nsISFVToken> itemToken(do_QueryInterface(value));
NS_ENSURE_TRUE(itemToken, NS_ERROR_FAILURE);
rv = itemToken->GetValue(itemStr);
NS_ENSURE_SUCCESS(rv, rv);
} else {
nsCOMPtr<nsISFVString> itemString(do_QueryInterface(value));
NS_ENSURE_TRUE(itemString, NS_ERROR_FAILURE);
rv = itemString->GetValue(itemStr);
NS_ENSURE_SUCCESS(rv, rv);
}
aStrings.AppendElement(itemStr);
}
return NS_OK;
}
/* static */
Result<IntegrityPolicy::Sources, nsresult> ParseSources(
nsISFVDictionary* aDict) {
// sources, a list of sources, Initially empty.
// 3. If dictionary["sources"] does not exist or if its value contains
// "inline", append "inline" to integrityPolicy’s sources.
nsCOMPtr<nsISFVItemOrInnerList> iil;
nsresult rv = aDict->Get("sources"_ns, getter_AddRefs(iil));
if (NS_FAILED(rv)) {
// The key doesn't exists, set it to inline as per spec.
return IntegrityPolicy::Sources(IntegrityPolicy::SourceType::Inline);
}
nsCOMPtr<nsISFVInnerList> il(do_QueryInterface(iil));
NS_ENSURE_TRUE(il, Err(NS_ERROR_FAILURE));
nsTArray<nsCString> sources;
rv = GetStringsFromInnerList(il, true, sources);
NS_ENSURE_SUCCESS(rv, Err(rv));
IntegrityPolicy::Sources result;
for (const auto& source : sources) {
if (source.EqualsLiteral("inline")) {
result += IntegrityPolicy::SourceType::Inline;
} else {
LOG("ParseSources: Unknown source: {}", source.get());
// Unknown source, we don't know how to handle it
continue;
}
}
return result;
}
/* static */
Result<IntegrityPolicy::Destinations, nsresult> ParseDestinations(
nsISFVDictionary* aDict) {
// blocked destinations, a list of destinations, initially empty.
nsCOMPtr<nsISFVItemOrInnerList> iil;
nsresult rv = aDict->Get("blocked-destinations"_ns, getter_AddRefs(iil));
if (NS_FAILED(rv)) {
return IntegrityPolicy::Destinations();
}
// 4. If dictionary["blocked-destinations"] exists:
nsCOMPtr<nsISFVInnerList> il(do_QueryInterface(iil));
NS_ENSURE_TRUE(il, Err(NS_ERROR_FAILURE));
nsTArray<nsCString> destinations;
rv = GetStringsFromInnerList(il, true, destinations);
NS_ENSURE_SUCCESS(rv, Err(rv));
IntegrityPolicy::Destinations result;
for (const auto& destination : destinations) {
if (destination.EqualsLiteral("script")) {
result += IntegrityPolicy::DestinationType::Script;
} else if (destination.EqualsLiteral("style")) {
if (StaticPrefs::security_integrity_policy_stylesheet_enabled()) {
result += IntegrityPolicy::DestinationType::Style;
}
} else {
LOG("ParseDestinations: Unknown destination: {}", destination.get());
// Unknown destination, we don't know how to handle it
continue;
}
}
return result;
}
/* static */
Result<nsTArray<nsCString>, nsresult> ParseEndpoints(nsISFVDictionary* aDict) {
// endpoints, a list of strings, initially empty.
nsCOMPtr<nsISFVItemOrInnerList> iil;
nsresult rv = aDict->Get("endpoints"_ns, getter_AddRefs(iil));
if (NS_FAILED(rv)) {
// The key doesn't exists, return empty list.
return nsTArray<nsCString>();
}
nsCOMPtr<nsISFVInnerList> il(do_QueryInterface(iil));
NS_ENSURE_TRUE(il, Err(NS_ERROR_FAILURE));
nsTArray<nsCString> endpoints;
rv = GetStringsFromInnerList(il, true, endpoints);
NS_ENSURE_SUCCESS(rv, Err(rv));
return endpoints;
}
/* static */
// https://w3c.github.io/webappsec-subresource-integrity/#processing-an-integrity-policy
nsresult IntegrityPolicy::ParseHeaders(const nsACString& aHeader,
const nsACString& aHeaderRO,
IntegrityPolicy** aPolicy) {
if (!StaticPrefs::security_integrity_policy_enabled()) {
return NS_OK;
}
// 1. Let integrityPolicy be a new integrity policy struct.
// (Our struct contains two entries, one for the enforcement header and one
// for report-only)
RefPtr<IntegrityPolicy> policy = new IntegrityPolicy();
LOG("[{}] Parsing headers: enforcement='{}' report-only='{}'",
static_cast<void*>(policy), aHeader.Data(), aHeaderRO.Data());
nsCOMPtr<nsISFVService> sfv = net::GetSFVService();
NS_ENSURE_TRUE(sfv, NS_ERROR_FAILURE);
for (const auto& isROHeader : {false, true}) {
const auto& headerString = isROHeader ? aHeaderRO : aHeader;
if (headerString.IsEmpty()) {
LOG("[{}] No {} header.", static_cast<void*>(policy),
isROHeader ? "report-only" : "enforcement");
continue;
}
// 2. Let dictionary be the result of getting a structured field value from
// headers given headerName and "dictionary".
nsCOMPtr<nsISFVDictionary> dict;
nsresult rv = sfv->ParseDictionary(headerString, getter_AddRefs(dict));
if (NS_FAILED(rv)) {
LOG("[{}] Failed to parse {} header.", static_cast<void*>(policy),
isROHeader ? "report-only" : "enforcement");
continue;
}
// 3. If dictionary["sources"] does not exist or if its value contains
// "inline", append "inline" to integrityPolicy’s sources.
auto sourcesResult = ParseSources(dict);
if (sourcesResult.isErr()) {
LOG("[{}] Failed to parse sources for {} header.",
static_cast<void*>(policy),
isROHeader ? "report-only" : "enforcement");
continue;
}
// 4. If dictionary["blocked-destinations"] exists:
auto destinationsResult = ParseDestinations(dict);
if (destinationsResult.isErr()) {
LOG("[{}] Failed to parse destinations for {} header.",
static_cast<void*>(policy),
isROHeader ? "report-only" : "enforcement");
continue;
}
// 5. If dictionary["endpoints"] exists:
auto endpointsResult = ParseEndpoints(dict);
if (endpointsResult.isErr()) {
LOG("[{}] Failed to parse endpoints for {} header.",
static_cast<void*>(policy),
isROHeader ? "report-only" : "enforcement");
continue;
}
LOG("[{}] Creating policy for {} header. sources={} destinations={} "
"endpoints=[{}]",
static_cast<void*>(policy), isROHeader ? "report-only" : "enforcement",
sourcesResult.unwrap().serialize(),
destinationsResult.unwrap().serialize(),
fmt::join(endpointsResult.unwrap(), ", "));
Entry entry = Entry(sourcesResult.unwrap(), destinationsResult.unwrap(),
endpointsResult.unwrap());
if (isROHeader) {
policy->mReportOnly.emplace(entry);
} else {
policy->mEnforcement.emplace(entry);
}
}
// 6. Return integrityPolicy.
policy.forget(aPolicy);
LOG("[{}] Finished parsing headers.", static_cast<void*>(policy));
return NS_OK;
}
void IntegrityPolicy::PolicyContains(DestinationType aDestination,
bool* aContains, bool* aROContains) const {
// 10. Let block be a boolean, initially false.
*aContains = false;
// 11. Let reportBlock be a boolean, initially false.
*aROContains = false;
// 12. If policy’s sources contains "inline" and policy’s blocked destinations
// contains request’s destination, set block to true.
if (mEnforcement && mEnforcement->mDestinations.contains(aDestination) &&
mEnforcement->mSources.contains(SourceType::Inline)) {
*aContains = true;
}
// 13. If reportPolicy’s sources contains "inline" and reportPolicy’s blocked
// destinations contains request’s destination, set reportBlock to true.
if (mReportOnly && mReportOnly->mDestinations.contains(aDestination) &&
mReportOnly->mSources.contains(SourceType::Inline)) {
*aROContains = true;
}
}
void IntegrityPolicy::ToArgs(const IntegrityPolicy* aPolicy,
mozilla::ipc::IntegrityPolicyArgs& aArgs) {
aArgs.enforcement() = Nothing();
aArgs.reportOnly() = Nothing();
if (!aPolicy) {
return;
}
if (aPolicy->mEnforcement) {
mozilla::ipc::IntegrityPolicyEntry entry;
entry.sources() = aPolicy->mEnforcement->mSources;
entry.destinations() = aPolicy->mEnforcement->mDestinations;
entry.endpoints() = aPolicy->mEnforcement->mEndpoints.Clone();
aArgs.enforcement() = Some(entry);
}
if (aPolicy->mReportOnly) {
mozilla::ipc::IntegrityPolicyEntry entry;
entry.sources() = aPolicy->mReportOnly->mSources;
entry.destinations() = aPolicy->mReportOnly->mDestinations;
entry.endpoints() = aPolicy->mReportOnly->mEndpoints.Clone();
aArgs.reportOnly() = Some(entry);
}
}
void IntegrityPolicy::FromArgs(const mozilla::ipc::IntegrityPolicyArgs& aArgs,
IntegrityPolicy** aPolicy) {
RefPtr<IntegrityPolicy> policy = new IntegrityPolicy();
if (aArgs.enforcement().isSome()) {
const auto& entry = *aArgs.enforcement();
policy->mEnforcement.emplace(Entry(entry.sources(), entry.destinations(),
entry.endpoints().Clone()));
}
if (aArgs.reportOnly().isSome()) {
const auto& entry = *aArgs.reportOnly();
policy->mReportOnly.emplace(Entry(entry.sources(), entry.destinations(),
entry.endpoints().Clone()));
}
policy.forget(aPolicy);
}
void IntegrityPolicy::InitFromOther(IntegrityPolicy* aOther) {
if (!aOther) {
return;
}
if (aOther->mEnforcement) {
mEnforcement.emplace(Entry(*aOther->mEnforcement));
}
if (aOther->mReportOnly) {
mReportOnly.emplace(Entry(*aOther->mReportOnly));
}
}
bool IntegrityPolicy::Equals(const IntegrityPolicy* aPolicy,
const IntegrityPolicy* aOtherPolicy) {
// Do a quick pointer check first, also checks if both are null.
if (aPolicy == aOtherPolicy) {
return true;
}
// We checked if they were null above, so make sure one of them is not null.
if (!aPolicy || !aOtherPolicy) {
return false;
}
if (!Entry::Equals(aPolicy->mEnforcement, aOtherPolicy->mEnforcement)) {
return false;
}
if (!Entry::Equals(aPolicy->mReportOnly, aOtherPolicy->mReportOnly)) {
return false;
}
return true;
}
bool IntegrityPolicy::Entry::Equals(const Maybe<Entry>& aPolicy,
const Maybe<Entry>& aOtherPolicy) {
// If one is set and the other is not, they are not equal.
if (aPolicy.isSome() != aOtherPolicy.isSome()) {
return false;
}
// If both are not set, they are equal.
if (aPolicy.isNothing() && aOtherPolicy.isNothing()) {
return true;
}
if (aPolicy->mSources != aOtherPolicy->mSources) {
return false;
}
if (aPolicy->mDestinations != aOtherPolicy->mDestinations) {
return false;
}
if (aPolicy->mEndpoints != aOtherPolicy->mEndpoints) {
return false;
}
return true;
}
constexpr static const uint32_t kIntegrityPolicySerializationVersion = 1;
NS_IMETHODIMP
IntegrityPolicy::Read(nsIObjectInputStream* aStream) {
nsresult rv;
uint32_t version;
rv = aStream->Read32(&version);
NS_ENSURE_SUCCESS(rv, rv);
if (version != kIntegrityPolicySerializationVersion) {
LOG("IntegrityPolicy::Read: Unsupported version: {}", version);
return NS_ERROR_FAILURE;
}
for (const bool& isRO : {false, true}) {
bool hasPolicy;
rv = aStream->ReadBoolean(&hasPolicy);
NS_ENSURE_SUCCESS(rv, rv);
if (!hasPolicy) {
continue;
}
uint32_t sources;
rv = aStream->Read32(&sources);
NS_ENSURE_SUCCESS(rv, rv);
Sources sourcesSet;
sourcesSet.deserialize(sources);
uint32_t destinations;
rv = aStream->Read32(&destinations);
NS_ENSURE_SUCCESS(rv, rv);
Destinations destinationsSet;
destinationsSet.deserialize(destinations);
uint32_t endpointsLen;
rv = aStream->Read32(&endpointsLen);
NS_ENSURE_SUCCESS(rv, rv);
nsTArray<nsCString> endpoints(endpointsLen);
for (size_t endpointI = 0; endpointI < endpointsLen; endpointI++) {
nsCString endpoint;
rv = aStream->ReadCString(endpoint);
NS_ENSURE_SUCCESS(rv, rv);
endpoints.AppendElement(std::move(endpoint));
}
Entry entry = Entry(sourcesSet, destinationsSet, std::move(endpoints));
if (isRO) {
mReportOnly.emplace(entry);
} else {
mEnforcement.emplace(entry);
}
}
return NS_OK;
}
NS_IMETHODIMP
IntegrityPolicy::Write(nsIObjectOutputStream* aStream) {
nsresult rv;
rv = aStream->Write32(kIntegrityPolicySerializationVersion);
NS_ENSURE_SUCCESS(rv, rv);
for (const auto& entry : {mEnforcement, mReportOnly}) {
if (!entry) {
aStream->WriteBoolean(false);
continue;
}
aStream->WriteBoolean(true);
rv = aStream->Write32(entry->mSources.serialize());
NS_ENSURE_SUCCESS(rv, rv);
rv = aStream->Write32(entry->mDestinations.serialize());
NS_ENSURE_SUCCESS(rv, rv);
rv = aStream->Write32(entry->mEndpoints.Length());
for (const auto& endpoint : entry->mEndpoints) {
rv = aStream->WriteCString(endpoint);
NS_ENSURE_SUCCESS(rv, rv);
}
}
return NS_OK;
}
NS_IMPL_CLASSINFO(IntegrityPolicy, nullptr, 0, NS_IINTEGRITYPOLICY_IID)
NS_IMPL_ISUPPORTS_CI(IntegrityPolicy, nsIIntegrityPolicy, nsISerializable)
} // namespace mozilla::dom
#undef LOG
|