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
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
|
/* -*- 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 <string>
#include <unordered_set>
#include "nsCOMPtr.h"
#include "nsContentPolicyUtils.h"
#include "nsContentUtils.h"
#include "nsCSPContext.h"
#include "nsCSPParser.h"
#include "nsCSPService.h"
#include "nsGlobalWindowOuter.h"
#include "nsError.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsIClassInfoImpl.h"
#include "mozilla/dom/Document.h"
#include "nsIHttpChannel.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"
#include "nsIStringStream.h"
#include "nsISupportsPrimitives.h"
#include "nsIUploadChannel.h"
#include "nsIURIMutator.h"
#include "nsIScriptError.h"
#include "nsMimeTypes.h"
#include "nsNetUtil.h"
#include "nsIContentPolicy.h"
#include "nsSupportsPrimitives.h"
#include "nsThreadUtils.h"
#include "nsString.h"
#include "nsScriptSecurityManager.h"
#include "nsStringStream.h"
#include "mozilla/Logging.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/dom/CSPReportBinding.h"
#include "mozilla/dom/CSPDictionariesBinding.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "nsINetworkInterceptController.h"
#include "nsSandboxFlags.h"
#include "nsIScriptElement.h"
#include "nsIEventTarget.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/Element.h"
#include "nsXULAppAPI.h"
#include "nsJSUtils.h"
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::ipc;
static LogModule* GetCspContextLog() {
static LazyLogModule gCspContextPRLog("CSPContext");
return gCspContextPRLog;
}
#define CSPCONTEXTLOG(args) \
MOZ_LOG(GetCspContextLog(), mozilla::LogLevel::Debug, args)
#define CSPCONTEXTLOGENABLED() \
MOZ_LOG_TEST(GetCspContextLog(), mozilla::LogLevel::Debug)
static LogModule* GetCspOriginLogLog() {
static LazyLogModule gCspOriginPRLog("CSPOrigin");
return gCspOriginPRLog;
}
#define CSPORIGINLOG(args) \
MOZ_LOG(GetCspOriginLogLog(), mozilla::LogLevel::Debug, args)
#define CSPORIGINLOGENABLED() \
MOZ_LOG_TEST(GetCspOriginLogLog(), mozilla::LogLevel::Debug)
#ifdef DEBUG
/**
* This function is only used for verification purposes within
* GatherSecurityPolicyViolationEventData.
*/
static bool ValidateDirectiveName(const nsAString& aDirective) {
static const auto directives = []() {
std::unordered_set<std::string> directives;
constexpr size_t dirLen =
sizeof(CSPStrDirectives) / sizeof(CSPStrDirectives[0]);
for (size_t i = 0; i < dirLen; ++i) {
directives.insert(CSPStrDirectives[i]);
}
return directives;
}();
nsAutoString directive(aDirective);
auto itr = directives.find(NS_ConvertUTF16toUTF8(directive).get());
return itr != directives.end();
}
#endif // DEBUG
static void BlockedContentSourceToString(
nsCSPContext::BlockedContentSource aSource, nsACString& aString) {
switch (aSource) {
case nsCSPContext::BlockedContentSource::eUnknown:
aString.Truncate();
break;
case nsCSPContext::BlockedContentSource::eInline:
aString.AssignLiteral("inline");
break;
case nsCSPContext::BlockedContentSource::eEval:
aString.AssignLiteral("eval");
break;
case nsCSPContext::BlockedContentSource::eSelf:
aString.AssignLiteral("self");
break;
case nsCSPContext::BlockedContentSource::eWasmEval:
aString.AssignLiteral("wasm-eval");
break;
}
}
/* ===== nsIContentSecurityPolicy impl ====== */
NS_IMETHODIMP
nsCSPContext::ShouldLoad(nsContentPolicyType aContentType,
nsICSPEventListener* aCSPEventListener,
nsIURI* aContentLocation,
nsIURI* aOriginalURIIfRedirect,
bool aSendViolationReports, const nsAString& aNonce,
bool aParserCreated, int16_t* outDecision) {
if (CSPCONTEXTLOGENABLED()) {
CSPCONTEXTLOG(("nsCSPContext::ShouldLoad, aContentLocation: %s",
aContentLocation->GetSpecOrDefault().get()));
CSPCONTEXTLOG((">>>> aContentType: %d", aContentType));
}
// This ShouldLoad function is called from nsCSPService::ShouldLoad,
// which already checked a number of things, including:
// * aContentLocation is not null; we can consume this without further checks
// * scheme is not a allowlisted scheme (about: chrome:, etc).
// * CSP is enabled
// * Content Type is not allowlisted (CSP Reports, TYPE_DOCUMENT, etc).
// * Fast Path for Apps
// Default decision, CSP can revise it if there's a policy to enforce
*outDecision = nsIContentPolicy::ACCEPT;
// If the content type doesn't map to a CSP directive, there's nothing for
// CSP to do.
CSPDirective dir = CSP_ContentTypeToDirective(aContentType);
if (dir == nsIContentSecurityPolicy::NO_DIRECTIVE) {
return NS_OK;
}
bool permitted = permitsInternal(
dir,
nullptr, // aTriggeringElement
aCSPEventListener, aContentLocation, aOriginalURIIfRedirect, aNonce,
false, // allow fallback to default-src
aSendViolationReports,
true, // send blocked URI in violation reports
aParserCreated);
*outDecision =
permitted ? nsIContentPolicy::ACCEPT : nsIContentPolicy::REJECT_SERVER;
if (CSPCONTEXTLOGENABLED()) {
CSPCONTEXTLOG(
("nsCSPContext::ShouldLoad, decision: %s, "
"aContentLocation: %s",
*outDecision > 0 ? "load" : "deny",
aContentLocation->GetSpecOrDefault().get()));
}
return NS_OK;
}
bool nsCSPContext::permitsInternal(
CSPDirective aDir, Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener, nsIURI* aContentLocation,
nsIURI* aOriginalURIIfRedirect, const nsAString& aNonce, bool aSpecific,
bool aSendViolationReports, bool aSendContentLocationInViolationReports,
bool aParserCreated) {
EnsureIPCPoliciesRead();
bool permits = true;
nsAutoString violatedDirective;
for (uint32_t p = 0; p < mPolicies.Length(); p++) {
if (!mPolicies[p]->permits(aDir, aContentLocation, aNonce,
!!aOriginalURIIfRedirect, aSpecific,
aParserCreated, violatedDirective)) {
// If the policy is violated and not report-only, reject the load and
// report to the console
if (!mPolicies[p]->getReportOnlyFlag()) {
CSPCONTEXTLOG(("nsCSPContext::permitsInternal, false"));
permits = false;
}
// In CSP 3.0 the effective directive doesn't become the actually used
// directive in case of a fallback from e.g. script-src-elem to
// script-src or default-src.
nsAutoString effectiveDirective;
effectiveDirective.AssignASCII(CSP_CSPDirectiveToString(aDir));
// Callers should set |aSendViolationReports| to false if this is a
// preload - the decision may be wrong due to the inability to get the
// nonce, and will incorrectly fail the unit tests.
if (aSendViolationReports) {
uint32_t lineNumber = 0;
uint32_t columnNumber = 0;
nsAutoString spec;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, spec, &lineNumber, &columnNumber);
// If GetCallingLocation fails linenumber & columnNumber are set to 0
// anyway so we can skip checking if that is the case.
}
AsyncReportViolation(
aTriggeringElement, aCSPEventListener,
(aSendContentLocationInViolationReports ? aContentLocation
: nullptr),
BlockedContentSource::eUnknown, /* a BlockedContentSource */
aOriginalURIIfRedirect, /* in case of redirect originalURI is not
null */
violatedDirective, effectiveDirective, p, /* policy index */
u""_ns, /* no observer subject */
spec, /* source file */
false, // aReportSample (no sample)
u""_ns, /* no script sample */
lineNumber, /* line number */
columnNumber); /* column number */
}
}
}
return permits;
}
/* ===== nsISupports implementation ========== */
NS_IMPL_CLASSINFO(nsCSPContext, nullptr, nsIClassInfo::MAIN_THREAD_ONLY,
NS_CSPCONTEXT_CID)
NS_IMPL_ISUPPORTS_CI(nsCSPContext, nsIContentSecurityPolicy, nsISerializable)
nsCSPContext::nsCSPContext()
: mInnerWindowID(0),
mSkipAllowInlineStyleCheck(false),
mLoadingContext(nullptr),
mLoadingPrincipal(nullptr),
mQueueUpMessages(true) {
CSPCONTEXTLOG(("nsCSPContext::nsCSPContext"));
}
nsCSPContext::~nsCSPContext() {
CSPCONTEXTLOG(("nsCSPContext::~nsCSPContext"));
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
delete mPolicies[i];
}
}
/* static */
bool nsCSPContext::Equals(nsIContentSecurityPolicy* aCSP,
nsIContentSecurityPolicy* aOtherCSP) {
if (aCSP == aOtherCSP) {
// fast path for pointer equality
return true;
}
uint32_t policyCount = 0;
if (aCSP) {
aCSP->GetPolicyCount(&policyCount);
}
uint32_t otherPolicyCount = 0;
if (aOtherCSP) {
aOtherCSP->GetPolicyCount(&otherPolicyCount);
}
if (policyCount != otherPolicyCount) {
return false;
}
nsAutoString policyStr, otherPolicyStr;
for (uint32_t i = 0; i < policyCount; ++i) {
aCSP->GetPolicyString(i, policyStr);
aOtherCSP->GetPolicyString(i, otherPolicyStr);
if (!policyStr.Equals(otherPolicyStr)) {
return false;
}
}
return true;
}
nsresult nsCSPContext::InitFromOther(nsCSPContext* aOtherContext) {
NS_ENSURE_ARG(aOtherContext);
nsresult rv = NS_OK;
nsCOMPtr<Document> doc = do_QueryReferent(aOtherContext->mLoadingContext);
if (doc) {
rv = SetRequestContextWithDocument(doc);
} else {
rv = SetRequestContextWithPrincipal(
aOtherContext->mLoadingPrincipal, aOtherContext->mSelfURI,
aOtherContext->mReferrer, aOtherContext->mInnerWindowID);
}
NS_ENSURE_SUCCESS(rv, rv);
mSkipAllowInlineStyleCheck = aOtherContext->mSkipAllowInlineStyleCheck;
// This policy was already parsed somewhere else, don't emit parsing errors.
mSuppressParserLogMessages = true;
for (auto policy : aOtherContext->mPolicies) {
nsAutoString policyStr;
policy->toString(policyStr);
AppendPolicy(policyStr, policy->getReportOnlyFlag(),
policy->getDeliveredViaMetaTagFlag());
}
mSuppressParserLogMessages = aOtherContext->mSuppressParserLogMessages;
mIPCPolicies = aOtherContext->mIPCPolicies.Clone();
return NS_OK;
}
void nsCSPContext::EnsureIPCPoliciesRead() {
// Most likely the parser errors already happened before serializing
// the policy for IPC.
bool previous = mSuppressParserLogMessages;
mSuppressParserLogMessages = true;
if (mIPCPolicies.Length() > 0) {
nsresult rv;
for (auto& policy : mIPCPolicies) {
rv = AppendPolicy(policy.policy(), policy.reportOnlyFlag(),
policy.deliveredViaMetaTagFlag());
Unused << NS_WARN_IF(NS_FAILED(rv));
}
mIPCPolicies.Clear();
}
mSuppressParserLogMessages = previous;
}
NS_IMETHODIMP
nsCSPContext::GetPolicyString(uint32_t aIndex, nsAString& outStr) {
outStr.Truncate();
EnsureIPCPoliciesRead();
if (aIndex >= mPolicies.Length()) {
return NS_ERROR_ILLEGAL_VALUE;
}
mPolicies[aIndex]->toString(outStr);
return NS_OK;
}
const nsCSPPolicy* nsCSPContext::GetPolicy(uint32_t aIndex) {
EnsureIPCPoliciesRead();
if (aIndex >= mPolicies.Length()) {
return nullptr;
}
return mPolicies[aIndex];
}
NS_IMETHODIMP
nsCSPContext::GetPolicyCount(uint32_t* outPolicyCount) {
EnsureIPCPoliciesRead();
*outPolicyCount = mPolicies.Length();
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetUpgradeInsecureRequests(bool* outUpgradeRequest) {
EnsureIPCPoliciesRead();
*outUpgradeRequest = false;
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
if (mPolicies[i]->hasDirective(
nsIContentSecurityPolicy::UPGRADE_IF_INSECURE_DIRECTIVE)) {
*outUpgradeRequest = true;
return NS_OK;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetBlockAllMixedContent(bool* outBlockAllMixedContent) {
EnsureIPCPoliciesRead();
*outBlockAllMixedContent = false;
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
if (!mPolicies[i]->getReportOnlyFlag() &&
mPolicies[i]->hasDirective(
nsIContentSecurityPolicy::BLOCK_ALL_MIXED_CONTENT)) {
*outBlockAllMixedContent = true;
return NS_OK;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetEnforcesFrameAncestors(bool* outEnforcesFrameAncestors) {
EnsureIPCPoliciesRead();
*outEnforcesFrameAncestors = false;
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
if (!mPolicies[i]->getReportOnlyFlag() &&
mPolicies[i]->hasDirective(
nsIContentSecurityPolicy::FRAME_ANCESTORS_DIRECTIVE)) {
*outEnforcesFrameAncestors = true;
return NS_OK;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::AppendPolicy(const nsAString& aPolicyString, bool aReportOnly,
bool aDeliveredViaMetaTag) {
CSPCONTEXTLOG(("nsCSPContext::AppendPolicy: %s",
NS_ConvertUTF16toUTF8(aPolicyString).get()));
// Use mSelfURI from setRequestContextWith{Document,Principal} (bug 991474)
MOZ_ASSERT(
mLoadingPrincipal,
"did you forget to call setRequestContextWith{Document,Principal}?");
MOZ_ASSERT(
mSelfURI,
"did you forget to call setRequestContextWith{Document,Principal}?");
NS_ENSURE_TRUE(mLoadingPrincipal, NS_ERROR_UNEXPECTED);
NS_ENSURE_TRUE(mSelfURI, NS_ERROR_UNEXPECTED);
if (CSPORIGINLOGENABLED()) {
nsAutoCString selfURISpec;
mSelfURI->GetSpec(selfURISpec);
CSPORIGINLOG(("CSP - AppendPolicy"));
CSPORIGINLOG((" * selfURI: %s", selfURISpec.get()));
CSPORIGINLOG((" * reportOnly: %s", aReportOnly ? "yes" : "no"));
CSPORIGINLOG(
(" * deliveredViaMetaTag: %s", aDeliveredViaMetaTag ? "yes" : "no"));
CSPORIGINLOG(
(" * policy: %s\n", NS_ConvertUTF16toUTF8(aPolicyString).get()));
}
nsCSPPolicy* policy = nsCSPParser::parseContentSecurityPolicy(
aPolicyString, mSelfURI, aReportOnly, this, aDeliveredViaMetaTag,
mSuppressParserLogMessages);
if (policy) {
if (policy->hasDirective(
nsIContentSecurityPolicy::UPGRADE_IF_INSECURE_DIRECTIVE)) {
nsAutoCString selfURIspec, referrer;
if (mSelfURI) {
mSelfURI->GetAsciiSpec(selfURIspec);
}
CopyUTF16toUTF8(mReferrer, referrer);
CSPCONTEXTLOG(
("nsCSPContext::AppendPolicy added UPGRADE_IF_INSECURE_DIRECTIVE "
"self-uri=%s referrer=%s",
selfURIspec.get(), referrer.get()));
}
mPolicies.AppendElement(policy);
// set the flag on the document for CSP telemetry
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc) {
doc->SetHasCSP(true);
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetAllowsEval(bool* outShouldReportViolation,
bool* outAllowsEval) {
EnsureIPCPoliciesRead();
*outShouldReportViolation = false;
*outAllowsEval = true;
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
if (!mPolicies[i]->allows(SCRIPT_SRC_DIRECTIVE, CSP_UNSAFE_EVAL, u""_ns,
false)) {
// policy is violated: must report the violation and allow the inline
// script if the policy is report-only.
*outShouldReportViolation = true;
if (!mPolicies[i]->getReportOnlyFlag()) {
*outAllowsEval = false;
}
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetAllowsWasmEval(bool* outShouldReportViolation,
bool* outAllowsWasmEval) {
EnsureIPCPoliciesRead();
*outShouldReportViolation = false;
*outAllowsWasmEval = true;
if (!StaticPrefs::security_csp_wasm_unsafe_eval_enabled()) {
// Allow and don't report when wasm-unsafe-eval isn't supported.
return NS_OK;
}
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
// Either 'unsafe-eval' or 'wasm-unsafe-eval' can allow this
if (!mPolicies[i]->allows(SCRIPT_SRC_DIRECTIVE, CSP_WASM_UNSAFE_EVAL,
u""_ns, false) &&
!mPolicies[i]->allows(SCRIPT_SRC_DIRECTIVE, CSP_UNSAFE_EVAL, u""_ns,
false)) {
// policy is violated: must report the violation and allow the inline
// script if the policy is report-only.
*outShouldReportViolation = true;
if (!mPolicies[i]->getReportOnlyFlag()) {
*outAllowsWasmEval = false;
}
}
}
return NS_OK;
}
// Helper function to report inline violations
void nsCSPContext::reportInlineViolation(
CSPDirective aDirective, Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener, const nsAString& aNonce,
bool aReportSample, const nsAString& aSample,
const nsAString& aViolatedDirective, const nsAString& aEffectiveDirective,
uint32_t aViolatedPolicyIndex, // TODO, use report only flag for that
uint32_t aLineNumber, uint32_t aColumnNumber) {
nsString observerSubject;
// if the nonce is non empty, then we report the nonce error, otherwise
// let's report the hash error; no need to report the unsafe-inline error
// anymore.
if (!aNonce.IsEmpty()) {
observerSubject = (aDirective == SCRIPT_SRC_ELEM_DIRECTIVE ||
aDirective == SCRIPT_SRC_ATTR_DIRECTIVE)
? NS_LITERAL_STRING_FROM_CSTRING(
SCRIPT_NONCE_VIOLATION_OBSERVER_TOPIC)
: NS_LITERAL_STRING_FROM_CSTRING(
STYLE_NONCE_VIOLATION_OBSERVER_TOPIC);
} else {
observerSubject = (aDirective == SCRIPT_SRC_ELEM_DIRECTIVE ||
aDirective == SCRIPT_SRC_ATTR_DIRECTIVE)
? NS_LITERAL_STRING_FROM_CSTRING(
SCRIPT_HASH_VIOLATION_OBSERVER_TOPIC)
: NS_LITERAL_STRING_FROM_CSTRING(
STYLE_HASH_VIOLATION_OBSERVER_TOPIC);
}
nsAutoString sourceFile;
uint32_t lineNumber;
uint32_t columnNumber;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (!cx || !nsJSUtils::GetCallingLocation(cx, sourceFile, &lineNumber,
&columnNumber)) {
// use selfURI as the sourceFile
if (mSelfURI) {
nsAutoCString cSourceFile;
mSelfURI->GetSpec(cSourceFile);
sourceFile.Assign(NS_ConvertUTF8toUTF16(cSourceFile));
}
lineNumber = aLineNumber;
columnNumber = aColumnNumber;
}
AsyncReportViolation(aTriggeringElement, aCSPEventListener,
nullptr, // aBlockedURI
BlockedContentSource::eInline, // aBlockedSource
mSelfURI, // aOriginalURI
aViolatedDirective, // aViolatedDirective
aEffectiveDirective, // aEffectiveDirective
aViolatedPolicyIndex, // aViolatedPolicyIndex
observerSubject, // aObserverSubject
sourceFile, // aSourceFile
aReportSample, // aReportSample
aSample, // aScriptSample
lineNumber, // aLineNum
columnNumber); // aColumnNum
}
NS_IMETHODIMP
nsCSPContext::GetAllowsInline(CSPDirective aDirective, bool aHasUnsafeHash,
const nsAString& aNonce, bool aParserCreated,
Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener,
const nsAString& aContentOfPseudoScript,
uint32_t aLineNumber, uint32_t aColumnNumber,
bool* outAllowsInline) {
*outAllowsInline = true;
if (aDirective != SCRIPT_SRC_ELEM_DIRECTIVE &&
aDirective != SCRIPT_SRC_ATTR_DIRECTIVE &&
aDirective != STYLE_SRC_ELEM_DIRECTIVE &&
aDirective != STYLE_SRC_ATTR_DIRECTIVE) {
MOZ_ASSERT(false,
"can only allow inline for (script/style)-src-(attr/elem)");
return NS_OK;
}
EnsureIPCPoliciesRead();
nsAutoString content(u""_ns);
// always iterate all policies, otherwise we might not send out all reports
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
bool allowed =
mPolicies[i]->allows(aDirective, CSP_UNSAFE_INLINE, u""_ns,
aParserCreated) ||
mPolicies[i]->allows(aDirective, CSP_NONCE, aNonce, aParserCreated);
// If the inlined script or style is allowed by either unsafe-inline or the
// nonce, go ahead and shortcut this loop so we can avoid allocating
// unecessary strings
if (allowed) {
continue;
}
// Check the content length to ensure the content is not allocated more than
// once. Even though we are in a for loop, it is probable that there is only
// one policy, so this check may be unnecessary.
if (content.IsEmpty() && aTriggeringElement) {
nsCOMPtr<nsIScriptElement> element =
do_QueryInterface(aTriggeringElement);
if (element) {
element->GetScriptText(content);
}
}
if (content.IsEmpty()) {
content = aContentOfPseudoScript;
}
// Per https://w3c.github.io/webappsec-csp/#match-element-to-source-list
// Step 5. If type is "script" or "style", or unsafe-hashes flag is true:
//
// aHasUnsafeHash is true for event handlers (type "script attribute"),
// style= attributes (type "style attribute") and the javascript: protocol.
if (!aHasUnsafeHash || mPolicies[i]->allows(aDirective, CSP_UNSAFE_HASHES,
u""_ns, aParserCreated)) {
allowed =
mPolicies[i]->allows(aDirective, CSP_HASH, content, aParserCreated);
}
if (!allowed) {
// policy is violoated: deny the load unless policy is report only and
// report the violation.
if (!mPolicies[i]->getReportOnlyFlag()) {
*outAllowsInline = false;
}
nsAutoString violatedDirective;
bool reportSample = false;
mPolicies[i]->getDirectiveStringAndReportSampleForContentType(
aDirective, violatedDirective, &reportSample);
// In CSP 3.0 the effective directive doesn't become the actually used
// directive in case of a fallback from e.g. script-src-elem to
// script-src or default-src.
nsAutoString effectiveDirective;
effectiveDirective.AssignASCII(CSP_CSPDirectiveToString(aDirective));
reportInlineViolation(aDirective, aTriggeringElement, aCSPEventListener,
aNonce, reportSample, content, violatedDirective,
effectiveDirective, i, aLineNumber, aColumnNumber);
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetAllowsNavigateTo(nsIURI* aURI, bool aIsFormSubmission,
bool aWasRedirected, bool aEnforceAllowlist,
bool* outAllowsNavigateTo) {
/*
* The matrix below shows the different values of (aWasRedirect,
* aEnforceAllowlist) for the three different checks we do.
*
* Navigation | Start Loading | Initiate Redirect | Document
* | (nsDocShell) | (nsCSPService) |
* -----------------------------------------------------------------
* A -> B (false,false) - (false,true)
* A -> ... -> B (false,false) (true,false) (true,true)
*/
*outAllowsNavigateTo = false;
EnsureIPCPoliciesRead();
// The 'form-action' directive overrules 'navigate-to' for form submissions.
// So in case this is a form submission and the directive 'form-action' is
// present then there is nothing for us to do here, see: 6.3.3.1.2
// https://www.w3.org/TR/CSP3/#navigate-to-pre-navigate
if (aIsFormSubmission) {
for (unsigned long i = 0; i < mPolicies.Length(); i++) {
if (mPolicies[i]->hasDirective(
nsIContentSecurityPolicy::FORM_ACTION_DIRECTIVE)) {
*outAllowsNavigateTo = true;
return NS_OK;
}
}
}
bool atLeastOneBlock = false;
for (unsigned long i = 0; i < mPolicies.Length(); i++) {
if (!mPolicies[i]->allowsNavigateTo(aURI, aWasRedirected,
aEnforceAllowlist)) {
if (!mPolicies[i]->getReportOnlyFlag()) {
atLeastOneBlock = true;
}
// If the load encountered a server side redirect, the spec suggests to
// remove the path component from the URI, see:
// https://www.w3.org/TR/CSP3/#source-list-paths-and-redirects
nsCOMPtr<nsIURI> blockedURIForReporting = aURI;
if (aWasRedirected) {
nsAutoCString prePathStr;
nsCOMPtr<nsIURI> prePathURI;
nsresult rv = aURI->GetPrePath(prePathStr);
NS_ENSURE_SUCCESS(rv, rv);
rv = NS_NewURI(getter_AddRefs(blockedURIForReporting), prePathStr);
NS_ENSURE_SUCCESS(rv, rv);
}
// Lines numbers and source file for the violation report
uint32_t lineNumber = 0;
uint32_t columnNumber = 0;
nsAutoCString spec;
JSContext* cx = nsContentUtils::GetCurrentJSContext();
if (cx) {
nsJSUtils::GetCallingLocation(cx, spec, &lineNumber, &columnNumber);
// If GetCallingLocation fails linenumber & columnNumber are set to 0
// anyway so we can skip checking if that is the case.
}
// Report the violation
nsresult rv = AsyncReportViolation(
nullptr, // aTriggeringElement
nullptr, // aCSPEventListener
blockedURIForReporting, // aBlockedURI
nsCSPContext::BlockedContentSource::eSelf, // aBlockedSource
nullptr, // aOriginalURI
u"navigate-to"_ns, // aViolatedDirective
u"navigate-to"_ns, // aEffectiveDirective
i, // aViolatedPolicyIndex
u""_ns, // aObserverSubject
NS_ConvertUTF8toUTF16(spec), // aSourceFile
false, // aReportSample
u""_ns, // aScriptSample
lineNumber, // aLineNum
columnNumber); // aColumnNum
NS_ENSURE_SUCCESS(rv, rv);
}
}
*outAllowsNavigateTo = !atLeastOneBlock;
return NS_OK;
}
/**
* For each policy, log any violation on the Error Console and send a report
* if a report-uri is present in the policy
*
* @param aViolationType
* one of the VIOLATION_TYPE_* constants, e.g. inline-script or eval
* @param aSourceFile
* name of the source file containing the violation (if available)
* @param aContentSample
* sample of the violating content (to aid debugging)
* @param aLineNum
* source line number of the violation (if available)
* @param aColumnNum
* source column number of the violation (if available)
* @param aNonce
* (optional) If this is a nonce violation, include the nonce so we can
* recheck to determine which policies were violated and send the
* appropriate reports.
* @param aContent
* (optional) If this is a hash violation, include contents of the inline
* resource in the question so we can recheck the hash in order to
* determine which policies were violated and send the appropriate
* reports.
*/
NS_IMETHODIMP
nsCSPContext::LogViolationDetails(
uint16_t aViolationType, Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener, const nsAString& aSourceFile,
const nsAString& aScriptSample, int32_t aLineNum, int32_t aColumnNum,
const nsAString& aNonce, const nsAString& aContent) {
EnsureIPCPoliciesRead();
BlockedContentSource blockedContentSource;
enum CSPKeyword keyword;
nsAutoString observerSubject;
if (aViolationType == nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL) {
blockedContentSource = BlockedContentSource::eEval;
keyword = CSP_UNSAFE_EVAL;
observerSubject.AssignLiteral(EVAL_VIOLATION_OBSERVER_TOPIC);
} else {
NS_ASSERTION(
aViolationType == nsIContentSecurityPolicy::VIOLATION_TYPE_WASM_EVAL,
"unexpected aViolationType");
blockedContentSource = BlockedContentSource::eWasmEval;
keyword = CSP_WASM_UNSAFE_EVAL;
observerSubject.AssignLiteral(WASM_EVAL_VIOLATION_OBSERVER_TOPIC);
}
for (uint32_t p = 0; p < mPolicies.Length(); p++) {
NS_ASSERTION(mPolicies[p], "null pointer in nsTArray<nsCSPPolicy>");
if (mPolicies[p]->allows(SCRIPT_SRC_DIRECTIVE, keyword, u""_ns, false)) {
continue;
}
nsAutoString violatedDirective;
bool reportSample = false;
mPolicies[p]->getDirectiveStringAndReportSampleForContentType(
SCRIPT_SRC_DIRECTIVE, violatedDirective, &reportSample);
AsyncReportViolation(aTriggeringElement, aCSPEventListener, nullptr,
blockedContentSource, nullptr, violatedDirective,
u"script-src"_ns /* aEffectiveDirective */, p,
observerSubject, aSourceFile, reportSample,
aScriptSample, aLineNum, aColumnNum);
}
return NS_OK;
}
#undef CASE_CHECK_AND_REPORT
NS_IMETHODIMP
nsCSPContext::SetRequestContextWithDocument(Document* aDocument) {
MOZ_ASSERT(aDocument, "Can't set context without doc");
NS_ENSURE_ARG(aDocument);
mLoadingContext = do_GetWeakReference(aDocument);
mSelfURI = aDocument->GetDocumentURI();
mLoadingPrincipal = aDocument->NodePrincipal();
aDocument->GetReferrer(mReferrer);
mInnerWindowID = aDocument->InnerWindowID();
// the innerWindowID is not available for CSPs delivered through the
// header at the time setReqeustContext is called - let's queue up
// console messages until it becomes available, see flushConsoleMessages
mQueueUpMessages = !mInnerWindowID;
mCallingChannelLoadGroup = aDocument->GetDocumentLoadGroup();
// set the flag on the document for CSP telemetry
mEventTarget = aDocument->EventTargetFor(TaskCategory::Other);
MOZ_ASSERT(mLoadingPrincipal, "need a valid requestPrincipal");
MOZ_ASSERT(mSelfURI, "need mSelfURI to translate 'self' into actual URI");
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::SetRequestContextWithPrincipal(nsIPrincipal* aRequestPrincipal,
nsIURI* aSelfURI,
const nsAString& aReferrer,
uint64_t aInnerWindowId) {
NS_ENSURE_ARG(aRequestPrincipal);
mLoadingPrincipal = aRequestPrincipal;
mSelfURI = aSelfURI;
mReferrer = aReferrer;
mInnerWindowID = aInnerWindowId;
// if no document is available, then it also does not make sense to queue
// console messages sending messages to the browser console instead of the web
// console in that case.
mQueueUpMessages = false;
mCallingChannelLoadGroup = nullptr;
mEventTarget = nullptr;
MOZ_ASSERT(mLoadingPrincipal, "need a valid requestPrincipal");
MOZ_ASSERT(mSelfURI, "need mSelfURI to translate 'self' into actual URI");
return NS_OK;
}
nsIPrincipal* nsCSPContext::GetRequestPrincipal() { return mLoadingPrincipal; }
nsIURI* nsCSPContext::GetSelfURI() { return mSelfURI; }
NS_IMETHODIMP
nsCSPContext::GetReferrer(nsAString& outReferrer) {
outReferrer.Truncate();
outReferrer.Append(mReferrer);
return NS_OK;
}
uint64_t nsCSPContext::GetInnerWindowID() { return mInnerWindowID; }
bool nsCSPContext::GetSkipAllowInlineStyleCheck() {
return mSkipAllowInlineStyleCheck;
}
void nsCSPContext::SetSkipAllowInlineStyleCheck(
bool aSkipAllowInlineStyleCheck) {
mSkipAllowInlineStyleCheck = aSkipAllowInlineStyleCheck;
}
NS_IMETHODIMP
nsCSPContext::EnsureEventTarget(nsIEventTarget* aEventTarget) {
NS_ENSURE_ARG(aEventTarget);
// Don't bother if we did have a valid event target (if the csp object is
// tied to a document in SetRequestContextWithDocument)
if (mEventTarget) {
return NS_OK;
}
mEventTarget = aEventTarget;
return NS_OK;
}
struct ConsoleMsgQueueElem {
nsString mMsg;
nsString mSourceName;
nsString mSourceLine;
uint32_t mLineNumber;
uint32_t mColumnNumber;
uint32_t mSeverityFlag;
nsCString mCategory;
};
void nsCSPContext::flushConsoleMessages() {
bool privateWindow = false;
// should flush messages even if doc is not available
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc) {
mInnerWindowID = doc->InnerWindowID();
privateWindow =
!!doc->NodePrincipal()->OriginAttributesRef().mPrivateBrowsingId;
}
mQueueUpMessages = false;
for (uint32_t i = 0; i < mConsoleMsgQueue.Length(); i++) {
ConsoleMsgQueueElem& elem = mConsoleMsgQueue[i];
CSP_LogMessage(elem.mMsg, elem.mSourceName, elem.mSourceLine,
elem.mLineNumber, elem.mColumnNumber, elem.mSeverityFlag,
elem.mCategory, mInnerWindowID, privateWindow);
}
mConsoleMsgQueue.Clear();
}
void nsCSPContext::logToConsole(const char* aName,
const nsTArray<nsString>& aParams,
const nsAString& aSourceName,
const nsAString& aSourceLine,
uint32_t aLineNumber, uint32_t aColumnNumber,
uint32_t aSeverityFlag) {
// we are passing aName as the category so we can link to the
// appropriate MDN docs depending on the specific error.
nsDependentCString category(aName);
// Fallback
nsAutoString sourceName(aSourceName);
if (sourceName.IsEmpty() && mSelfURI) {
nsAutoCString spec;
mSelfURI->GetSpec(spec);
CopyUTF8toUTF16(spec, sourceName);
}
// let's check if we have to queue up console messages
if (mQueueUpMessages) {
nsAutoString msg;
CSP_GetLocalizedStr(aName, aParams, msg);
ConsoleMsgQueueElem& elem = *mConsoleMsgQueue.AppendElement();
elem.mMsg = msg;
elem.mSourceName = PromiseFlatString(sourceName);
elem.mSourceLine = PromiseFlatString(aSourceLine);
elem.mLineNumber = aLineNumber;
elem.mColumnNumber = aColumnNumber;
elem.mSeverityFlag = aSeverityFlag;
elem.mCategory = category;
return;
}
bool privateWindow = false;
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc) {
privateWindow =
!!doc->NodePrincipal()->OriginAttributesRef().mPrivateBrowsingId;
}
CSP_LogLocalizedStr(aName, aParams, sourceName, aSourceLine, aLineNumber,
aColumnNumber, aSeverityFlag, category, mInnerWindowID,
privateWindow);
}
/**
* Strip URI for reporting according to:
* https://w3c.github.io/webappsec-csp/#security-violation-reports
*
* @param aSelfURI
* The URI of the CSP policy. Used for cross-origin checks.
* @param aURI
* The URI of the blocked resource. In case of a redirect, this it the
* initial URI the request started out with, not the redirected URI.
* @param aEffectiveDirective
* The effective directive that triggered this report
* @return The ASCII serialization of the uri to be reported ignoring
* the ref part of the URI.
*/
void StripURIForReporting(nsIURI* aSelfURI, nsIURI* aURI,
const nsAString& aEffectiveDirective,
nsACString& outStrippedURI) {
// If the origin of aURI is a globally unique identifier (for example,
// aURI has a scheme of data, blob, or filesystem), then
// return the ASCII serialization of uri’s scheme.
bool isHttpFtpOrWs =
(aURI->SchemeIs("http") || aURI->SchemeIs("https") ||
aURI->SchemeIs("ftp") || aURI->SchemeIs("ws") || aURI->SchemeIs("wss"));
if (!isHttpFtpOrWs) {
// not strictly spec compliant, but what we really care about is
// http/https and also ftp. If it's not http/https or ftp, then treat aURI
// as if it's a globally unique identifier and just return the scheme.
aURI->GetScheme(outStrippedURI);
return;
}
// For cross-origin URIs in frame-src also strip the path.
// This prevents detailed tracking of pages loaded into an iframe
// by the embedding page using a report-only policy.
if (aEffectiveDirective.EqualsLiteral("frame-src") ||
aEffectiveDirective.EqualsLiteral("object-src")) {
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
if (NS_FAILED(ssm->CheckSameOriginURI(aSelfURI, aURI, false, false))) {
aURI->GetPrePath(outStrippedURI);
return;
}
}
// Return aURI, with any fragment component removed.
aURI->GetSpecIgnoringRef(outStrippedURI);
}
nsresult nsCSPContext::GatherSecurityPolicyViolationEventData(
nsIURI* aBlockedURI, const nsACString& aBlockedString, nsIURI* aOriginalURI,
const nsAString& aEffectiveDirective, uint32_t aViolatedPolicyIndex,
const nsAString& aSourceFile, const nsAString& aScriptSample,
uint32_t aLineNum, uint32_t aColumnNum,
mozilla::dom::SecurityPolicyViolationEventInit& aViolationEventInit) {
EnsureIPCPoliciesRead();
NS_ENSURE_ARG_MAX(aViolatedPolicyIndex, mPolicies.Length() - 1);
MOZ_ASSERT(ValidateDirectiveName(aEffectiveDirective),
"Invalid directive name");
nsresult rv;
// document-uri
nsAutoCString reportDocumentURI;
StripURIForReporting(mSelfURI, mSelfURI, aEffectiveDirective,
reportDocumentURI);
CopyUTF8toUTF16(reportDocumentURI, aViolationEventInit.mDocumentURI);
// referrer
aViolationEventInit.mReferrer = mReferrer;
// blocked-uri
if (aBlockedURI) {
nsAutoCString reportBlockedURI;
StripURIForReporting(mSelfURI, aOriginalURI ? aOriginalURI : aBlockedURI,
aEffectiveDirective, reportBlockedURI);
CopyUTF8toUTF16(reportBlockedURI, aViolationEventInit.mBlockedURI);
} else {
CopyUTF8toUTF16(aBlockedString, aViolationEventInit.mBlockedURI);
}
// effective-directive
// The name of the policy directive that was violated.
aViolationEventInit.mEffectiveDirective = aEffectiveDirective;
// violated-directive
// In CSP2, the policy directive that was violated, as it appears in the
// policy. In CSP3, the same as effective-directive.
aViolationEventInit.mViolatedDirective = aEffectiveDirective;
// original-policy
nsAutoString originalPolicy;
rv = this->GetPolicyString(aViolatedPolicyIndex, originalPolicy);
NS_ENSURE_SUCCESS(rv, rv);
aViolationEventInit.mOriginalPolicy = originalPolicy;
// source-file
if (!aSourceFile.IsEmpty()) {
// if aSourceFile is a URI, we have to make sure to strip fragments
nsCOMPtr<nsIURI> sourceURI;
NS_NewURI(getter_AddRefs(sourceURI), aSourceFile);
if (sourceURI) {
nsAutoCString spec;
StripURIForReporting(mSelfURI, sourceURI, aEffectiveDirective, spec);
CopyUTF8toUTF16(spec, aViolationEventInit.mSourceFile);
} else {
aViolationEventInit.mSourceFile = aSourceFile;
}
}
// sample (already truncated)
aViolationEventInit.mSample = aScriptSample;
// disposition
aViolationEventInit.mDisposition =
mPolicies[aViolatedPolicyIndex]->getReportOnlyFlag()
? mozilla::dom::SecurityPolicyViolationEventDisposition::Report
: mozilla::dom::SecurityPolicyViolationEventDisposition::Enforce;
// status-code
uint16_t statusCode = 0;
{
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc) {
nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(doc->GetChannel());
if (channel) {
uint32_t responseStatus = 0;
nsresult rv = channel->GetResponseStatus(&responseStatus);
if (NS_SUCCEEDED(rv) && (responseStatus <= UINT16_MAX)) {
statusCode = static_cast<uint16_t>(responseStatus);
}
}
}
}
aViolationEventInit.mStatusCode = statusCode;
// line-number
aViolationEventInit.mLineNumber = aLineNum;
// column-number
aViolationEventInit.mColumnNumber = aColumnNum;
aViolationEventInit.mBubbles = true;
aViolationEventInit.mComposed = true;
return NS_OK;
}
nsresult nsCSPContext::SendReports(
const mozilla::dom::SecurityPolicyViolationEventInit& aViolationEventInit,
uint32_t aViolatedPolicyIndex) {
EnsureIPCPoliciesRead();
NS_ENSURE_ARG_MAX(aViolatedPolicyIndex, mPolicies.Length() - 1);
dom::CSPReport report;
// blocked-uri
report.mCsp_report.mBlocked_uri = aViolationEventInit.mBlockedURI;
// document-uri
report.mCsp_report.mDocument_uri = aViolationEventInit.mDocumentURI;
// original-policy
report.mCsp_report.mOriginal_policy = aViolationEventInit.mOriginalPolicy;
// referrer
report.mCsp_report.mReferrer = aViolationEventInit.mReferrer;
// effective-directive
report.mCsp_report.mEffective_directive =
aViolationEventInit.mEffectiveDirective;
// violated-directive
report.mCsp_report.mViolated_directive =
aViolationEventInit.mEffectiveDirective;
// disposition
report.mCsp_report.mDisposition = aViolationEventInit.mDisposition;
// status-code
report.mCsp_report.mStatus_code = aViolationEventInit.mStatusCode;
// source-file
if (!aViolationEventInit.mSourceFile.IsEmpty()) {
report.mCsp_report.mSource_file.Construct();
report.mCsp_report.mSource_file.Value() = aViolationEventInit.mSourceFile;
}
// script-sample
if (!aViolationEventInit.mSample.IsEmpty()) {
report.mCsp_report.mScript_sample.Construct();
report.mCsp_report.mScript_sample.Value() = aViolationEventInit.mSample;
}
// line-number
if (aViolationEventInit.mLineNumber != 0) {
report.mCsp_report.mLine_number.Construct();
report.mCsp_report.mLine_number.Value() = aViolationEventInit.mLineNumber;
}
if (aViolationEventInit.mColumnNumber != 0) {
report.mCsp_report.mColumn_number.Construct();
report.mCsp_report.mColumn_number.Value() =
aViolationEventInit.mColumnNumber;
}
nsString csp_report;
if (!report.ToJSON(csp_report)) {
return NS_ERROR_FAILURE;
}
// ---------- Assembled, now send it to all the report URIs ----------- //
nsTArray<nsString> reportURIs;
mPolicies[aViolatedPolicyIndex]->getReportURIs(reportURIs);
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
nsCOMPtr<nsIURI> reportURI;
nsCOMPtr<nsIChannel> reportChannel;
nsresult rv;
for (uint32_t r = 0; r < reportURIs.Length(); r++) {
nsAutoCString reportURICstring = NS_ConvertUTF16toUTF8(reportURIs[r]);
// try to create a new uri from every report-uri string
rv = NS_NewURI(getter_AddRefs(reportURI), reportURIs[r]);
if (NS_FAILED(rv)) {
AutoTArray<nsString, 1> params = {reportURIs[r]};
CSPCONTEXTLOG(("Could not create nsIURI for report URI %s",
reportURICstring.get()));
logToConsole("triedToSendReport", params, aViolationEventInit.mSourceFile,
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber,
nsIScriptError::errorFlag);
continue; // don't return yet, there may be more URIs
}
// try to create a new channel for every report-uri
if (doc) {
rv =
NS_NewChannel(getter_AddRefs(reportChannel), reportURI, doc,
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
nsIContentPolicy::TYPE_CSP_REPORT);
} else {
rv = NS_NewChannel(
getter_AddRefs(reportChannel), reportURI, mLoadingPrincipal,
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
nsIContentPolicy::TYPE_CSP_REPORT);
}
if (NS_FAILED(rv)) {
CSPCONTEXTLOG(("Could not create new channel for report URI %s",
reportURICstring.get()));
continue; // don't return yet, there may be more URIs
}
// log a warning to console if scheme is not http or https
bool isHttpScheme =
reportURI->SchemeIs("http") || reportURI->SchemeIs("https");
if (!isHttpScheme) {
AutoTArray<nsString, 1> params = {reportURIs[r]};
logToConsole(
"reportURInotHttpsOrHttp2", params, aViolationEventInit.mSourceFile,
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber, nsIScriptError::errorFlag);
continue;
}
// make sure this is an anonymous request (no cookies) so in case the
// policy URI is injected, it can't be abused for CSRF.
nsLoadFlags flags;
rv = reportChannel->GetLoadFlags(&flags);
NS_ENSURE_SUCCESS(rv, rv);
flags |= nsIRequest::LOAD_ANONYMOUS;
rv = reportChannel->SetLoadFlags(flags);
NS_ENSURE_SUCCESS(rv, rv);
// we need to set an nsIChannelEventSink on the channel object
// so we can tell it to not follow redirects when posting the reports
RefPtr<CSPReportRedirectSink> reportSink = new CSPReportRedirectSink();
if (doc && doc->GetDocShell()) {
nsCOMPtr<nsINetworkInterceptController> interceptController =
do_QueryInterface(doc->GetDocShell());
reportSink->SetInterceptController(interceptController);
}
reportChannel->SetNotificationCallbacks(reportSink);
// apply the loadgroup taken by setRequestContextWithDocument. If there's
// no loadgroup, AsyncOpen will fail on process-split necko (since the
// channel cannot query the iBrowserChild).
rv = reportChannel->SetLoadGroup(mCallingChannelLoadGroup);
NS_ENSURE_SUCCESS(rv, rv);
// wire in the string input stream to send the report
nsCOMPtr<nsIStringInputStream> sis(
do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID));
NS_ASSERTION(sis,
"nsIStringInputStream is needed but not available to send CSP "
"violation reports");
nsAutoCString utf8CSPReport = NS_ConvertUTF16toUTF8(csp_report);
rv = sis->SetData(utf8CSPReport.get(), utf8CSPReport.Length());
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(reportChannel));
if (!uploadChannel) {
// It's possible the URI provided can't be uploaded to, in which case
// we skip this one. We'll already have warned about a non-HTTP URI
// earlier.
continue;
}
rv = uploadChannel->SetUploadStream(sis, "application/csp-report"_ns, -1);
NS_ENSURE_SUCCESS(rv, rv);
// if this is an HTTP channel, set the request method to post
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(reportChannel));
if (httpChannel) {
rv = httpChannel->SetRequestMethod("POST"_ns);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
RefPtr<CSPViolationReportListener> listener =
new CSPViolationReportListener();
rv = reportChannel->AsyncOpen(listener);
// AsyncOpen should not fail, but could if there's no load group (like if
// SetRequestContextWith{Document,Principal} is not given a channel). This
// should fail quietly and not return an error since it's really ok if
// reports don't go out, but it's good to log the error locally.
if (NS_FAILED(rv)) {
AutoTArray<nsString, 1> params = {reportURIs[r]};
CSPCONTEXTLOG(("AsyncOpen failed for report URI %s",
NS_ConvertUTF16toUTF8(params[0]).get()));
logToConsole("triedToSendReport", params, aViolationEventInit.mSourceFile,
aViolationEventInit.mSample, aViolationEventInit.mLineNumber,
aViolationEventInit.mColumnNumber,
nsIScriptError::errorFlag);
} else {
CSPCONTEXTLOG(
("Sent violation report to URI %s", reportURICstring.get()));
}
}
return NS_OK;
}
nsresult nsCSPContext::FireViolationEvent(
Element* aTriggeringElement, nsICSPEventListener* aCSPEventListener,
const mozilla::dom::SecurityPolicyViolationEventInit& aViolationEventInit) {
if (aCSPEventListener) {
nsAutoString json;
if (aViolationEventInit.ToJSON(json)) {
aCSPEventListener->OnCSPViolationEvent(json);
}
}
// 1. If target is not null, and global is a Window, and target’s
// shadow-including root is not global’s associated Document, set target to
// null.
RefPtr<EventTarget> eventTarget = aTriggeringElement;
nsCOMPtr<Document> doc = do_QueryReferent(mLoadingContext);
if (doc && aTriggeringElement &&
aTriggeringElement->GetComposedDoc() != doc) {
eventTarget = nullptr;
}
if (!eventTarget) {
// If target is a Window, set target to target’s associated Document.
eventTarget = doc;
}
if (!eventTarget && mInnerWindowID && XRE_IsParentProcess()) {
if (RefPtr<WindowGlobalParent> parent =
WindowGlobalParent::GetByInnerWindowId(mInnerWindowID)) {
nsAutoString json;
if (aViolationEventInit.ToJSON(json)) {
Unused << parent->SendDispatchSecurityPolicyViolation(json);
}
}
return NS_OK;
}
if (!eventTarget) {
// If we are here, we are probably dealing with workers. Those are handled
// via nsICSPEventListener. Nothing to do here.
return NS_OK;
}
RefPtr<mozilla::dom::Event> event =
mozilla::dom::SecurityPolicyViolationEvent::Constructor(
eventTarget, u"securitypolicyviolation"_ns, aViolationEventInit);
event->SetTrusted(true);
ErrorResult rv;
eventTarget->DispatchEvent(*event, rv);
return rv.StealNSResult();
}
/**
* Dispatched from the main thread to send reports for one CSP violation.
*/
class CSPReportSenderRunnable final : public Runnable {
public:
CSPReportSenderRunnable(
Element* aTriggeringElement, nsICSPEventListener* aCSPEventListener,
nsIURI* aBlockedURI,
nsCSPContext::BlockedContentSource aBlockedContentSource,
nsIURI* aOriginalURI, uint32_t aViolatedPolicyIndex, bool aReportOnlyFlag,
const nsAString& aViolatedDirective, const nsAString& aEffectiveDirective,
const nsAString& aObserverSubject, const nsAString& aSourceFile,
bool aReportSample, const nsAString& aScriptSample, uint32_t aLineNum,
uint32_t aColumnNum, nsCSPContext* aCSPContext)
: mozilla::Runnable("CSPReportSenderRunnable"),
mTriggeringElement(aTriggeringElement),
mCSPEventListener(aCSPEventListener),
mBlockedURI(aBlockedURI),
mBlockedContentSource(aBlockedContentSource),
mOriginalURI(aOriginalURI),
mViolatedPolicyIndex(aViolatedPolicyIndex),
mReportOnlyFlag(aReportOnlyFlag),
mReportSample(aReportSample),
mViolatedDirective(aViolatedDirective),
mEffectiveDirective(aEffectiveDirective),
mSourceFile(aSourceFile),
mScriptSample(aScriptSample),
mLineNum(aLineNum),
mColumnNum(aColumnNum),
mCSPContext(aCSPContext) {
NS_ASSERTION(!aViolatedDirective.IsEmpty(),
"Can not send reports without a violated directive");
// the observer subject is an nsISupports: either an nsISupportsCString
// from the arg passed in directly, or if that's empty, it's the blocked
// source.
if (aObserverSubject.IsEmpty() && mBlockedURI) {
mObserverSubject = aBlockedURI;
return;
}
nsAutoCString subject;
if (aObserverSubject.IsEmpty()) {
BlockedContentSourceToString(aBlockedContentSource, subject);
} else {
CopyUTF16toUTF8(aObserverSubject, subject);
}
nsCOMPtr<nsISupportsCString> supportscstr =
do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID);
if (supportscstr) {
supportscstr->SetData(subject);
mObserverSubject = do_QueryInterface(supportscstr);
}
// Truncate sample string.
uint32_t length = mScriptSample.Length();
if (length > nsCSPContext::ScriptSampleMaxLength()) {
uint32_t desiredLength = nsCSPContext::ScriptSampleMaxLength();
// Don't cut off right before a low surrogate. Just include it.
if (NS_IS_LOW_SURROGATE(mScriptSample[desiredLength])) {
desiredLength++;
}
mScriptSample.Replace(nsCSPContext::ScriptSampleMaxLength(),
length - desiredLength,
nsContentUtils::GetLocalizedEllipsis());
}
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
nsresult rv;
// 0) prepare violation data
mozilla::dom::SecurityPolicyViolationEventInit init;
nsAutoCString blockedContentSource;
BlockedContentSourceToString(mBlockedContentSource, blockedContentSource);
rv = mCSPContext->GatherSecurityPolicyViolationEventData(
mBlockedURI, blockedContentSource, mOriginalURI, mEffectiveDirective,
mViolatedPolicyIndex, mSourceFile,
mReportSample ? mScriptSample : EmptyString(), mLineNum, mColumnNum,
init);
NS_ENSURE_SUCCESS(rv, rv);
// 1) notify observers
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (mObserverSubject && observerService) {
rv = observerService->NotifyObservers(
mObserverSubject, CSP_VIOLATION_TOPIC, mViolatedDirective.get());
NS_ENSURE_SUCCESS(rv, rv);
}
// 2) send reports for the policy that was violated
mCSPContext->SendReports(init, mViolatedPolicyIndex);
// 3) log to console (one per policy violation)
if (mBlockedURI) {
mBlockedURI->GetSpec(blockedContentSource);
if (blockedContentSource.Length() >
nsCSPContext::ScriptSampleMaxLength()) {
bool isData = mBlockedURI->SchemeIs("data");
if (NS_SUCCEEDED(rv) && isData &&
blockedContentSource.Length() >
nsCSPContext::ScriptSampleMaxLength()) {
blockedContentSource.Truncate(nsCSPContext::ScriptSampleMaxLength());
blockedContentSource.Append(
NS_ConvertUTF16toUTF8(nsContentUtils::GetLocalizedEllipsis()));
}
}
}
if (blockedContentSource.Length() > 0) {
nsString blockedContentSource16 =
NS_ConvertUTF8toUTF16(blockedContentSource);
AutoTArray<nsString, 2> params = {mViolatedDirective,
blockedContentSource16};
mCSPContext->logToConsole(
mReportOnlyFlag ? "CSPROViolationWithURI" : "CSPViolationWithURI",
params, mSourceFile, mScriptSample, mLineNum, mColumnNum,
nsIScriptError::errorFlag);
}
// 4) fire violation event
// A frame-ancestors violation has occurred, but we should not dispatch
// the violation event to a potentially cross-origin ancestor.
if (!mViolatedDirective.EqualsLiteral("frame-ancestors")) {
mCSPContext->FireViolationEvent(mTriggeringElement, mCSPEventListener,
init);
}
return NS_OK;
}
private:
RefPtr<Element> mTriggeringElement;
nsCOMPtr<nsICSPEventListener> mCSPEventListener;
nsCOMPtr<nsIURI> mBlockedURI;
nsCSPContext::BlockedContentSource mBlockedContentSource;
nsCOMPtr<nsIURI> mOriginalURI;
uint32_t mViolatedPolicyIndex;
bool mReportOnlyFlag;
bool mReportSample;
nsString mViolatedDirective;
nsString mEffectiveDirective;
nsCOMPtr<nsISupports> mObserverSubject;
nsString mSourceFile;
nsString mScriptSample;
uint32_t mLineNum;
uint32_t mColumnNum;
RefPtr<nsCSPContext> mCSPContext;
};
/**
* Asynchronously notifies any nsIObservers listening to the CSP violation
* topic that a violation occurred. Also triggers report sending and console
* logging. All asynchronous on the main thread.
*
* @param aTriggeringElement
* The element that triggered this report violation. It can be null.
* @param aBlockedContentSource
* Either a CSP Source (like 'self', as string) or nsIURI: the source
* of the violation.
* @param aOriginalUri
* The original URI if the blocked content is a redirect, else null
* @param aViolatedDirective
* the directive that was violated (string).
* @param aViolatedPolicyIndex
* the index of the policy that was violated (so we know where to send
* the reports).
* @param aObserverSubject
* optional, subject sent to the nsIObservers listening to the CSP
* violation topic.
* @param aSourceFile
* name of the file containing the inline script violation
* @param aScriptSample
* a sample of the violating inline script
* @param aLineNum
* source line number of the violation (if available)
* @param aColumnNum
* source column number of the violation (if available)
*/
nsresult nsCSPContext::AsyncReportViolation(
Element* aTriggeringElement, nsICSPEventListener* aCSPEventListener,
nsIURI* aBlockedURI, BlockedContentSource aBlockedContentSource,
nsIURI* aOriginalURI, const nsAString& aViolatedDirective,
const nsAString& aEffectiveDirective, uint32_t aViolatedPolicyIndex,
const nsAString& aObserverSubject, const nsAString& aSourceFile,
bool aReportSample, const nsAString& aScriptSample, uint32_t aLineNum,
uint32_t aColumnNum) {
EnsureIPCPoliciesRead();
NS_ENSURE_ARG_MAX(aViolatedPolicyIndex, mPolicies.Length() - 1);
nsCOMPtr<nsIRunnable> task = new CSPReportSenderRunnable(
aTriggeringElement, aCSPEventListener, aBlockedURI, aBlockedContentSource,
aOriginalURI, aViolatedPolicyIndex,
mPolicies[aViolatedPolicyIndex]->getReportOnlyFlag(), aViolatedDirective,
aEffectiveDirective, aObserverSubject, aSourceFile, aReportSample,
aScriptSample, aLineNum, aColumnNum, this);
if (XRE_IsContentProcess()) {
if (mEventTarget) {
mEventTarget->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
return NS_OK;
}
}
NS_DispatchToMainThread(task.forget());
return NS_OK;
}
/**
* Based on the given loadinfo, determines if this CSP context allows the
* ancestry.
*
* In order to determine the URI of the parent document (one causing the load
* of this protected document), this function traverses all Browsing Contexts
* until it reaches the top level browsing context.
*/
NS_IMETHODIMP
nsCSPContext::PermitsAncestry(nsILoadInfo* aLoadInfo,
bool* outPermitsAncestry) {
nsresult rv;
*outPermitsAncestry = true;
RefPtr<mozilla::dom::BrowsingContext> ctx;
aLoadInfo->GetBrowsingContext(getter_AddRefs(ctx));
// extract the ancestry as an array
nsCOMArray<nsIURI> ancestorsArray;
nsCOMPtr<nsIURI> uriClone;
while (ctx) {
nsCOMPtr<nsIPrincipal> currentPrincipal;
// Generally permitsAncestry is consulted from within the
// DocumentLoadListener in the parent process. For loads of type object
// and embed it's called from the Document in the content process.
// After Bug 1646899 we should be able to remove that branching code for
// querying the currentURI.
if (XRE_IsParentProcess()) {
WindowGlobalParent* window = ctx->Canonical()->GetCurrentWindowGlobal();
if (window) {
// Using the URI of the Principal and not the document because e.g.
// about:blank inherits the principal and hence the URI of the
// document does not reflect the security context of the document.
currentPrincipal = window->DocumentPrincipal();
}
} else if (nsPIDOMWindowOuter* windowOuter = ctx->GetDOMWindow()) {
currentPrincipal = nsGlobalWindowOuter::Cast(windowOuter)->GetPrincipal();
}
if (currentPrincipal) {
nsCOMPtr<nsIURI> currentURI;
auto* currentBasePrincipal = BasePrincipal::Cast(currentPrincipal);
currentBasePrincipal->GetURI(getter_AddRefs(currentURI));
if (currentURI) {
nsAutoCString spec;
currentURI->GetSpec(spec);
// delete the userpass from the URI.
rv = NS_MutateURI(currentURI)
.SetRef(""_ns)
.SetUserPass(""_ns)
.Finalize(uriClone);
// If setUserPass fails for some reason, just return a clone of the
// current URI
if (NS_FAILED(rv)) {
rv = NS_GetURIWithoutRef(currentURI, getter_AddRefs(uriClone));
NS_ENSURE_SUCCESS(rv, rv);
}
ancestorsArray.AppendElement(uriClone);
}
}
ctx = ctx->GetParent();
}
nsAutoString violatedDirective;
// Now that we've got the ancestry chain in ancestorsArray, time to check
// them against any CSP.
// NOTE: the ancestors are not allowed to be sent cross origin; this is a
// restriction not placed on subresource loads.
for (uint32_t a = 0; a < ancestorsArray.Length(); a++) {
if (CSPCONTEXTLOGENABLED()) {
CSPCONTEXTLOG(("nsCSPContext::PermitsAncestry, checking ancestor: %s",
ancestorsArray[a]->GetSpecOrDefault().get()));
}
// omit the ancestor URI in violation reports if cross-origin as per spec
// (it is a violation of the same-origin policy).
bool okToSendAncestor =
NS_SecurityCompareURIs(ancestorsArray[a], mSelfURI, true);
bool permits =
permitsInternal(nsIContentSecurityPolicy::FRAME_ANCESTORS_DIRECTIVE,
nullptr, // triggering element
nullptr, // nsICSPEventListener
ancestorsArray[a],
nullptr, // no redirect here.
u""_ns, // no nonce
true, // specific, do not use default-src
true, // send violation reports
okToSendAncestor,
false); // not parser created
if (!permits) {
*outPermitsAncestry = false;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::Permits(Element* aTriggeringElement,
nsICSPEventListener* aCSPEventListener, nsIURI* aURI,
CSPDirective aDir, bool aSpecific,
bool aSendViolationReports, bool* outPermits) {
// Can't perform check without aURI
if (aURI == nullptr) {
return NS_ERROR_FAILURE;
}
if (aURI->SchemeIs("resource")) {
// XXX Ideally we would call SubjectToCSP() here but that would also
// allowlist e.g. javascript: URIs which should not be allowlisted here.
// As a hotfix we just allowlist pdf.js internals here explicitly.
nsAutoCString uriSpec;
aURI->GetSpec(uriSpec);
if (StringBeginsWith(uriSpec, "resource://pdf.js/"_ns)) {
*outPermits = true;
return NS_OK;
}
}
*outPermits =
permitsInternal(aDir, aTriggeringElement, aCSPEventListener, aURI,
nullptr, // no original (pre-redirect) URI
u""_ns, // no nonce
aSpecific, aSendViolationReports,
true, // send blocked URI in violation reports
false); // not parser created
if (CSPCONTEXTLOGENABLED()) {
CSPCONTEXTLOG(("nsCSPContext::Permits, aUri: %s, aDir: %s, isAllowed: %s",
aURI->GetSpecOrDefault().get(),
CSP_CSPDirectiveToString(aDir),
*outPermits ? "allow" : "deny"));
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::ToJSON(nsAString& outCSPinJSON) {
outCSPinJSON.Truncate();
dom::CSPPolicies jsonPolicies;
jsonPolicies.mCsp_policies.Construct();
EnsureIPCPoliciesRead();
for (uint32_t p = 0; p < mPolicies.Length(); p++) {
dom::CSP jsonCSP;
mPolicies[p]->toDomCSPStruct(jsonCSP);
if (!jsonPolicies.mCsp_policies.Value().AppendElement(jsonCSP, fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
// convert the gathered information to JSON
if (!jsonPolicies.ToJSON(outCSPinJSON)) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::GetCSPSandboxFlags(uint32_t* aOutSandboxFlags) {
if (!aOutSandboxFlags) {
return NS_ERROR_FAILURE;
}
*aOutSandboxFlags = SANDBOXED_NONE;
EnsureIPCPoliciesRead();
for (uint32_t i = 0; i < mPolicies.Length(); i++) {
uint32_t flags = mPolicies[i]->getSandboxFlags();
// current policy doesn't have sandbox flag, check next policy
if (!flags) {
continue;
}
// current policy has sandbox flags, if the policy is in enforcement-mode
// (i.e. not report-only) set these flags and check for policies with more
// restrictions
if (!mPolicies[i]->getReportOnlyFlag()) {
*aOutSandboxFlags |= flags;
} else {
// sandbox directive is ignored in report-only mode, warn about it and
// continue the loop checking for an enforcement policy.
nsAutoString policy;
mPolicies[i]->toString(policy);
CSPCONTEXTLOG(
("nsCSPContext::GetCSPSandboxFlags, report only policy, ignoring "
"sandbox in: %s",
NS_ConvertUTF16toUTF8(policy).get()));
AutoTArray<nsString, 1> params = {policy};
logToConsole("ignoringReportOnlyDirective", params, u""_ns, u""_ns, 0, 0,
nsIScriptError::warningFlag);
}
}
return NS_OK;
}
/* ========== CSPViolationReportListener implementation ========== */
NS_IMPL_ISUPPORTS(CSPViolationReportListener, nsIStreamListener,
nsIRequestObserver, nsISupports);
CSPViolationReportListener::CSPViolationReportListener() = default;
CSPViolationReportListener::~CSPViolationReportListener() = default;
nsresult AppendSegmentToString(nsIInputStream* aInputStream, void* aClosure,
const char* aRawSegment, uint32_t aToOffset,
uint32_t aCount, uint32_t* outWrittenCount) {
nsCString* decodedData = static_cast<nsCString*>(aClosure);
decodedData->Append(aRawSegment, aCount);
*outWrittenCount = aCount;
return NS_OK;
}
NS_IMETHODIMP
CSPViolationReportListener::OnDataAvailable(nsIRequest* aRequest,
nsIInputStream* aInputStream,
uint64_t aOffset, uint32_t aCount) {
uint32_t read;
nsCString decodedData;
return aInputStream->ReadSegments(AppendSegmentToString, &decodedData, aCount,
&read);
}
NS_IMETHODIMP
CSPViolationReportListener::OnStopRequest(nsIRequest* aRequest,
nsresult aStatus) {
return NS_OK;
}
NS_IMETHODIMP
CSPViolationReportListener::OnStartRequest(nsIRequest* aRequest) {
return NS_OK;
}
/* ========== CSPReportRedirectSink implementation ========== */
NS_IMPL_ISUPPORTS(CSPReportRedirectSink, nsIChannelEventSink,
nsIInterfaceRequestor);
CSPReportRedirectSink::CSPReportRedirectSink() = default;
CSPReportRedirectSink::~CSPReportRedirectSink() = default;
NS_IMETHODIMP
CSPReportRedirectSink::AsyncOnChannelRedirect(
nsIChannel* aOldChannel, nsIChannel* aNewChannel, uint32_t aRedirFlags,
nsIAsyncVerifyRedirectCallback* aCallback) {
if (aRedirFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
aCallback->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
// cancel the old channel so XHR failure callback happens
nsresult rv = aOldChannel->Cancel(NS_ERROR_ABORT);
NS_ENSURE_SUCCESS(rv, rv);
// notify an observer that we have blocked the report POST due to a
// redirect, used in testing, do this async since we're in an async call now
// to begin with
nsCOMPtr<nsIURI> uri;
rv = aOldChannel->GetURI(getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
NS_ASSERTION(observerService,
"Observer service required to log CSP violations");
observerService->NotifyObservers(
uri, CSP_VIOLATION_TOPIC,
u"denied redirect while sending violation report");
return NS_BINDING_REDIRECTED;
}
NS_IMETHODIMP
CSPReportRedirectSink::GetInterface(const nsIID& aIID, void** aResult) {
if (aIID.Equals(NS_GET_IID(nsINetworkInterceptController)) &&
mInterceptController) {
nsCOMPtr<nsINetworkInterceptController> copy(mInterceptController);
*aResult = copy.forget().take();
return NS_OK;
}
return QueryInterface(aIID, aResult);
}
void CSPReportRedirectSink::SetInterceptController(
nsINetworkInterceptController* aInterceptController) {
mInterceptController = aInterceptController;
}
/* ===== nsISerializable implementation ====== */
NS_IMETHODIMP
nsCSPContext::Read(nsIObjectInputStream* aStream) {
nsresult rv;
nsCOMPtr<nsISupports> supports;
rv = NS_ReadOptionalObject(aStream, true, getter_AddRefs(supports));
NS_ENSURE_SUCCESS(rv, rv);
mSelfURI = do_QueryInterface(supports);
MOZ_ASSERT(mSelfURI, "need a self URI to de-serialize");
nsAutoCString JSON;
rv = aStream->ReadCString(JSON);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIPrincipal> principal = BasePrincipal::FromJSON(JSON);
mLoadingPrincipal = principal;
MOZ_ASSERT(mLoadingPrincipal, "need a loadingPrincipal to de-serialize");
uint32_t numPolicies;
rv = aStream->Read32(&numPolicies);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString policyString;
while (numPolicies > 0) {
numPolicies--;
rv = aStream->ReadString(policyString);
NS_ENSURE_SUCCESS(rv, rv);
bool reportOnly = false;
rv = aStream->ReadBoolean(&reportOnly);
NS_ENSURE_SUCCESS(rv, rv);
bool deliveredViaMetaTag = false;
rv = aStream->ReadBoolean(&deliveredViaMetaTag);
NS_ENSURE_SUCCESS(rv, rv);
AddIPCPolicy(mozilla::ipc::ContentSecurityPolicy(policyString, reportOnly,
deliveredViaMetaTag));
}
return NS_OK;
}
NS_IMETHODIMP
nsCSPContext::Write(nsIObjectOutputStream* aStream) {
nsresult rv = NS_WriteOptionalCompoundObject(aStream, mSelfURI,
NS_GET_IID(nsIURI), true);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString JSON;
BasePrincipal::Cast(mLoadingPrincipal)->ToJSON(JSON);
rv = aStream->WriteStringZ(JSON.get());
NS_ENSURE_SUCCESS(rv, rv);
// Serialize all the policies.
aStream->Write32(mPolicies.Length() + mIPCPolicies.Length());
nsAutoString polStr;
for (uint32_t p = 0; p < mPolicies.Length(); p++) {
polStr.Truncate();
mPolicies[p]->toString(polStr);
aStream->WriteWStringZ(polStr.get());
aStream->WriteBoolean(mPolicies[p]->getReportOnlyFlag());
aStream->WriteBoolean(mPolicies[p]->getDeliveredViaMetaTagFlag());
}
for (auto& policy : mIPCPolicies) {
aStream->WriteWStringZ(policy.policy().get());
aStream->WriteBoolean(policy.reportOnlyFlag());
aStream->WriteBoolean(policy.deliveredViaMetaTagFlag());
}
return NS_OK;
}
void nsCSPContext::AddIPCPolicy(const ContentSecurityPolicy& aPolicy) {
mIPCPolicies.AppendElement(aPolicy);
}
void nsCSPContext::SerializePolicies(
nsTArray<ContentSecurityPolicy>& aPolicies) {
for (auto* policy : mPolicies) {
nsAutoString policyString;
policy->toString(policyString);
aPolicies.AppendElement(
ContentSecurityPolicy(policyString, policy->getReportOnlyFlag(),
policy->getDeliveredViaMetaTagFlag()));
}
aPolicies.AppendElements(mIPCPolicies);
}
|