DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "nsArray.h"
#include "nsArray.h"
#include "nsContentSecurityManager.h"
#include "nsEscape.h"
#include "nsDataHandler.h"
#include "nsIChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIHttpChannelInternal.h"
#include "nsINode.h"
#include "nsIStreamListener.h"
#include "nsILoadInfo.h"
#include "nsIOService.h"
#include "nsContentUtils.h"
#include "nsContentUtils.h"
#include "nsCORSListenerProxy.h"
#include "nsIStreamListener.h"
#include "nsIRedirectHistoryEntry.h"
#include "nsReadableUtils.h"
#include "nsReadableUtils.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/Components.h"
#include "mozilla/Logging.h"
#include "mozilla/Telemetry.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TelemetryComms.h"
#include "xpcpublic.h"
#include "js/RegExp.h"

#include "jsapi.h"
#include "js/RegExp.h"

using namespace mozilla::Telemetry;
                  nsIChannelEventSink)

NS_IMPL_ISUPPORTS(nsContentSecurityManager, nsIContentSecurityManager,
                  nsIChannelEventSink)

static mozilla::LazyLogModule sCSMLog("CSMLog");


static Atomic<bool, mozilla::Relaxed> sTelemetryEventEnabled(false);

/* static */
bool nsContentSecurityManager::AllowTopLevelNavigationToDataURI(
    nsIChannel* aChannel) {
  // Let's block all toplevel document navigations to a data: URI.
  // a NullPrincipal. In other cases, e.g. typing a data: URL into
  // 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
  if (!mozilla::net::nsIOService::BlockToplevelDataUriNavigations()) {
  // 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() !=
      nsIContentPolicy::TYPE_DOCUMENT) {
    // if the loadinfo explicitly allows the data URI navigation, let's allow it
    return true;
  }
  if (loadInfo->GetForceAllowDataURI()) {
    // if the loadinfo explicitly allows the data URI navigation, let's allow it
    // now
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
    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;
  bool base64;
  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
    return true;
  if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/")) &&
      !contentType.EqualsLiteral("image/svg+xml")) {
    return true;
  }
  // Allow all plain text types as well as data: PDFs.
    return true;
  if (nsContentUtils::IsPlainTextType(contentType) ||
      contentType.EqualsLiteral("application/pdf")) {
    return true;
  }
  // Redirecting to a toplevel data: URI is not allowed, hence we make
      loadInfo->TriggeringPrincipal()->IsSystemPrincipal() &&
  // sure the RedirectChain is empty.
  if (!loadInfo->GetLoadTriggeredFromExternal() &&
      loadInfo->TriggeringPrincipal()->IsSystemPrincipal() &&
      loadInfo->RedirectChain().IsEmpty()) {
  uri->GetSpec(dataSpec);
    return true;
  }
  nsAutoCString dataSpec;
  uri->GetSpec(dataSpec);
  if (dataSpec.Length() > 50) {
    dataSpec.Truncate(50);
  nsCOMPtr<nsIBrowserChild> browserChild = do_QueryInterface(context);
    dataSpec.AppendLiteral("...");
  }
  nsCOMPtr<nsISupports> context = loadInfo->ContextForTopLevelLoad();
  nsCOMPtr<nsIBrowserChild> browserChild = do_QueryInterface(context);
  nsCOMPtr<Document> doc;
  }
  if (browserChild) {
    doc = static_cast<mozilla::dom::BrowserChild*>(browserChild.get())
              ->GetTopLevelDocument();
  }
  AutoTArray<nsString, 1> params;
                                  nsContentUtils::eSECURITY_PROPERTIES,
  CopyUTF8toUTF16(NS_UnescapeURL(dataSpec), *params.AppendElement());
  nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
                                  NS_LITERAL_CSTRING("DATA_URI_BLOCKED"), doc,
                                  nsContentUtils::eSECURITY_PROPERTIES,
                                  "BlockTopLevelDataURINavigation", params);
/* static */
  return false;
}

/* static */
bool nsContentSecurityManager::AllowInsecureRedirectToDataURI(
      nsIContentPolicy::TYPE_SCRIPT) {
    nsIChannel* aNewChannel) {
  nsCOMPtr<nsILoadInfo> loadInfo = aNewChannel->LoadInfo();
  if (loadInfo->GetExternalContentPolicyType() !=
      nsIContentPolicy::TYPE_SCRIPT) {
    return true;
  if (NS_FAILED(rv) || !newURI) {
  }
  nsCOMPtr<nsIURI> newURI;
  nsresult rv = NS_GetFinalChannelURI(aNewChannel, getter_AddRefs(newURI));
  if (NS_FAILED(rv) || !newURI) {
  bool isDataURI = newURI->SchemeIs("data");
  if (!isDataURI) {
    return true;
  }
  bool isDataURI = newURI->SchemeIs("data");
  if (!isDataURI) {
  // Web Extensions are exempt from that restriction and are allowed to redirect
    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;
  }

    dataSpec.Truncate(50);
  nsAutoCString dataSpec;
  newURI->GetSpec(dataSpec);
  if (dataSpec.Length() > 50) {
    dataSpec.Truncate(50);
    dataSpec.AppendLiteral("...");
  if (node) {
  }
  nsCOMPtr<Document> doc;
  nsINode* node = loadInfo->LoadingNode();
  if (node) {
    doc = node->OwnerDoc();
  }
  nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
  AutoTArray<nsString, 1> params;
  CopyUTF8toUTF16(NS_UnescapeURL(dataSpec), *params.AppendElement());
  nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
                                  NS_LITERAL_CSTRING("DATA_URI_BLOCKED"), doc,
                                  nsContentUtils::eSECURITY_PROPERTIES,
}
                                  "BlockSubresourceRedirectToData", params);
  return false;
}

/* static */
  // The only valid way to use FTP resources is loading it as
nsresult nsContentSecurityManager::CheckFTPSubresourceLoad(
    nsIChannel* aChannel) {
  // We dissallow using FTP resources as a subresource everywhere.
  // The only valid way to use FTP resources is loading it as
  // a top level document.


  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
  nsContentPolicyType type = loadInfo->GetExternalContentPolicyType();

  // Allow top-level FTP documents and save-as download of FTP files on
  // HTTP pages.
  if (type == nsIContentPolicy::TYPE_DOCUMENT ||

      type == nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD) {
    return NS_OK;
  }

  // Allow the system principal to load everything. This is meant to
    return NS_OK;
  // temporarily fix downloads and pdf.js.
  nsIPrincipal* triggeringPrincipal = loadInfo->TriggeringPrincipal();
  if (triggeringPrincipal->IsSystemPrincipal()) {
    return NS_OK;
  }
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);
  if (!uri) {
    return NS_OK;
  if (!isFtpURI) {
  }

  bool isFtpURI = uri->SchemeIs("ftp");
  if (!isFtpURI) {
    return NS_OK;
  if (nsINode* node = loadInfo->LoadingNode()) {
  }

  nsCOMPtr<Document> doc;
  if (nsINode* node = loadInfo->LoadingNode()) {
    doc = node->OwnerDoc();
  }
  uri->GetSpec(spec);

  nsAutoCString spec;
  uri->GetSpec(spec);
  AutoTArray<nsString, 1> params;
  CopyUTF8toUTF16(NS_UnescapeURL(spec), *params.AppendElement());
      nsIScriptError::warningFlag, NS_LITERAL_CSTRING("FTP_URI_BLOCKED"), doc,

  nsContentUtils::ReportToConsole(
      nsIScriptError::warningFlag, NS_LITERAL_CSTRING("FTP_URI_BLOCKED"), doc,
      nsContentUtils::eSECURITY_PROPERTIES, "BlockSubresourceFTP", params);


  return NS_ERROR_CONTENT_BLOCKED;
}

static nsresult ValidateSecurityFlags(nsILoadInfo* aLoadInfo) {
  nsSecurityFlags securityMode = aLoadInfo->GetSecurityMode();
  // SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, because that is only used for

  // 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
      securityMode != nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS &&
  // set as a security flag on an actual channel.
  if (securityMode != nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS &&
      securityMode != nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED &&
      securityMode != nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS &&
      securityMode != nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL &&
        "need one securityflag from nsILoadInfo to perform security checks");
      securityMode != nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS) {
    MOZ_ASSERT(
        false,
        "need one securityflag from nsILoadInfo to perform security checks");
    return NS_ERROR_FAILURE;
  }
  return NS_OK;

  // all good, found the right security flags
  return NS_OK;
}
  // from anywhere.  This allows editor to insert images from file://

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.
      type != nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON &&
  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) {
  if (!doc) {
    return false;
  }
  Document* doc = node->OwnerDoc();
  if (!doc) {
    return false;
  if (!docShellTreeItem) {
  }

  nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = doc->GetDocShell();
  if (!docShellTreeItem) {
    return false;
  }
  docShellTreeItem->GetInProcessRootTreeItem(getter_AddRefs(root));

  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;
}
  // In practice, these DTDs are just used for localization, so applying the

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() ==
    aLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
      nsIContentPolicy::TYPE_INTERNAL_DTD) {
    RefPtr<Document> doc;
    aLoadInfo->GetLoadingDocument(getter_AddRefs(doc));
    bool allowed = false;
    return allowed ? NS_OK : NS_ERROR_DOM_BAD_URI;
    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
      nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD) {
  // TYPE_INTERNAL_FORCE_ALLOWED_DTD no matter what the triggering principal is.
  if (aLoadInfo->InternalContentPolicyType() ==
      nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD) {
    return NS_OK;
  }
    return NS_OK;

  if (IsImageLoadInEditorAppType(aLoadInfo)) {
    return NS_OK;
  }

  // to allow, e.g. user stylesheets to load chrome:// URIs.
  // 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(
}
      aLoadInfo->TriggeringPrincipal(), aURI, aLoadInfo->CheckLoadURIFlags(),
      aLoadInfo->GetInnerWindowID());
}

static bool URIHasFlags(nsIURI* aURI, uint32_t aURIFlags) {
  NS_ENSURE_SUCCESS(rv, false);
  bool hasFlags;
  nsresult rv = NS_URIChainHasFlags(aURI, aURIFlags, &hasFlags);
  NS_ENSURE_SUCCESS(rv, false);

  return hasFlags;
static nsresult DoSOPChecks(nsIURI* aURI, nsILoadInfo* aLoadInfo,
}

static nsresult DoSOPChecks(nsIURI* aURI, nsILoadInfo* aLoadInfo,
                            nsIChannel* aChannel) {
    // UI resources are allowed.
  if (aLoadInfo->GetAllowChrome() &&
      (URIHasFlags(aURI, nsIProtocolHandler::URI_IS_UI_RESOURCE) ||
       nsContentUtils::SchemeIs(aURI, "moz-safe-about"))) {
    // UI resources are allowed.
    return DoCheckLoadURIChecks(aURI, aLoadInfo);
    NS_SetRequestBlockingReason(aLoadInfo,
  }

  if (NS_HasBeenCrossOrigin(aChannel, true)) {
    NS_SetRequestBlockingReason(aLoadInfo,
                                nsILoadInfo::BLOCKING_REASON_NOT_SAME_ORIGIN);

    return NS_ERROR_DOM_BAD_URI;
  }

  return NS_OK;
}
                             nsCOMPtr<nsIStreamListener>& aInAndOutListener) {

static nsresult DoCORSChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo,
                             nsCOMPtr<nsIStreamListener>& aInAndOutListener) {
  MOZ_RELEASE_ASSERT(aInAndOutListener,
                     "can not perform CORS checks without a listener");
  if (aLoadInfo->TriggeringPrincipal()->IsSystemPrincipal()) {

  // No need to set up CORS if TriggeringPrincipal is the SystemPrincipal.
  if (aLoadInfo->TriggeringPrincipal()->IsSystemPrincipal()) {
    return NS_OK;
  // to ensure that anonymous CORS content in the browser resources and in
  }

  // 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.
      aLoadInfo->GetCookiePolicy() == nsILoadInfo::SEC_COOKIES_INCLUDE);
  nsIPrincipal* principal = aLoadInfo->TriggeringPrincipal();
  RefPtr<nsCORSListenerProxy> corsListener = new nsCORSListenerProxy(
      aInAndOutListener, principal,
      aLoadInfo->GetCookiePolicy() == nsILoadInfo::SEC_COOKIES_INCLUDE);
  // http://mxr.mozilla.org/mozilla-central/source/dom/security/nsCORSListenerProxy.h#33
  // XXX: @arg: DataURIHandling::Allow
  // lets use  DataURIHandling::Allow for now and then decide on callsite basis.
  // see also:
  // http://mxr.mozilla.org/mozilla-central/source/dom/security/nsCORSListenerProxy.h#33
  nsresult rv = corsListener->Init(aChannel, DataURIHandling::Allow);
}
  NS_ENSURE_SUCCESS(rv, rv);
  aInAndOutListener = corsListener;
  return NS_OK;
}

      aLoadInfo->GetExternalContentPolicyType();
static nsresult DoContentSecurityChecks(nsIChannel* aChannel,
                                        nsILoadInfo* aLoadInfo) {
  nsContentPolicyType contentPolicyType =
      aLoadInfo->GetExternalContentPolicyType();
  nsContentPolicyType internalContentPolicyType =
  nsCOMPtr<nsIURI> uri;
      aLoadInfo->InternalContentPolicyType();
  nsCString mimeTypeGuess;

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
    case nsIContentPolicy::TYPE_OTHER: {
  NS_ENSURE_SUCCESS(rv, rv);

  switch (contentPolicyType) {
    case nsIContentPolicy::TYPE_OTHER: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_SCRIPT: {
    }

    case nsIContentPolicy::TYPE_SCRIPT: {
      mimeTypeGuess = NS_LITERAL_CSTRING("application/javascript");
      break;
    case nsIContentPolicy::TYPE_IMAGE: {
    }

    case nsIContentPolicy::TYPE_IMAGE: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_STYLESHEET: {
    }

    case nsIContentPolicy::TYPE_STYLESHEET: {
      mimeTypeGuess = NS_LITERAL_CSTRING("text/css");
      break;
    case nsIContentPolicy::TYPE_OBJECT: {
    }

    case nsIContentPolicy::TYPE_OBJECT: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_DOCUMENT: {
    }

    case nsIContentPolicy::TYPE_DOCUMENT: {
    }
      mimeTypeGuess = EmptyCString();

      break;
    }
      break;

    case nsIContentPolicy::TYPE_SUBDOCUMENT: {
      mimeTypeGuess = NS_LITERAL_CSTRING("text/html");
      break;
      MOZ_ASSERT(false, "contentPolicyType not supported yet");
    }

    case nsIContentPolicy::TYPE_REFRESH: {
      MOZ_ASSERT(false, "contentPolicyType not supported yet");
      break;
      mimeTypeGuess = EmptyCString();
    }

    case nsIContentPolicy::TYPE_PING: {
      mimeTypeGuess = EmptyCString();
      break;
      // alias nsIContentPolicy::TYPE_DATAREQUEST:
    }

    case nsIContentPolicy::TYPE_XMLHTTPREQUEST: {
      // alias nsIContentPolicy::TYPE_DATAREQUEST:
#ifdef DEBUG
                   "type_xml requires requestingContext of type Document");
      {
        nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
        MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
                   "type_xml requires requestingContext of type Document");
      // an addon creates a request with that type.
      }
#endif
      // We're checking for the external TYPE_XMLHTTPREQUEST here in case
      // an addon creates a request with that type.
      if (internalContentPolicyType ==
      } else {
              nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST ||
          internalContentPolicyType == nsIContentPolicy::TYPE_XMLHTTPREQUEST) {
        mimeTypeGuess = EmptyCString();
      } else {
        MOZ_ASSERT(internalContentPolicyType ==
                       nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE,
                   "can not set mime type guess for unexpected internal type");
        mimeTypeGuess = NS_LITERAL_CSTRING(TEXT_EVENT_STREAM);
    }
      }
      break;
    }

    case nsIContentPolicy::TYPE_OBJECT_SUBREQUEST: {
      mimeTypeGuess = EmptyCString();
        MOZ_ASSERT(
#ifdef DEBUG
      {
        nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
        MOZ_ASSERT(
            !node || node->NodeType() == nsINode::ELEMENT_NODE,
      break;
            "type_subrequest requires requestingContext of type Element");
      }
#endif
      break;
    }
#ifdef DEBUG

    case nsIContentPolicy::TYPE_DTD: {
      mimeTypeGuess = EmptyCString();
#ifdef DEBUG
      {
      }
        nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
        MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
                   "type_dtd requires requestingContext of type Document");
      }
#endif
    case nsIContentPolicy::TYPE_FONT: {
      break;
    }

    case nsIContentPolicy::TYPE_FONT: {

      mimeTypeGuess = EmptyCString();
      break;
    }

    case nsIContentPolicy::TYPE_MEDIA: {
        mimeTypeGuess = EmptyCString();
      if (internalContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_TRACK) {
        mimeTypeGuess = NS_LITERAL_CSTRING("text/vtt");
      } else {
        mimeTypeGuess = EmptyCString();
      }
        MOZ_ASSERT(!node || node->NodeType() == nsINode::ELEMENT_NODE,
#ifdef DEBUG
      {
        nsCOMPtr<nsINode> node = aLoadInfo->LoadingNode();
        MOZ_ASSERT(!node || node->NodeType() == nsINode::ELEMENT_NODE,
                   "type_media requires requestingContext of type Element");
    }
      }
#endif
      break;
    }

      nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
    case nsIContentPolicy::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) {
      mimeTypeGuess = EmptyCString();
        rv = httpChannelInternal->GetProxyURI(getter_AddRefs(uri));
        MOZ_ASSERT(NS_SUCCEEDED(rv));
      }
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_CSP_REPORT: {
    }

    case nsIContentPolicy::TYPE_CSP_REPORT: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_XSLT: {
    }

    case nsIContentPolicy::TYPE_XSLT: {
      mimeTypeGuess = NS_LITERAL_CSTRING("application/xml");
        MOZ_ASSERT(!node || node->NodeType() == nsINode::DOCUMENT_NODE,
#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 nsIContentPolicy::TYPE_BEACON: {
      mimeTypeGuess = EmptyCString();
#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 nsIContentPolicy::TYPE_FETCH: {
    }

    case nsIContentPolicy::TYPE_FETCH: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_IMAGESET: {
    }

    case nsIContentPolicy::TYPE_IMAGESET: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_WEB_MANIFEST: {
    }

    case nsIContentPolicy::TYPE_WEB_MANIFEST: {
      mimeTypeGuess = NS_LITERAL_CSTRING("application/manifest+json");
      break;
    case nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD: {
    }

    case nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD: {
      mimeTypeGuess = EmptyCString();
      break;
    case nsIContentPolicy::TYPE_SPECULATIVE: {
    }

    case nsIContentPolicy::TYPE_SPECULATIVE: {
      mimeTypeGuess = EmptyCString();
      break;
    }
      MOZ_ASSERT(false,

    default:
      // nsIContentPolicy::TYPE_INVALID
      MOZ_ASSERT(false,
                 "can not perform security check without a valid contentType");
  }

  int16_t shouldLoad = nsIContentPolicy::ACCEPT;
  if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
  rv = NS_CheckContentLoadPolicy(uri, aLoadInfo, mimeTypeGuess, &shouldLoad,
                                 nsContentUtils::GetContentPolicy());

  if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
    NS_SetRequestBlockingReasonIfNull(
        (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
        aLoadInfo, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_GENERAL);

    if ((NS_SUCCEEDED(rv) && shouldLoad == nsIContentPolicy::REJECT_TYPE) &&
        (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
         contentPolicyType == nsIContentPolicy::TYPE_SUBDOCUMENT)) {
    return NS_ERROR_CONTENT_BLOCKED;
      // for docshell loads we might have to return SHOW_ALT.
      return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT;
    }
    return NS_ERROR_CONTENT_BLOCKED;
}
  }

  return NS_OK;
}

    MOZ_LOG(sCSMLog, LogLevel::Debug,
static void LogPrincipal(nsIPrincipal* aPrincipal,
                         const nsAString& aPrincipalName) {
  if (aPrincipal && aPrincipal->IsSystemPrincipal()) {
    MOZ_LOG(sCSMLog, LogLevel::Debug,
            ("  %s: SystemPrincipal\n",
  if (aPrincipal) {
             NS_ConvertUTF16toUTF8(aPrincipalName).get()));
    return;
  }
  if (aPrincipal) {
    if (aPrincipal->GetIsNullPrincipal()) {
               NS_ConvertUTF16toUTF8(aPrincipalName).get()));
      MOZ_LOG(sCSMLog, LogLevel::Debug,
              ("  %s: NullPrincipal\n",
               NS_ConvertUTF16toUTF8(aPrincipalName).get()));
      return;
      const nsTArray<nsCOMPtr<nsIPrincipal>>& allowList = expanded->AllowList();
    }
    if (aPrincipal->GetIsExpandedPrincipal()) {
      nsCOMPtr<nsIExpandedPrincipal> expanded(do_QueryInterface(aPrincipal));
      const nsTArray<nsCOMPtr<nsIPrincipal>>& allowList = expanded->AllowList();
      nsAutoCString origin;
          origin.AppendLiteral(", ");
      origin.AssignLiteral("[Expanded Principal [");
      for (size_t i = 0; i < allowList.Length(); ++i) {
        if (i != 0) {
          origin.AppendLiteral(", ");
        }
        MOZ_ASSERT(NS_SUCCEEDED(rv));

        nsAutoCString subOrigin;
        DebugOnly<nsresult> rv = allowList.ElementAt(i)->GetOrigin(subOrigin);
        MOZ_ASSERT(NS_SUCCEEDED(rv));
        origin.Append(subOrigin);

      }
      origin.AppendLiteral("]]");

      MOZ_LOG(sCSMLog, LogLevel::Debug,
              ("  %s: %s\n", NS_ConvertUTF16toUTF8(aPrincipalName).get(),
    }
               origin.get()));
      return;
    }
    nsAutoCString principalSpec;
    aPrincipal->GetAsciiSpec(principalSpec);
    return;
    MOZ_LOG(sCSMLog, LogLevel::Debug,
            ("  %s: %s\n", NS_ConvertUTF16toUTF8(aPrincipalName).get(),
             principalSpec.get()));
    return;
  }

  MOZ_LOG(sCSMLog, LogLevel::Debug,
          ("  %s: nullptr\n", 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_REQUIRE_SAME_ORIGIN_DATA_INHERITS"},
       "SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK"},
      {nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS,
       "SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS"},
      {nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
       "SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED"},
      {nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS,
       "SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS"},
      {nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
       "SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL"},
      {nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS,
       "SEC_REQUIRE_CORS_DATA_INHERITS"},
      {nsILoadInfo::SEC_COOKIES_SAME_ORIGIN, "SEC_COOKIES_SAME_ORIGIN"},
      {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_DISALLOW_SCRIPT, "SEC_DISALLOW_SCRIPT"},
      {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) {
      MOZ_LOG(sCSMLog, LogLevel::Debug, ("    %s,\n", flag.secTypeStr));
    }
  }
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel));
}
static void DebugDoContentSecurityCheck(nsIChannel* aChannel,
                                        nsILoadInfo* aLoadInfo) {
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel));

  // we only log http channels, unless loglevel is 5.
  if (httpChannel || MOZ_LOG_TEST(sCSMLog, LogLevel::Verbose)) {
    NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
    nsCOMPtr<nsIURI> channelURI;
    nsAutoCString channelSpec;
    nsAutoCString channelMethod;
    NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
    if (channelURI) {
    MOZ_LOG(sCSMLog, LogLevel::Verbose, ("doContentSecurityCheck {\n"));
      channelURI->GetSpec(channelSpec);
    }

    MOZ_LOG(sCSMLog, LogLevel::Verbose, ("doContentSecurityCheck {\n"));
    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  channelURI: %s\n", channelSpec.get()));
      nsresult rv;

    // Log HTTP-specific things
    if (httpChannel) {
      nsresult rv;
      rv = httpChannel->GetRequestMethod(channelMethod);
      }
      if (!NS_FAILED(rv)) {
        MOZ_LOG(sCSMLog, LogLevel::Verbose,
                ("  HTTP Method: %s\n", channelMethod.get()));
      }
    }
    LogPrincipal(aLoadInfo->GetLoadingPrincipal(),

    // Log Principals
    nsCOMPtr<nsIPrincipal> requestPrincipal = aLoadInfo->TriggeringPrincipal();
    LogPrincipal(aLoadInfo->GetLoadingPrincipal(),
                 NS_LITERAL_STRING("loadingPrincipal"));
    LogPrincipal(requestPrincipal, NS_LITERAL_STRING("triggeringPrincipal"));
    // Log Redirect Chain
    LogPrincipal(aLoadInfo->PrincipalToInherit(),
                 NS_LITERAL_STRING("principalToInherit"));

    // Log Redirect Chain
    MOZ_LOG(sCSMLog, LogLevel::Verbose, ("  RedirectChain:\n"));
      redirectHistoryEntry->GetPrincipal(getter_AddRefs(principal));
    for (nsIRedirectHistoryEntry* redirectHistoryEntry :
         aLoadInfo->RedirectChain()) {
      nsCOMPtr<nsIPrincipal> principal;
      redirectHistoryEntry->GetPrincipal(getter_AddRefs(principal));
      LogPrincipal(principal, NS_LITERAL_STRING("->"));
            ("  internalContentPolicyType: %d\n",
    }

    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  internalContentPolicyType: %d\n",
             aLoadInfo->GetExternalContentPolicyType()));
             aLoadInfo->InternalContentPolicyType()));
    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  externalContentPolicyType: %d\n",
             aLoadInfo->GetExternalContentPolicyType()));
    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  upgradeInsecureRequests: %s\n",
            ("  initalSecurityChecksDone: %s\n",
             aLoadInfo->GetUpgradeInsecureRequests() ? "true" : "false"));
    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  initalSecurityChecksDone: %s\n",
             aLoadInfo->GetInitialSecurityCheckDone() ? "true" : "false"));
    MOZ_LOG(sCSMLog, LogLevel::Verbose,
            ("  allowDeprecatedSystemRequests: %s\n",
             aLoadInfo->GetAllowDeprecatedSystemRequests() ? "true" : "false"));

    // Log CSPrequestPrincipal
      MOZ_LOG(sCSMLog, LogLevel::Debug, ("  CSP (%d): ", count));
    nsCOMPtr<nsIContentSecurityPolicy> csp = aLoadInfo->GetCsp();
    if (csp) {
      nsAutoString parsedPolicyStr;
      uint32_t count = 0;
      csp->GetPolicyCount(&count);
      MOZ_LOG(sCSMLog, LogLevel::Debug, ("  CSP (%d): ", count));

      for (uint32_t i = 0; i < count; ++i) {
        csp->GetPolicyString(i, parsedPolicyStr);
        MOZ_LOG(sCSMLog, LogLevel::Debug,
                ("    %s\n", NS_ConvertUTF16toUTF8(parsedPolicyStr).get()));
      }
  }
    }

    // Security Flags
    MOZ_LOG(sCSMLog, LogLevel::Verbose, ("  securityFlags: "));
    LogSecurityFlags(aLoadInfo->GetSecurityFlags());
    nsIChannel* aChannel) {
    MOZ_LOG(sCSMLog, LogLevel::Verbose, ("}\n\n"));
  }
}

/* static */
  // nothing to do here if we are not loading a resource into a
nsresult nsContentSecurityManager::CheckAllowLoadInSystemPrivilegedContext(
    nsIChannel* aChannel) {
  // Check and assert that we never allow remote documents/scripts (http:,
  // https:, ...) to load in system privileged contexts.
      !loadInfo->GetLoadingPrincipal()->IsSystemPrincipal()) {
  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();

  // nothing to do here if we are not loading a resource into a
  // system prvileged context.
  if (!loadInfo->GetLoadingPrincipal() ||
  NS_GetFinalChannelURI(aChannel, getter_AddRefs(finalURI));
      !loadInfo->GetLoadingPrincipal()->IsSystemPrincipal()) {
    return NS_OK;
  }
  // loads with the allow flag are waived through
  }
  // until refactored (e.g., Shavar, OCSP)
  if (loadInfo->GetAllowDeprecatedSystemRequests()) {
    return NS_OK;
  }

      !nsContentUtils::SchemeIs(finalURI, "ftp")) {
  nsContentPolicyType contentPolicyType =
      loadInfo->GetExternalContentPolicyType();


  // allowing some fetches due to their lowered risk
  // i.e., data & downloads fetches do limited parsing, no rendering
  // remote images are too widely used (favicons, about:addons etc.)
  if ((contentPolicyType == nsIContentPolicy::TYPE_FETCH) ||
  // a) remote scripts
      (contentPolicyType == nsIContentPolicy::TYPE_XMLHTTPREQUEST) ||
      (contentPolicyType == nsIContentPolicy::TYPE_WEBSOCKET) ||
      (contentPolicyType == nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD) ||
      (contentPolicyType == nsIContentPolicy::TYPE_IMAGE)) {
    return NS_OK;
  if (contentPolicyType == nsIContentPolicy::TYPE_SCRIPT) {
  }

  // Allow the user interface (e.g., schemes like chrome, resource)
  nsCOMPtr<nsIURI> finalURI;
  NS_GetFinalChannelURI(aChannel, getter_AddRefs(finalURI));
    nsAutoCString scriptSpec;
  bool isUiResource = false;
  if (NS_SUCCEEDED(NS_URIChainHasFlags(
          finalURI, nsIProtocolHandler::URI_IS_UI_RESOURCE, &isUiResource)) &&
      isUiResource) {
    return NS_OK;
         scriptSpec.get()));
  }
  // For about: and extension-based URIs, which don't get
  // URI_IS_UI_RESOURCE, first remove layers of view-source:, if present.
  while (finalURI && finalURI->SchemeIs("view-source")) {
    // return NS_ERROR_CONTENT_BLOCKED.
    nsCOMPtr<nsINestedURI> nested = do_QueryInterface(finalURI);
    if (nested) {
      nested->GetInnerURI(getter_AddRefs(finalURI));
    }
  }
      (contentPolicyType != nsIContentPolicy::TYPE_SUBDOCUMENT)) {
  // This is our escape hatch, if things break in release.
  // We expect to remove the pref in bug 1638770
  bool cancelNonLocalSystemPrincipal = StaticPrefs::
      security_cancel_non_local_loads_triggered_by_systemprincipal();

    bool disallowSystemPrincipalRemoteDocuments = Preferences::GetBool(
  // GetInnerURI can return null for malformed nested URIs like moz-icon:trash
  if (!finalURI && cancelNonLocalSystemPrincipal) {
    aChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
    return NS_ERROR_CONTENT_BLOCKED;
  }
      aChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
  // loads of userContent.css during startup and tests that show up as file:
  if (finalURI->SchemeIs("file")) {
    if ((contentPolicyType == nsIContentPolicy::TYPE_STYLESHEET) ||
        (contentPolicyType == nsIContentPolicy::TYPE_OTHER)) {
    return NS_OK;
      return NS_OK;
    }
  }
  // (1)loads from within omni.ja and system add-ons use jar:
  // this is safe to allow, because we do not support remote jar.
  MOZ_LOG(
  // (2) about: resources are always allowed: they are part of the build.
  // (3) extensions are signed or the user has made bad decisions.
  if (finalURI->SchemeIs("jar") || finalURI->SchemeIs("about") ||
      finalURI->SchemeIs("moz-extension")) {
    return NS_OK;
  aChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
  }

  // Relaxing restrictions for our test suites:
  // (1) AreNonLocalConnectionsDisabled() disables network, so http://mochitest
  // is actually local and allowed. (2) The marionette test framework uses
 * Every protocol handler must set one of the five security flags
  // injections and data URLs to execute scripts, checking for the environment
  // variable breaks the attack but not the tests.
  if (xpc::AreNonLocalConnectionsDisabled() ||
      mozilla::EnvHasValue("MOZ_MARIONETTE")) {
    bool disallowSystemPrincipalRemoteDocuments = Preferences::GetBool(
  nsCOMPtr<nsIURI> uri;
        "security.disallow_non_local_systemprincipal_in_tests");
    if (disallowSystemPrincipalRemoteDocuments) {
      // our own mochitest needs NS_ASSERTION instead of MOZ_ASSERT
      NS_ASSERTION(false, "SystemPrincipal must not load remote documents.");
      aChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
      return NS_ERROR_CONTENT_BLOCKED;
    }
    // but other mochitest are exempt from this
    return NS_OK;
  NS_ENSURE_SUCCESS(rv, rv);
  }

  nsAutoCString requestedURL;
  finalURI->GetAsciiSpec(requestedURL);
  MOZ_LOG(sCSMLog, LogLevel::Warning,
          ("SystemPrincipal must not load remote documents. URL: %s, type %d",

           requestedURL.get(), contentPolicyType));

  if (cancelNonLocalSystemPrincipal) {
    MOZ_ASSERT(false, "SystemPrincipal must not load remote documents.");
  uint32_t securityFlagsSet = 0;
    aChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
    return NS_ERROR_CONTENT_BLOCKED;
  }
  return NS_OK;
}
    securityFlagsSet += 1;

/*
 * Every protocol handler must set one of the five security flags
 * defined in nsIProtocolHandler - if not - deny the load.
 */
  if (flags & nsIProtocolHandler::URI_IS_LOCAL_FILE) {
nsresult nsContentSecurityManager::CheckChannelHasProtocolSecurityFlag(
    nsIChannel* aChannel) {
  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);
  }

  nsAutoCString scheme;
  rv = uri->GetScheme(scheme);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIProtocolHandler> handler;
  rv = ios->GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  NS_ENSURE_SUCCESS(rv, rv);

/*
  uint32_t flags;
  rv = handler->DoGetProtocolFlags(uri, &flags);
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t securityFlagsSet = 0;
 * (1) Same Origin Policy Check (if applicable)
  if (flags & nsIProtocolHandler::URI_LOADABLE_BY_ANYONE) {
    securityFlagsSet += 1;
  }
  if (flags & nsIProtocolHandler::URI_DANGEROUS_TO_LOAD) {
    securityFlagsSet += 1;
 *
  }
  if (flags & nsIProtocolHandler::URI_IS_UI_RESOURCE) {
    securityFlagsSet += 1;
  }
 * potentially wrappend within nsCORSListenerProxy() and becomes the
  if (flags & nsIProtocolHandler::URI_IS_LOCAL_FILE) {
    securityFlagsSet += 1;
  }
  if (flags & nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS) {
    securityFlagsSet += 1;
  }

  // Ensure that only "1" valid security flags is set.
  if (MOZ_UNLIKELY(MOZ_LOG_TEST(sCSMLog, LogLevel::Verbose))) {
  if (securityFlagsSet == 1) {
    return NS_OK;
  }

  MOZ_ASSERT(false, "protocol must use one valid security flag");
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_ERROR_CONTENT_BLOCKED;
}

/*
 * Based on the security flags provided in the loadInfo of the channel,
 * doContentSecurityCheck() performs the following content security checks
  // streamlistener and redirect proxies and so we are done.
 * before opening the channel:
 *
 * (1) Same Origin Policy Check (if applicable)
 * (2) Allow Cross Origin but perform sanity checks whether a principal
 *     is allowed to access the following URL.
  // make sure that only one of the five security flags is set in the loadinfo
 * (3) Perform CORS check (if applicable)
 * (4) ContentPolicy checks (Content-Security-Policy, Mixed Content, ...)
 *
 * @param aChannel
  if (loadInfo->GetSecurityMode() ==
 *    The channel to perform the security checks on.
 * @param aInAndOutListener
 *    The streamListener that is passed to channel->AsyncOpen() that is now
 * potentially wrappend within nsCORSListenerProxy() and becomes the
 * corsListener that now needs to be set as new streamListener on the channel.

 */
nsresult nsContentSecurityManager::doContentSecurityCheck(
    nsIChannel* aChannel, nsCOMPtr<nsIStreamListener>& aInAndOutListener) {
  NS_ENSURE_ARG(aChannel);
  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
  rv = DoContentSecurityChecks(aChannel, loadInfo);
  if (MOZ_UNLIKELY(MOZ_LOG_TEST(sCSMLog, LogLevel::Verbose))) {
    DebugDoContentSecurityCheck(aChannel, loadInfo);
  }

  nsresult rv = CheckAllowLoadInSystemPrivilegedContext(aChannel);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = CheckChannelHasProtocolSecurityFlag(aChannel);
  NS_ENSURE_SUCCESS(rv, rv);
  loadInfo->SetInitialSecurityCheckDone(true);

  // if dealing with a redirected channel then we have already installed
  // streamlistener and redirect proxies and so we are done.
  if (loadInfo->GetInitialSecurityCheckDone()) {
    return NS_OK;

  }

  // make sure that only one of the five security flags is set in the loadinfo
  // e.g. do not require same origin and allow cross origin at the same time
  rv = ValidateSecurityFlags(loadInfo);
  // Since we compare the principal from the loadInfo to the URI's
  NS_ENSURE_SUCCESS(rv, rv);

  if (loadInfo->GetSecurityMode() ==
      nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS) {
    rv = DoCORSChecks(aChannel, loadInfo, aInAndOutListener);
    aCb->OnRedirectVerifyCallback(NS_OK);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = CheckChannel(aChannel);
  NS_ENSURE_SUCCESS(rv, rv);
  nsresult rv = CheckChannel(aNewChannel);

  // Perform all ContentPolicy checks (MixedContent, CSP, ...)
  rv = DoContentSecurityChecks(aChannel, loadInfo);
  NS_ENSURE_SUCCESS(rv, rv);

  // Apply this after CSP to match Chrome.
  }
  rv = CheckFTPSubresourceLoad(aChannel);
  NS_ENSURE_SUCCESS(rv, rv);

  // now lets set the initalSecurityFlag for subsequent calls
  loadInfo->SetInitialSecurityCheckDone(true);

  // all security checks passed - lets allow the load

  return NS_OK;
}

NS_IMETHODIMP
nsContentSecurityManager::AsyncOnChannelRedirect(
  // Do not allow insecure redirects to data: URIs
    nsIChannel* aOldChannel, nsIChannel* aNewChannel, uint32_t aRedirFlags,
    nsIAsyncVerifyRedirectCallback* aCb) {
  // Since we compare the principal from the loadInfo to the URI's
  // princicpal, it's possible that the checks fail when doing an internal
  // redirect. We can just return early instead, since we should never
  }
  // need to block an internal redirect.
  if (aRedirFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
    aCb->OnRedirectVerifyCallback(NS_OK);
    return NS_OK;
  }
  rv = nsContentUtils::GetSecurityManager()->CheckLoadURIWithPrincipal(

  nsCOMPtr<nsILoadInfo> loadInfo = aOldChannel->LoadInfo();
  nsresult rv = CheckChannel(aNewChannel);

  if (NS_SUCCEEDED(rv)) {
  aCb->OnRedirectVerifyCallback(NS_OK);
    rv = CheckFTPSubresourceLoad(aNewChannel);
  }
  if (NS_FAILED(rv)) {
    aOldChannel->Cancel(rv);

    return rv;
  }

  // Also verify that the redirecting server is allowed to redirect to the
  aRequest->SetLoadFlags(flags);
  // given URI
  nsCOMPtr<nsIPrincipal> oldPrincipal;
  nsContentUtils::GetSecurityManager()->GetChannelResultPrincipal(
      aOldChannel, getter_AddRefs(oldPrincipal));

  nsCOMPtr<nsIURI> newURI;
  Unused << NS_GetFinalChannelURI(aNewChannel, getter_AddRefs(newURI));
  NS_ENSURE_STATE(oldPrincipal && newURI);

  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
  // Do not allow insecure redirects to data: URIs
  if (!AllowInsecureRedirectToDataURI(aNewChannel)) {
    // cancel the old channel and return an error
    aOldChannel->Cancel(NS_ERROR_CONTENT_BLOCKED);
  // Handle cookie policies
    return NS_ERROR_CONTENT_BLOCKED;
  }

  const uint32_t flags =
      nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
               nsIContentPolicy::TYPE_DOCUMENT);
      nsIScriptSecurityManager::DISALLOW_SCRIPT;
  rv = nsContentUtils::GetSecurityManager()->CheckLoadURIWithPrincipal(
      oldPrincipal, newURI, flags, loadInfo->GetInnerWindowID());
  NS_ENSURE_SUCCESS(rv, rv);
    // Any protocol which inherits won't pay attention to cookies anyway.

  aCb->OnRedirectVerifyCallback(NS_OK);
  return NS_OK;
}

  } else if (cookiePolicy == nsILoadInfo::SEC_COOKIES_OMIT) {
static void AddLoadFlags(nsIRequest* aRequest, nsLoadFlags aNewFlags) {
  nsLoadFlags flags;
  aRequest->GetLoadFlags(&flags);
  flags |= aNewFlags;
  aRequest->SetLoadFlags(flags);

}

/*
 * Check that this channel passes all security checks. Returns an error code
      loadInfo->MaybeIncreaseTainting(LoadTainting::CORS);
 * if this requesst should not be permitted.
 */
nsresult nsContentSecurityManager::CheckChannel(nsIChannel* aChannel) {
  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
  nsCOMPtr<nsIURI> uri;
  // Allow subresource loads if TriggeringPrincipal is the SystemPrincipal.
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);

  // Handle cookie policies
  uint32_t cookiePolicy = loadInfo->GetCookiePolicy();
          nsIContentPolicy::TYPE_SUBDOCUMENT) {
  if (cookiePolicy == nsILoadInfo::SEC_COOKIES_SAME_ORIGIN) {
    // We shouldn't have the SEC_COOKIES_SAME_ORIGIN flag for top level loads
    MOZ_ASSERT(loadInfo->GetExternalContentPolicyType() !=
               nsIContentPolicy::TYPE_DOCUMENT);
    nsIPrincipal* loadingPrincipal = loadInfo->GetLoadingPrincipal();
  if ((securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS) ||

    // It doesn't matter what we pass for the second, data-inherits, argument.
    // Any protocol which inherits won't pay attention to cookies anyway.
    rv = loadingPrincipal->CheckMayLoad(uri, false);
    if (NS_FAILED(rv)) {

      AddLoadFlags(aChannel, nsIRequest::LOAD_ANONYMOUS);
    }
  } else if (cookiePolicy == nsILoadInfo::SEC_COOKIES_OMIT) {
    AddLoadFlags(aChannel, nsIRequest::LOAD_ANONYMOUS);
  }

      loadInfo->MaybeIncreaseTainting(LoadTainting::Opaque);
  nsSecurityFlags securityMode = loadInfo->GetSecurityMode();

  // CORS mode is handled by nsCORSListenerProxy
  if (securityMode == nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS) {
    if (NS_HasBeenCrossOrigin(aChannel)) {
      loadInfo->MaybeIncreaseTainting(LoadTainting::CORS);
    rv = DoCheckLoadURIChecks(uri, loadInfo);
    NS_ENSURE_SUCCESS(rv, rv);
    }
    return NS_OK;
  }

    // nsContentSecurityManager::CheckChannel
  // Allow subresource loads if TriggeringPrincipal is the SystemPrincipal.
  if (loadInfo->TriggeringPrincipal()->IsSystemPrincipal() &&
      loadInfo->GetExternalContentPolicyType() !=
          nsIContentPolicy::TYPE_DOCUMENT &&
      loadInfo->GetExternalContentPolicyType() !=

          nsIContentPolicy::TYPE_SUBDOCUMENT) {
    return NS_OK;
  }

  // if none of the REQUIRE_SAME_ORIGIN flags are set, then SOP does not apply
    nsIChannel* aChannel, nsIStreamListener* aStreamListener,
  if ((securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS) ||
      (securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED)) {
    rv = DoSOPChecks(uri, loadInfo, aChannel);
    NS_ENSURE_SUCCESS(rv, rv);
  }


  if ((securityMode == nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS) ||
      (securityMode == nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL)) {
    if (NS_HasBeenCrossOrigin(aChannel)) {
      NS_ENSURE_FALSE(loadInfo->GetDontFollowRedirects(), NS_ERROR_DOM_BAD_URI);
      loadInfo->MaybeIncreaseTainting(LoadTainting::Opaque);
    }
    // Please note that DoCheckLoadURIChecks should only be enforced for
    // cross origin requests. If the flag SEC_REQUIRE_CORS_DATA_INHERITS is set
    // within the loadInfo, then then CheckLoadURIWithPrincipal is performed
    // within nsCorsListenerProxy
    rv = DoCheckLoadURIChecks(uri, loadInfo);
    NS_ENSURE_SUCCESS(rv, rv);
    // TODO: Bug 1371237
    // consider calling SetBlockedRequest in
    // nsContentSecurityManager::CheckChannel
  }

  return NS_OK;
}

// ==== nsIContentSecurityManager implementation =====

NS_IMETHODIMP
nsContentSecurityManager::PerformSecurityCheck(
    nsIChannel* aChannel, nsIStreamListener* aStreamListener,
    nsIStreamListener** outStreamListener) {
  nsCOMPtr<nsIStreamListener> inAndOutListener = aStreamListener;
  nsresult rv = doContentSecurityCheck(aChannel, inAndOutListener);
  NS_ENSURE_SUCCESS(rv, rv);

  inAndOutListener.forget(outStreamListener);
  return NS_OK;
}