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
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
|
/* -*- 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 "ContentAnalysis.h"
#include "ContentAnalysisIPCTypes.h"
#include "content_analysis/sdk/analysis_client.h"
#include "base/process_util.h"
#include "GMPUtils.h" // ToHexString
#include "mozilla/Components.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/Logging.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Services.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/StaticMutex.h"
#include "mozilla/StaticPrefs_browser.h"
#include "nsAppRunner.h"
#include "nsBaseClipboard.h"
#include "nsComponentManagerUtils.h"
#include "nsIClassInfoImpl.h"
#include "nsIFile.h"
#include "nsIGlobalObject.h"
#include "nsIObserverService.h"
#include "nsIOutputStream.h"
#include "nsIPrintSettings.h"
#include "nsIStorageStream.h"
#include "nsISupportsPrimitives.h"
#include "nsITransferable.h"
#include "ScopedNSSTypes.h"
#include "xpcpublic.h"
#include <algorithm>
#include <sstream>
#include <string>
#ifdef XP_WIN
# include <windows.h>
# define SECURITY_WIN32 1
# include <security.h>
# include "mozilla/NativeNt.h"
# include "mozilla/WinDllServices.h"
#endif // XP_WIN
namespace mozilla::contentanalysis {
LazyLogModule gContentAnalysisLog("contentanalysis");
#define LOGD(...) \
MOZ_LOG(mozilla::contentanalysis::gContentAnalysisLog, \
mozilla::LogLevel::Debug, (__VA_ARGS__))
#define LOGE(...) \
MOZ_LOG(mozilla::contentanalysis::gContentAnalysisLog, \
mozilla::LogLevel::Error, (__VA_ARGS__))
} // namespace mozilla::contentanalysis
namespace {
const char* kIsDLPEnabledPref = "browser.contentanalysis.enabled";
const char* kIsPerUserPref = "browser.contentanalysis.is_per_user";
const char* kPipePathNamePref = "browser.contentanalysis.pipe_path_name";
const char* kClientSignature = "browser.contentanalysis.client_signature";
const char* kAllowUrlPref = "browser.contentanalysis.allow_url_regex_list";
const char* kDenyUrlPref = "browser.contentanalysis.deny_url_regex_list";
nsresult MakePromise(JSContext* aCx, RefPtr<mozilla::dom::Promise>* aPromise) {
nsIGlobalObject* go = xpc::CurrentNativeGlobal(aCx);
if (NS_WARN_IF(!go)) {
return NS_ERROR_UNEXPECTED;
}
mozilla::ErrorResult result;
*aPromise = mozilla::dom::Promise::Create(go, result);
if (NS_WARN_IF(result.Failed())) {
return result.StealNSResult();
}
return NS_OK;
}
nsCString GenerateRequestToken() {
nsID id = nsID::GenerateUUID();
return nsCString(id.ToString().get());
}
static nsresult GetFileDisplayName(const nsString& aFilePath,
nsString& aFileDisplayName) {
nsresult rv;
nsCOMPtr<nsIFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = file->InitWithPath(aFilePath);
NS_ENSURE_SUCCESS(rv, rv);
return file->GetDisplayName(aFileDisplayName);
}
nsIContentAnalysisAcknowledgement::FinalAction ConvertResult(
nsIContentAnalysisResponse::Action aResponseResult) {
switch (aResponseResult) {
case nsIContentAnalysisResponse::Action::eReportOnly:
return nsIContentAnalysisAcknowledgement::FinalAction::eReportOnly;
case nsIContentAnalysisResponse::Action::eWarn:
return nsIContentAnalysisAcknowledgement::FinalAction::eWarn;
case nsIContentAnalysisResponse::Action::eBlock:
return nsIContentAnalysisAcknowledgement::FinalAction::eBlock;
case nsIContentAnalysisResponse::Action::eAllow:
return nsIContentAnalysisAcknowledgement::FinalAction::eAllow;
case nsIContentAnalysisResponse::Action::eUnspecified:
return nsIContentAnalysisAcknowledgement::FinalAction::eUnspecified;
default:
LOGE(
"ConvertResult got unexpected responseResult "
"%d",
static_cast<uint32_t>(aResponseResult));
return nsIContentAnalysisAcknowledgement::FinalAction::eUnspecified;
}
}
} // anonymous namespace
namespace mozilla::contentanalysis {
ContentAnalysisRequest::~ContentAnalysisRequest() {
#ifdef XP_WIN
CloseHandle(mPrintDataHandle);
#endif
}
NS_IMETHODIMP
ContentAnalysisRequest::GetAnalysisType(AnalysisType* aAnalysisType) {
*aAnalysisType = mAnalysisType;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetTextContent(nsAString& aTextContent) {
aTextContent = mTextContent;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetFilePath(nsAString& aFilePath) {
aFilePath = mFilePath;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetPrintDataHandle(uint64_t* aPrintDataHandle) {
#ifdef XP_WIN
uintptr_t printDataHandle = reinterpret_cast<uintptr_t>(mPrintDataHandle);
uint64_t printDataValue = static_cast<uint64_t>(printDataHandle);
*aPrintDataHandle = printDataValue;
return NS_OK;
#else
return NS_ERROR_NOT_IMPLEMENTED;
#endif
}
NS_IMETHODIMP
ContentAnalysisRequest::GetPrinterName(nsAString& aPrinterName) {
aPrinterName = mPrinterName;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetPrintDataSize(uint64_t* aPrintDataSize) {
#ifdef XP_WIN
*aPrintDataSize = mPrintDataSize;
return NS_OK;
#else
return NS_ERROR_NOT_IMPLEMENTED;
#endif
}
NS_IMETHODIMP
ContentAnalysisRequest::GetUrl(nsIURI** aUrl) {
NS_ENSURE_ARG_POINTER(aUrl);
NS_IF_ADDREF(*aUrl = mUrl);
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetEmail(nsAString& aEmail) {
aEmail = mEmail;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetSha256Digest(nsACString& aSha256Digest) {
aSha256Digest = mSha256Digest;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetResources(
nsTArray<RefPtr<nsIClientDownloadResource>>& aResources) {
aResources = mResources.Clone();
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetRequestToken(nsACString& aRequestToken) {
aRequestToken = mRequestToken;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetOperationTypeForDisplay(
OperationType* aOperationType) {
*aOperationType = mOperationTypeForDisplay;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetOperationDisplayString(
nsAString& aOperationDisplayString) {
aOperationDisplayString = mOperationDisplayString;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisRequest::GetWindowGlobalParent(
dom::WindowGlobalParent** aWindowGlobalParent) {
NS_IF_ADDREF(*aWindowGlobalParent = mWindowGlobalParent);
return NS_OK;
}
nsresult ContentAnalysis::CreateContentAnalysisClient(
nsCString&& aPipePathName, nsString&& aClientSignatureSetting,
bool aIsPerUser) {
MOZ_ASSERT(!NS_IsMainThread());
// This method should only be called once
MOZ_ASSERT(!mCaClientPromise->IsResolved());
std::shared_ptr<content_analysis::sdk::Client> client(
content_analysis::sdk::Client::Create({aPipePathName.Data(), aIsPerUser})
.release());
LOGD("Content analysis is %s", client ? "connected" : "not available");
#ifdef XP_WIN
if (client && !aClientSignatureSetting.IsEmpty()) {
std::string agentPath = client->GetAgentInfo().binary_path;
nsString agentWidePath = NS_ConvertUTF8toUTF16(agentPath);
UniquePtr<wchar_t[]> orgName =
mozilla::DllServices::Get()->GetBinaryOrgName(agentWidePath.Data());
bool signatureMatches = false;
if (orgName) {
auto dependentOrgName = nsDependentString(orgName.get());
LOGD("Content analysis client signed with organization name \"%S\"",
static_cast<const wchar_t*>(dependentOrgName.get()));
signatureMatches = aClientSignatureSetting.Equals(dependentOrgName);
} else {
LOGD("Content analysis client has no signature");
}
if (!signatureMatches) {
LOGE(
"Got mismatched content analysis client signature! All content "
"analysis operations will fail.");
mCaClientPromise->Reject(NS_ERROR_INVALID_SIGNATURE, __func__);
return NS_OK;
}
}
#endif // XP_WIN
mCaClientPromise->Resolve(client, __func__);
return NS_OK;
}
ContentAnalysisRequest::ContentAnalysisRequest(
AnalysisType aAnalysisType, nsString aString, bool aStringIsFilePath,
nsCString aSha256Digest, nsCOMPtr<nsIURI> aUrl,
OperationType aOperationType, dom::WindowGlobalParent* aWindowGlobalParent)
: mAnalysisType(aAnalysisType),
mUrl(std::move(aUrl)),
mSha256Digest(std::move(aSha256Digest)),
mWindowGlobalParent(aWindowGlobalParent) {
MOZ_ASSERT(aAnalysisType != AnalysisType::ePrint,
"Print should use other ContentAnalysisRequest constructor!");
if (aStringIsFilePath) {
mFilePath = std::move(aString);
} else {
mTextContent = std::move(aString);
}
mOperationTypeForDisplay = aOperationType;
if (mOperationTypeForDisplay == OperationType::eCustomDisplayString) {
MOZ_ASSERT(aStringIsFilePath);
nsresult rv = GetFileDisplayName(mFilePath, mOperationDisplayString);
if (NS_FAILED(rv)) {
mOperationDisplayString = u"file";
}
}
mRequestToken = GenerateRequestToken();
}
ContentAnalysisRequest::ContentAnalysisRequest(
const nsTArray<uint8_t> aPrintData, nsCOMPtr<nsIURI> aUrl,
nsString aPrinterName, dom::WindowGlobalParent* aWindowGlobalParent)
: mAnalysisType(AnalysisType::ePrint),
mUrl(std::move(aUrl)),
mPrinterName(std::move(aPrinterName)),
mWindowGlobalParent(aWindowGlobalParent) {
#ifdef XP_WIN
LARGE_INTEGER dataContentLength;
dataContentLength.QuadPart = static_cast<LONGLONG>(aPrintData.Length());
mPrintDataHandle = ::CreateFileMappingW(
INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, dataContentLength.HighPart,
dataContentLength.LowPart, nullptr);
if (mPrintDataHandle) {
mozilla::nt::AutoMappedView view(mPrintDataHandle, FILE_MAP_ALL_ACCESS);
memcpy(view.as<uint8_t>(), aPrintData.Elements(), aPrintData.Length());
mPrintDataSize = aPrintData.Length();
}
#else
MOZ_ASSERT_UNREACHABLE(
"Content Analysis is not supported on non-Windows platforms");
#endif
mOperationTypeForDisplay = OperationType::eOperationPrint;
mRequestToken = GenerateRequestToken();
}
nsresult ContentAnalysisRequest::GetFileDigest(const nsAString& aFilePath,
nsCString& aDigestString) {
MOZ_DIAGNOSTIC_ASSERT(
!NS_IsMainThread(),
"ContentAnalysisRequest::GetFileDigest does file IO and should "
"not run on the main thread");
nsresult rv;
mozilla::Digest digest;
digest.Begin(SEC_OID_SHA256);
PRFileDesc* fd = nullptr;
nsCOMPtr<nsIFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = file->InitWithPath(aFilePath);
NS_ENSURE_SUCCESS(rv, rv);
rv = file->OpenNSPRFileDesc(PR_RDONLY | nsIFile::OS_READAHEAD, 0, &fd);
NS_ENSURE_SUCCESS(rv, rv);
auto closeFile = MakeScopeExit([fd]() { PR_Close(fd); });
constexpr uint32_t kBufferSize = 1024 * 1024;
auto buffer = mozilla::MakeUnique<uint8_t[]>(kBufferSize);
if (!buffer) {
return NS_ERROR_OUT_OF_MEMORY;
}
PRInt32 bytesRead = PR_Read(fd, buffer.get(), kBufferSize);
while (bytesRead != 0) {
if (bytesRead == -1) {
return NS_ErrorAccordingToNSPR();
}
digest.Update(mozilla::Span<const uint8_t>(buffer.get(), bytesRead));
bytesRead = PR_Read(fd, buffer.get(), kBufferSize);
}
nsTArray<uint8_t> digestResults;
rv = digest.End(digestResults);
NS_ENSURE_SUCCESS(rv, rv);
aDigestString = mozilla::ToHexString(digestResults);
return NS_OK;
}
// Generate an ID that will be shared by all DLP requests.
// Used to cancel all requests on Firefox shutdown.
void ContentAnalysis::GenerateUserActionId() {
nsID id = nsID::GenerateUUID();
mUserActionId = nsPrintfCString("Firefox %s", id.ToString().get());
}
nsCString ContentAnalysis::GetUserActionId() { return mUserActionId; }
static nsresult ConvertToProtobuf(
nsIClientDownloadResource* aIn,
content_analysis::sdk::ClientDownloadRequest_Resource* aOut) {
nsString url;
nsresult rv = aIn->GetUrl(url);
NS_ENSURE_SUCCESS(rv, rv);
aOut->set_url(NS_ConvertUTF16toUTF8(url).get());
uint32_t resourceType;
rv = aIn->GetType(&resourceType);
NS_ENSURE_SUCCESS(rv, rv);
aOut->set_type(
static_cast<content_analysis::sdk::ClientDownloadRequest_ResourceType>(
resourceType));
return NS_OK;
}
static nsresult ConvertToProtobuf(
nsIContentAnalysisRequest* aIn, nsCString&& aUserActionId,
int64_t aRequestCount,
content_analysis::sdk::ContentAnalysisRequest* aOut) {
uint32_t timeout = StaticPrefs::browser_contentanalysis_agent_timeout();
aOut->set_expires_at(time(nullptr) + timeout);
nsIContentAnalysisRequest::AnalysisType analysisType;
nsresult rv = aIn->GetAnalysisType(&analysisType);
NS_ENSURE_SUCCESS(rv, rv);
auto connector =
static_cast<content_analysis::sdk::AnalysisConnector>(analysisType);
aOut->set_analysis_connector(connector);
nsCString requestToken;
rv = aIn->GetRequestToken(requestToken);
NS_ENSURE_SUCCESS(rv, rv);
aOut->set_request_token(requestToken.get(), requestToken.Length());
aOut->set_user_action_id(aUserActionId.get());
aOut->set_user_action_requests_count(aRequestCount);
const std::string tag = "dlp"; // TODO:
*aOut->add_tags() = tag;
auto* requestData = aOut->mutable_request_data();
nsCOMPtr<nsIURI> url;
rv = aIn->GetUrl(getter_AddRefs(url));
NS_ENSURE_SUCCESS(rv, rv);
nsCString urlString;
rv = url->GetSpec(urlString);
NS_ENSURE_SUCCESS(rv, rv);
if (!urlString.IsEmpty()) {
requestData->set_url(urlString.get());
}
nsString email;
rv = aIn->GetEmail(email);
NS_ENSURE_SUCCESS(rv, rv);
if (!email.IsEmpty()) {
requestData->set_email(NS_ConvertUTF16toUTF8(email).get());
}
nsCString sha256Digest;
rv = aIn->GetSha256Digest(sha256Digest);
NS_ENSURE_SUCCESS(rv, rv);
if (!sha256Digest.IsEmpty()) {
requestData->set_digest(sha256Digest.get());
}
if (analysisType == nsIContentAnalysisRequest::AnalysisType::ePrint) {
#if XP_WIN
uint64_t printDataHandle;
MOZ_TRY(aIn->GetPrintDataHandle(&printDataHandle));
if (!printDataHandle) {
return NS_ERROR_OUT_OF_MEMORY;
}
aOut->mutable_print_data()->set_handle(printDataHandle);
uint64_t printDataSize;
MOZ_TRY(aIn->GetPrintDataSize(&printDataSize));
aOut->mutable_print_data()->set_size(printDataSize);
nsString printerName;
MOZ_TRY(aIn->GetPrinterName(printerName));
requestData->mutable_print_metadata()->set_printer_name(
NS_ConvertUTF16toUTF8(printerName).get());
#else
return NS_ERROR_NOT_IMPLEMENTED;
#endif
} else {
nsString filePath;
rv = aIn->GetFilePath(filePath);
NS_ENSURE_SUCCESS(rv, rv);
if (!filePath.IsEmpty()) {
std::string filePathStr = NS_ConvertUTF16toUTF8(filePath).get();
aOut->set_file_path(filePathStr);
auto filename = filePathStr.substr(filePathStr.find_last_of("/\\") + 1);
if (!filename.empty()) {
requestData->set_filename(filename);
}
} else {
nsString textContent;
rv = aIn->GetTextContent(textContent);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(!textContent.IsEmpty());
aOut->set_text_content(NS_ConvertUTF16toUTF8(textContent).get());
}
}
#ifdef XP_WIN
ULONG userLen = 0;
GetUserNameExW(NameSamCompatible, nullptr, &userLen);
if (GetLastError() == ERROR_MORE_DATA && userLen > 0) {
auto user = mozilla::MakeUnique<wchar_t[]>(userLen);
if (GetUserNameExW(NameSamCompatible, user.get(), &userLen)) {
auto* clientMetadata = aOut->mutable_client_metadata();
auto* browser = clientMetadata->mutable_browser();
browser->set_machine_user(NS_ConvertUTF16toUTF8(user.get()).get());
}
}
#endif
nsTArray<RefPtr<nsIClientDownloadResource>> resources;
rv = aIn->GetResources(resources);
NS_ENSURE_SUCCESS(rv, rv);
if (!resources.IsEmpty()) {
auto* pbClientDownloadRequest = requestData->mutable_csd();
for (auto& nsResource : resources) {
rv = ConvertToProtobuf(nsResource.get(),
pbClientDownloadRequest->add_resources());
NS_ENSURE_SUCCESS(rv, rv);
}
}
return NS_OK;
}
namespace {
// We don't want this overload to be called for string parameters, so
// use std::enable_if
template <typename T>
typename std::enable_if_t<!std::is_same<std::string, std::decay_t<T>>::value,
void>
LogWithMaxLength(std::stringstream& ss, T value, size_t maxLength) {
ss << value;
}
// 0 indicates no max length
template <typename T>
typename std::enable_if_t<std::is_same<std::string, std::decay_t<T>>::value,
void>
LogWithMaxLength(std::stringstream& ss, T value, size_t maxLength) {
if (!maxLength || value.length() < maxLength) {
ss << value;
} else {
ss << value.substr(0, maxLength) << " (truncated)";
}
}
} // namespace
static void LogRequest(
const content_analysis::sdk::ContentAnalysisRequest* aPbRequest) {
// We cannot use Protocol Buffer's DebugString() because we optimize for
// lite runtime.
if (!static_cast<LogModule*>(gContentAnalysisLog)
->ShouldLog(LogLevel::Debug)) {
return;
}
std::stringstream ss;
ss << "ContentAnalysisRequest:"
<< "\n";
#define ADD_FIELD(PBUF, NAME, FUNC) \
ss << " " << (NAME) << ": "; \
if ((PBUF)->has_##FUNC()) { \
LogWithMaxLength(ss, (PBUF)->FUNC(), 500); \
ss << "\n"; \
} else \
ss << "<none>" \
<< "\n";
#define ADD_EXISTS(PBUF, NAME, FUNC) \
ss << " " << (NAME) << ": " \
<< ((PBUF)->has_##FUNC() ? "<exists>" : "<none>") << "\n";
ADD_FIELD(aPbRequest, "Expires", expires_at);
ADD_FIELD(aPbRequest, "Analysis Type", analysis_connector);
ADD_FIELD(aPbRequest, "Request Token", request_token);
ADD_FIELD(aPbRequest, "File Path", file_path);
ADD_FIELD(aPbRequest, "Text Content", text_content);
// TODO: Tags
ADD_EXISTS(aPbRequest, "Request Data Struct", request_data);
const auto* requestData =
aPbRequest->has_request_data() ? &aPbRequest->request_data() : nullptr;
if (requestData) {
ADD_FIELD(requestData, " Url", url);
ADD_FIELD(requestData, " Email", email);
ADD_FIELD(requestData, " SHA-256 Digest", digest);
ADD_FIELD(requestData, " Filename", filename);
ADD_EXISTS(requestData, " Client Download Request struct", csd);
const auto* csd = requestData->has_csd() ? &requestData->csd() : nullptr;
if (csd) {
uint32_t i = 0;
for (const auto& resource : csd->resources()) {
ss << " Resource " << i << ":"
<< "\n";
ADD_FIELD(&resource, " Url", url);
ADD_FIELD(&resource, " Type", type);
++i;
}
}
}
ADD_EXISTS(aPbRequest, "Client Metadata Struct", client_metadata);
const auto* clientMetadata = aPbRequest->has_client_metadata()
? &aPbRequest->client_metadata()
: nullptr;
if (clientMetadata) {
ADD_EXISTS(clientMetadata, " Browser Struct", browser);
const auto* browser =
clientMetadata->has_browser() ? &clientMetadata->browser() : nullptr;
if (browser) {
ADD_FIELD(browser, " Machine User", machine_user);
}
}
#undef ADD_EXISTS
#undef ADD_FIELD
LOGD("%s", ss.str().c_str());
}
ContentAnalysisResponse::ContentAnalysisResponse(
content_analysis::sdk::ContentAnalysisResponse&& aResponse) {
mAction = Action::eUnspecified;
for (const auto& result : aResponse.results()) {
if (!result.has_status() ||
result.status() !=
content_analysis::sdk::ContentAnalysisResponse::Result::SUCCESS) {
mAction = Action::eUnspecified;
return;
}
// The action values increase with severity, so the max is the most severe.
for (const auto& rule : result.triggered_rules()) {
mAction =
static_cast<Action>(std::max(static_cast<uint32_t>(mAction),
static_cast<uint32_t>(rule.action())));
}
}
// If no rules blocked then we should allow.
if (mAction == Action::eUnspecified) {
mAction = Action::eAllow;
}
const auto& requestToken = aResponse.request_token();
mRequestToken.Assign(requestToken.data(), requestToken.size());
}
ContentAnalysisResponse::ContentAnalysisResponse(
Action aAction, const nsACString& aRequestToken)
: mAction(aAction), mRequestToken(aRequestToken) {}
/* static */
already_AddRefed<ContentAnalysisResponse> ContentAnalysisResponse::FromProtobuf(
content_analysis::sdk::ContentAnalysisResponse&& aResponse) {
auto ret = RefPtr<ContentAnalysisResponse>(
new ContentAnalysisResponse(std::move(aResponse)));
if (ret->mAction == Action::eUnspecified) {
return nullptr;
}
return ret.forget();
}
/* static */
RefPtr<ContentAnalysisResponse> ContentAnalysisResponse::FromAction(
Action aAction, const nsACString& aRequestToken) {
if (aAction == Action::eUnspecified) {
return nullptr;
}
return RefPtr<ContentAnalysisResponse>(
new ContentAnalysisResponse(aAction, aRequestToken));
}
NS_IMETHODIMP
ContentAnalysisResponse::GetRequestToken(nsACString& aRequestToken) {
aRequestToken = mRequestToken;
return NS_OK;
}
static void LogResponse(
content_analysis::sdk::ContentAnalysisResponse* aPbResponse) {
if (!static_cast<LogModule*>(gContentAnalysisLog)
->ShouldLog(LogLevel::Debug)) {
return;
}
std::stringstream ss;
ss << "ContentAnalysisResponse:"
<< "\n";
#define ADD_FIELD(PBUF, NAME, FUNC) \
ss << " " << (NAME) << ": "; \
if ((PBUF)->has_##FUNC()) \
ss << (PBUF)->FUNC() << "\n"; \
else \
ss << "<none>" \
<< "\n";
ADD_FIELD(aPbResponse, "Request Token", request_token);
uint32_t i = 0;
for (const auto& result : aPbResponse->results()) {
ss << " Result " << i << ":"
<< "\n";
ADD_FIELD(&result, " Status", status);
uint32_t j = 0;
for (const auto& rule : result.triggered_rules()) {
ss << " Rule " << j << ":"
<< "\n";
ADD_FIELD(&rule, " action", action);
++j;
}
++i;
}
#undef ADD_FIELD
LOGD("%s", ss.str().c_str());
}
static nsresult ConvertToProtobuf(
nsIContentAnalysisAcknowledgement* aIn, const nsACString& aRequestToken,
content_analysis::sdk::ContentAnalysisAcknowledgement* aOut) {
aOut->set_request_token(aRequestToken.Data(), aRequestToken.Length());
nsIContentAnalysisAcknowledgement::Result result;
nsresult rv = aIn->GetResult(&result);
NS_ENSURE_SUCCESS(rv, rv);
aOut->set_status(
static_cast<content_analysis::sdk::ContentAnalysisAcknowledgement_Status>(
result));
nsIContentAnalysisAcknowledgement::FinalAction finalAction;
rv = aIn->GetFinalAction(&finalAction);
NS_ENSURE_SUCCESS(rv, rv);
aOut->set_final_action(
static_cast<
content_analysis::sdk::ContentAnalysisAcknowledgement_FinalAction>(
finalAction));
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisResponse::GetAction(Action* aAction) {
*aAction = mAction;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisResponse::GetCancelError(CancelError* aCancelError) {
*aCancelError = mCancelError;
return NS_OK;
}
static void LogAcknowledgement(
content_analysis::sdk::ContentAnalysisAcknowledgement* aPbAck) {
if (!static_cast<LogModule*>(gContentAnalysisLog)
->ShouldLog(LogLevel::Debug)) {
return;
}
std::stringstream ss;
ss << "ContentAnalysisAcknowledgement:"
<< "\n";
#define ADD_FIELD(PBUF, NAME, FUNC) \
ss << " " << (NAME) << ": "; \
if ((PBUF)->has_##FUNC()) \
ss << (PBUF)->FUNC() << "\n"; \
else \
ss << "<none>" \
<< "\n";
ADD_FIELD(aPbAck, "Status", status);
ADD_FIELD(aPbAck, "Final Action", final_action);
#undef ADD_FIELD
LOGD("%s", ss.str().c_str());
}
void ContentAnalysisResponse::SetOwner(RefPtr<ContentAnalysis> aOwner) {
mOwner = std::move(aOwner);
}
void ContentAnalysisResponse::SetCancelError(CancelError aCancelError) {
mCancelError = aCancelError;
}
void ContentAnalysisResponse::ResolveWarnAction(bool aAllowContent) {
MOZ_ASSERT(mAction == Action::eWarn);
mAction = aAllowContent ? Action::eAllow : Action::eBlock;
}
ContentAnalysisAcknowledgement::ContentAnalysisAcknowledgement(
Result aResult, FinalAction aFinalAction)
: mResult(aResult), mFinalAction(aFinalAction) {}
NS_IMETHODIMP
ContentAnalysisAcknowledgement::GetResult(Result* aResult) {
*aResult = mResult;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysisAcknowledgement::GetFinalAction(FinalAction* aFinalAction) {
*aFinalAction = mFinalAction;
return NS_OK;
}
namespace {
static bool ShouldAllowAction(
nsIContentAnalysisResponse::Action aResponseCode) {
return aResponseCode == nsIContentAnalysisResponse::Action::eAllow ||
aResponseCode == nsIContentAnalysisResponse::Action::eReportOnly ||
aResponseCode == nsIContentAnalysisResponse::Action::eWarn;
}
static DefaultResult GetDefaultResultFromPref() {
uint32_t value = StaticPrefs::browser_contentanalysis_default_result();
if (value > static_cast<uint32_t>(DefaultResult::eLastValue)) {
LOGE(
"Invalid value for browser.contentanalysis.default_result pref "
"value");
return DefaultResult::eBlock;
}
return static_cast<DefaultResult>(value);
}
} // namespace
NS_IMETHODIMP ContentAnalysisResponse::GetShouldAllowContent(
bool* aShouldAllowContent) {
*aShouldAllowContent = ShouldAllowAction(mAction);
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisResult::GetShouldAllowContent(
bool* aShouldAllowContent) {
if (mValue.is<NoContentAnalysisResult>()) {
NoContentAnalysisResult result = mValue.as<NoContentAnalysisResult>();
if (GetDefaultResultFromPref() == DefaultResult::eAllow) {
*aShouldAllowContent =
result != NoContentAnalysisResult::DENY_DUE_TO_CANCELED;
} else {
// Note that we allow content if we're unable to get it (for example, if
// there's clipboard content that is not text or file)
*aShouldAllowContent =
result == NoContentAnalysisResult::
ALLOW_DUE_TO_CONTENT_ANALYSIS_NOT_ACTIVE ||
result == NoContentAnalysisResult::
ALLOW_DUE_TO_CONTEXT_EXEMPT_FROM_CONTENT_ANALYSIS ||
result == NoContentAnalysisResult::ALLOW_DUE_TO_SAME_TAB_SOURCE ||
result == NoContentAnalysisResult::ALLOW_DUE_TO_COULD_NOT_GET_DATA;
}
} else {
*aShouldAllowContent =
ShouldAllowAction(mValue.as<nsIContentAnalysisResponse::Action>());
}
return NS_OK;
}
void ContentAnalysis::EnsureParsedUrlFilters() {
MOZ_ASSERT(NS_IsMainThread());
if (mParsedUrlLists) {
return;
}
mParsedUrlLists = true;
nsAutoCString allowList;
MOZ_ALWAYS_SUCCEEDS(Preferences::GetCString(kAllowUrlPref, allowList));
for (const nsACString& regexSubstr : allowList.Split(u' ')) {
if (!regexSubstr.IsEmpty()) {
auto flatStr = PromiseFlatCString(regexSubstr);
const char* regex = flatStr.get();
LOGD("CA will allow URLs that match %s", regex);
mAllowUrlList.push_back(std::regex(regex));
}
}
nsAutoCString denyList;
MOZ_ALWAYS_SUCCEEDS(Preferences::GetCString(kDenyUrlPref, denyList));
for (const nsACString& regexSubstr : denyList.Split(u' ')) {
if (!regexSubstr.IsEmpty()) {
auto flatStr = PromiseFlatCString(regexSubstr);
const char* regex = flatStr.get();
LOGD("CA will block URLs that match %s", regex);
mDenyUrlList.push_back(std::regex(regex));
}
}
}
ContentAnalysis::UrlFilterResult ContentAnalysis::FilterByUrlLists(
nsIContentAnalysisRequest* aRequest) {
EnsureParsedUrlFilters();
nsCOMPtr<nsIURI> nsiUrl;
MOZ_ALWAYS_SUCCEEDS(aRequest->GetUrl(getter_AddRefs(nsiUrl)));
nsCString urlString;
nsresult rv = nsiUrl->GetSpec(urlString);
NS_ENSURE_SUCCESS(rv, UrlFilterResult::eDeny);
MOZ_ASSERT(!urlString.IsEmpty());
std::string url = urlString.BeginReading();
size_t count = 0;
for (const auto& denyFilter : mDenyUrlList) {
if (std::regex_search(url, denyFilter)) {
LOGD("Denying CA request : Deny filter %zu matched url %s", count,
url.c_str());
return UrlFilterResult::eDeny;
}
++count;
}
count = 0;
UrlFilterResult result = UrlFilterResult::eCheck;
for (const auto& allowFilter : mAllowUrlList) {
if (std::regex_match(url, allowFilter)) {
LOGD("CA request : Allow filter %zu matched %s", count, url.c_str());
result = UrlFilterResult::eAllow;
break;
}
++count;
}
// The rest only applies to download resources.
nsIContentAnalysisRequest::AnalysisType analysisType;
MOZ_ALWAYS_SUCCEEDS(aRequest->GetAnalysisType(&analysisType));
if (analysisType != ContentAnalysisRequest::AnalysisType::eFileDownloaded) {
MOZ_ASSERT(result == UrlFilterResult::eCheck ||
result == UrlFilterResult::eAllow);
LOGD("CA request filter result: %s",
result == UrlFilterResult::eCheck ? "check" : "allow");
return result;
}
nsTArray<RefPtr<nsIClientDownloadResource>> resources;
MOZ_ALWAYS_SUCCEEDS(aRequest->GetResources(resources));
for (size_t resourceIdx = 0; resourceIdx < resources.Length();
/* noop */) {
auto& resource = resources[resourceIdx];
nsAutoString nsUrl;
MOZ_ALWAYS_SUCCEEDS(resource->GetUrl(nsUrl));
std::string url = NS_ConvertUTF16toUTF8(nsUrl).get();
count = 0;
for (auto& denyFilter : mDenyUrlList) {
if (std::regex_search(url, denyFilter)) {
LOGD(
"Denying CA request : Deny filter %zu matched download resource "
"at url %s",
count, url.c_str());
return UrlFilterResult::eDeny;
}
++count;
}
count = 0;
bool removed = false;
for (auto& allowFilter : mAllowUrlList) {
if (std::regex_search(url, allowFilter)) {
LOGD(
"CA request : Allow filter %zu matched download resource "
"at url %s",
count, url.c_str());
resources.RemoveElementAt(resourceIdx);
removed = true;
break;
}
++count;
}
if (!removed) {
++resourceIdx;
}
}
// Check unless all were allowed.
return resources.Length() ? UrlFilterResult::eCheck : UrlFilterResult::eAllow;
}
NS_IMPL_CLASSINFO(ContentAnalysisRequest, nullptr, 0, {0});
NS_IMPL_ISUPPORTS_CI(ContentAnalysisRequest, nsIContentAnalysisRequest);
NS_IMPL_CLASSINFO(ContentAnalysisResponse, nullptr, 0, {0});
NS_IMPL_ISUPPORTS_CI(ContentAnalysisResponse, nsIContentAnalysisResponse);
NS_IMPL_ISUPPORTS(ContentAnalysisAcknowledgement,
nsIContentAnalysisAcknowledgement);
NS_IMPL_ISUPPORTS(ContentAnalysisCallback, nsIContentAnalysisCallback);
NS_IMPL_ISUPPORTS(ContentAnalysisResult, nsIContentAnalysisResult);
NS_IMPL_ISUPPORTS(ContentAnalysisDiagnosticInfo,
nsIContentAnalysisDiagnosticInfo);
NS_IMPL_ISUPPORTS(ContentAnalysis, nsIContentAnalysis, ContentAnalysis);
ContentAnalysis::ContentAnalysis()
: mCaClientPromise(
new ClientPromise::Private("ContentAnalysis::ContentAnalysis")),
mClientCreationAttempted(false),
mSetByEnterprise(false),
mCallbackMap("ContentAnalysis::mCallbackMap"),
mWarnResponseDataMap("ContentAnalysis::mWarnResponseDataMap") {
GenerateUserActionId();
}
ContentAnalysis::~ContentAnalysis() {
// Accessing mClientCreationAttempted so need to be on the main thread
MOZ_ASSERT(NS_IsMainThread());
if (!mClientCreationAttempted) {
// Reject the promise to avoid assertions when it gets destroyed
mCaClientPromise->Reject(NS_ERROR_ILLEGAL_DURING_SHUTDOWN, __func__);
}
}
NS_IMETHODIMP
ContentAnalysis::GetIsActive(bool* aIsActive) {
*aIsActive = false;
// Need to be on the main thread to read prefs
MOZ_ASSERT(NS_IsMainThread());
// gAllowContentAnalysisArgPresent is only set in the parent process
MOZ_ASSERT(XRE_IsParentProcess());
if (!Preferences::GetBool(kIsDLPEnabledPref)) {
LOGD("Local DLP Content Analysis is not active");
return NS_OK;
}
if (!gAllowContentAnalysisArgPresent && !mSetByEnterprise) {
LOGE(
"The content analysis pref is enabled but not by an enterprise "
"policy and -allow-content-analysis was not present on the "
"command-line. Content Analysis will not be active.");
return NS_OK;
}
*aIsActive = true;
LOGD("Local DLP Content Analysis is active");
// mClientCreationAttempted is only accessed on the main thread,
// so no need for synchronization here.
if (!mClientCreationAttempted) {
mClientCreationAttempted = true;
LOGD("Dispatching background task to create Content Analysis client");
nsCString pipePathName;
nsresult rv = Preferences::GetCString(kPipePathNamePref, pipePathName);
if (NS_WARN_IF(NS_FAILED(rv))) {
mCaClientPromise->Reject(rv, __func__);
return rv;
}
bool isPerUser = Preferences::GetBool(kIsPerUserPref);
nsString clientSignature;
// It's OK if this fails, we will default to the empty string
Preferences::GetString(kClientSignature, clientSignature);
rv = NS_DispatchBackgroundTask(NS_NewCancelableRunnableFunction(
"ContentAnalysis::CreateContentAnalysisClient",
[owner = RefPtr{this}, pipePathName = std::move(pipePathName),
clientSignature = std::move(clientSignature), isPerUser]() mutable {
owner->CreateContentAnalysisClient(
std::move(pipePathName), std::move(clientSignature), isPerUser);
}));
if (NS_WARN_IF(NS_FAILED(rv))) {
mCaClientPromise->Reject(rv, __func__);
return rv;
}
}
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::GetMightBeActive(bool* aMightBeActive) {
// A DLP connection is not permitted to be added/removed while the
// browser is running, so we can cache this.
static bool sIsEnabled = Preferences::GetBool(kIsDLPEnabledPref);
// Note that we can't check gAllowContentAnalysis here because it
// only gets set in the parent process.
*aMightBeActive = sIsEnabled;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::GetIsSetByEnterprisePolicy(bool* aSetByEnterprise) {
*aSetByEnterprise = mSetByEnterprise;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::SetIsSetByEnterprisePolicy(bool aSetByEnterprise) {
mSetByEnterprise = aSetByEnterprise;
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::TestOnlySetCACmdLineArg(bool aVal) {
#ifdef ENABLE_TESTS
gAllowContentAnalysisArgPresent = aVal;
return NS_OK;
#else
LOGE("ContentAnalysis::TestOnlySetCACmdLineArg is test-only");
return NS_ERROR_UNEXPECTED;
#endif
}
nsresult ContentAnalysis::CancelWithError(nsCString aRequestToken,
nsresult aResult) {
return NS_DispatchToMainThread(NS_NewCancelableRunnableFunction(
"ContentAnalysis::CancelWithError",
[aResult, aRequestToken = std::move(aRequestToken)]() mutable {
RefPtr<ContentAnalysis> owner = GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
owner->SetLastResult(aResult);
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
DefaultResult defaultResponse = GetDefaultResultFromPref();
nsIContentAnalysisResponse::Action action;
switch (defaultResponse) {
case DefaultResult::eAllow:
action = nsIContentAnalysisResponse::Action::eAllow;
break;
case DefaultResult::eWarn:
action = nsIContentAnalysisResponse::Action::eWarn;
break;
case DefaultResult::eBlock:
action = nsIContentAnalysisResponse::Action::eCanceled;
break;
default:
MOZ_ASSERT(false);
action = nsIContentAnalysisResponse::Action::eCanceled;
}
RefPtr<ContentAnalysisResponse> response =
ContentAnalysisResponse::FromAction(action, aRequestToken);
response->SetOwner(owner);
nsIContentAnalysisResponse::CancelError cancelError;
switch (aResult) {
case NS_ERROR_NOT_AVAILABLE:
cancelError = nsIContentAnalysisResponse::CancelError::eNoAgent;
break;
case NS_ERROR_INVALID_SIGNATURE:
cancelError =
nsIContentAnalysisResponse::CancelError::eInvalidAgentSignature;
break;
default:
cancelError = nsIContentAnalysisResponse::CancelError::eErrorOther;
break;
}
response->SetCancelError(cancelError);
Maybe<CallbackData> maybeCallbackData;
{
auto lock = owner->mCallbackMap.Lock();
maybeCallbackData = lock->Extract(aRequestToken);
if (maybeCallbackData.isNothing()) {
LOGD("Content analysis did not find callback for token %s",
aRequestToken.get());
return;
}
}
if (action == nsIContentAnalysisResponse::Action::eWarn) {
owner->SendWarnResponse(std::move(aRequestToken),
std::move(*maybeCallbackData), response);
return;
}
nsMainThreadPtrHandle<nsIContentAnalysisCallback> callbackHolder =
maybeCallbackData->TakeCallbackHolder();
obsServ->NotifyObservers(response, "dlp-response", nullptr);
if (callbackHolder) {
if (action == nsIContentAnalysisResponse::Action::eCanceled) {
callbackHolder->Error(aResult);
} else {
callbackHolder->ContentResult(response);
}
}
}));
}
RefPtr<ContentAnalysis> ContentAnalysis::GetContentAnalysisFromService() {
RefPtr<ContentAnalysis> contentAnalysisService =
mozilla::components::nsIContentAnalysis::Service();
if (!contentAnalysisService) {
// May be shutting down
return nullptr;
}
return contentAnalysisService;
}
nsresult ContentAnalysis::RunAnalyzeRequestTask(
const RefPtr<nsIContentAnalysisRequest>& aRequest, bool aAutoAcknowledge,
int64_t aRequestCount,
const RefPtr<nsIContentAnalysisCallback>& aCallback) {
MOZ_ASSERT(NS_IsMainThread());
nsresult rv = NS_ERROR_FAILURE;
auto callbackCopy = aCallback;
auto se = MakeScopeExit([&] {
if (!NS_SUCCEEDED(rv)) {
LOGE("RunAnalyzeRequestTask failed");
callbackCopy->Error(rv);
}
});
nsCString requestToken;
rv = aRequest->GetRequestToken(requestToken);
NS_ENSURE_SUCCESS(rv, rv);
nsMainThreadPtrHandle<nsIContentAnalysisCallback> callbackHolderCopy(
new nsMainThreadPtrHolder<nsIContentAnalysisCallback>(
"content analysis callback", aCallback));
CallbackData callbackData(std::move(callbackHolderCopy), aAutoAcknowledge);
{
auto lock = mCallbackMap.Lock();
lock->InsertOrUpdate(requestToken, std::move(callbackData));
}
// Check URLs of requested info against
// browser.contentanalysis.allow_url_regex_list/deny_url_regex_list.
// Build the list once since creating regexs is slow.
// URLs that match the allow list are removed from the check. There is
// only one URL in all cases except downloads. If all contents are removed
// or the page URL is allowed (for downloads) then the operation is allowed.
// URLs that match the deny list block the entire operation.
// If the request is completely covered by this filter then flag it as
// not needing to send an Acknowledge.
auto filterResult = FilterByUrlLists(aRequest);
if (filterResult == ContentAnalysis::UrlFilterResult::eDeny) {
LOGD("Blocking request due to deny URL filter.");
auto response = ContentAnalysisResponse::FromAction(
nsIContentAnalysisResponse::Action::eBlock, requestToken);
response->DoNotAcknowledge();
IssueResponse(response);
return NS_OK;
}
if (filterResult == ContentAnalysis::UrlFilterResult::eAllow) {
LOGD("Allowing request -- all operations match allow URL filter.");
auto response = ContentAnalysisResponse::FromAction(
nsIContentAnalysisResponse::Action::eAllow, requestToken);
response->DoNotAcknowledge();
IssueResponse(response);
return NS_OK;
}
LOGD("Issuing ContentAnalysisRequest for token %s", requestToken.get());
content_analysis::sdk::ContentAnalysisRequest pbRequest;
rv =
ConvertToProtobuf(aRequest, GetUserActionId(), aRequestCount, &pbRequest);
NS_ENSURE_SUCCESS(rv, rv);
LogRequest(&pbRequest);
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
// Avoid serializing the string here if no one is observing this message
if (obsServ->HasObservers("dlp-request-sent-raw")) {
std::string requestString = pbRequest.SerializeAsString();
nsTArray<char16_t> requestArray;
requestArray.SetLength(requestString.size() + 1);
for (size_t i = 0; i < requestString.size(); ++i) {
// Since NotifyObservers() expects a null-terminated string,
// make sure none of these values are 0.
requestArray[i] = requestString[i] + 0xFF00;
}
requestArray[requestString.size()] = 0;
obsServ->NotifyObservers(this, "dlp-request-sent-raw",
requestArray.Elements());
}
mCaClientPromise->Then(
GetCurrentSerialEventTarget(), __func__,
[requestToken, pbRequest = std::move(pbRequest)](
std::shared_ptr<content_analysis::sdk::Client> client) mutable {
// The content analysis call is synchronous so run in the background.
NS_DispatchBackgroundTask(
NS_NewCancelableRunnableFunction(
__func__,
[requestToken, pbRequest = std::move(pbRequest),
client = std::move(client)]() mutable {
DoAnalyzeRequest(requestToken, std::move(pbRequest), client);
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
},
[requestToken](nsresult rv) mutable {
LOGD("RunAnalyzeRequestTask failed to get client");
RefPtr<ContentAnalysis> owner = GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
owner->CancelWithError(std::move(requestToken), rv);
});
return rv;
}
void ContentAnalysis::DoAnalyzeRequest(
nsCString aRequestToken,
content_analysis::sdk::ContentAnalysisRequest&& aRequest,
const std::shared_ptr<content_analysis::sdk::Client>& aClient) {
MOZ_ASSERT(!NS_IsMainThread());
RefPtr<ContentAnalysis> owner =
ContentAnalysis::GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
if (!aClient) {
owner->CancelWithError(std::move(aRequestToken), NS_ERROR_NOT_AVAILABLE);
return;
}
if (aRequest.has_file_path() && !aRequest.file_path().empty() &&
(!aRequest.request_data().has_digest() ||
aRequest.request_data().digest().empty())) {
// Calculate the digest
nsCString digest;
nsCString fileCPath(aRequest.file_path().data(),
aRequest.file_path().length());
nsString filePath = NS_ConvertUTF8toUTF16(fileCPath);
nsresult rv = ContentAnalysisRequest::GetFileDigest(filePath, digest);
if (NS_FAILED(rv)) {
owner->CancelWithError(std::move(aRequestToken), rv);
return;
}
if (!digest.IsEmpty()) {
aRequest.mutable_request_data()->set_digest(digest.get());
}
}
{
auto callbackMap = owner->mCallbackMap.Lock();
if (!callbackMap->Contains(aRequestToken)) {
LOGD(
"RunAnalyzeRequestTask token %s has already been "
"cancelled - not issuing request",
aRequestToken.get());
return;
}
}
// Run request, then dispatch back to main thread to resolve
// aCallback
content_analysis::sdk::ContentAnalysisResponse pbResponse;
int err = aClient->Send(aRequest, &pbResponse);
if (err != 0) {
LOGE("RunAnalyzeRequestTask client transaction failed");
owner->CancelWithError(std::move(aRequestToken), NS_ERROR_FAILURE);
return;
}
LOGD("Content analysis client transaction succeeded");
LogResponse(&pbResponse);
NS_DispatchToMainThread(NS_NewCancelableRunnableFunction(
"ContentAnalysis::RunAnalyzeRequestTask::HandleResponse",
[pbResponse = std::move(pbResponse)]() mutable {
RefPtr<ContentAnalysis> owner = GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
RefPtr<ContentAnalysisResponse> response =
ContentAnalysisResponse::FromProtobuf(std::move(pbResponse));
if (!response) {
LOGE("Content analysis got invalid response!");
return;
}
owner->IssueResponse(response);
}));
}
void ContentAnalysis::SendWarnResponse(
nsCString&& aResponseRequestToken, CallbackData aCallbackData,
RefPtr<ContentAnalysisResponse>& aResponse) {
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
{
auto warnResponseDataMap = mWarnResponseDataMap.Lock();
warnResponseDataMap->InsertOrUpdate(
aResponseRequestToken,
WarnResponseData(std::move(aCallbackData), aResponse));
}
obsServ->NotifyObservers(aResponse, "dlp-response", nullptr);
}
void ContentAnalysis::IssueResponse(RefPtr<ContentAnalysisResponse>& response) {
MOZ_ASSERT(NS_IsMainThread());
nsCString responseRequestToken;
nsresult requestRv = response->GetRequestToken(responseRequestToken);
if (NS_FAILED(requestRv)) {
LOGE("Content analysis couldn't get request token from response!");
return;
}
// Successfully made a request to the agent, so mark that we succeeded
mLastResult = NS_OK;
Maybe<CallbackData> maybeCallbackData;
{
auto callbackMap = mCallbackMap.Lock();
maybeCallbackData = callbackMap->Extract(responseRequestToken);
}
if (maybeCallbackData.isNothing()) {
LOGD("Content analysis did not find callback for token %s",
responseRequestToken.get());
return;
}
response->SetOwner(this);
if (maybeCallbackData->Canceled()) {
// request has already been cancelled, so there's
// nothing to do
LOGD(
"Content analysis got response but ignoring "
"because it was already cancelled for token %s",
responseRequestToken.get());
// Note that we always acknowledge here, even if
// autoAcknowledge isn't set, since we raise an exception
// at the caller on cancellation.
auto acknowledgement = MakeRefPtr<ContentAnalysisAcknowledgement>(
nsIContentAnalysisAcknowledgement::Result::eTooLate,
nsIContentAnalysisAcknowledgement::FinalAction::eBlock);
response->Acknowledge(acknowledgement);
return;
}
LOGD("Content analysis resolving response promise for token %s",
responseRequestToken.get());
nsIContentAnalysisResponse::Action action;
DebugOnly<nsresult> rv = response->GetAction(&action);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
if (action == nsIContentAnalysisResponse::Action::eWarn) {
SendWarnResponse(std::move(responseRequestToken),
std::move(*maybeCallbackData), response);
return;
}
obsServ->NotifyObservers(response, "dlp-response", nullptr);
if (maybeCallbackData->AutoAcknowledge()) {
auto acknowledgement = MakeRefPtr<ContentAnalysisAcknowledgement>(
nsIContentAnalysisAcknowledgement::Result::eSuccess,
ConvertResult(action));
response->Acknowledge(acknowledgement);
}
nsMainThreadPtrHandle<nsIContentAnalysisCallback> callbackHolder =
maybeCallbackData->TakeCallbackHolder();
callbackHolder->ContentResult(response);
}
NS_IMETHODIMP
ContentAnalysis::AnalyzeContentRequest(nsIContentAnalysisRequest* aRequest,
bool aAutoAcknowledge, JSContext* aCx,
mozilla::dom::Promise** aPromise) {
RefPtr<mozilla::dom::Promise> promise;
nsresult rv = MakePromise(aCx, &promise);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<ContentAnalysisCallback> callbackPtr =
new ContentAnalysisCallback(promise);
promise.forget(aPromise);
return AnalyzeContentRequestCallback(aRequest, aAutoAcknowledge,
callbackPtr.get());
}
NS_IMETHODIMP
ContentAnalysis::AnalyzeContentRequestCallback(
nsIContentAnalysisRequest* aRequest, bool aAutoAcknowledge,
nsIContentAnalysisCallback* aCallback) {
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_ARG(aRequest);
NS_ENSURE_ARG(aCallback);
nsresult rv = AnalyzeContentRequestCallbackPrivate(aRequest, aAutoAcknowledge,
aCallback);
if (NS_FAILED(rv)) {
nsCString requestToken;
nsresult requestTokenRv = aRequest->GetRequestToken(requestToken);
NS_ENSURE_SUCCESS(requestTokenRv, requestTokenRv);
CancelWithError(requestToken, rv);
}
return rv;
}
nsresult ContentAnalysis::AnalyzeContentRequestCallbackPrivate(
nsIContentAnalysisRequest* aRequest, bool aAutoAcknowledge,
nsIContentAnalysisCallback* aCallback) {
// Make sure we send the notification first, so if we later return
// an error the JS will handle it correctly.
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
obsServ->NotifyObservers(aRequest, "dlp-request-made", nullptr);
bool isActive;
nsresult rv = GetIsActive(&isActive);
NS_ENSURE_SUCCESS(rv, rv);
if (!isActive) {
return NS_ERROR_NOT_AVAILABLE;
}
MOZ_ASSERT(NS_IsMainThread());
// since we're on the main thread, don't need to synchronize this
int64_t requestCount = ++mRequestCount;
return RunAnalyzeRequestTask(aRequest, aAutoAcknowledge, requestCount,
aCallback);
}
NS_IMETHODIMP
ContentAnalysis::CancelContentAnalysisRequest(const nsACString& aRequestToken) {
MOZ_ASSERT(NS_IsMainThread());
nsCString requestToken(aRequestToken);
auto callbackMap = mCallbackMap.Lock();
auto entry = callbackMap->Lookup(requestToken);
LOGD("Content analysis cancelling request %s", requestToken.get());
// Make sure the entry hasn't been cancelled already
if (entry && !entry->Canceled()) {
nsMainThreadPtrHandle<nsIContentAnalysisCallback> callbackHolder =
entry->TakeCallbackHolder();
entry->SetCanceled();
// Should only be called once
MOZ_ASSERT(callbackHolder);
if (callbackHolder) {
callbackHolder->Error(NS_ERROR_ABORT);
}
} else {
LOGD("Content analysis request not found when trying to cancel %s",
requestToken.get());
}
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::CancelAllRequests() {
mCaClientPromise->Then(
GetCurrentSerialEventTarget(), __func__,
[&](std::shared_ptr<content_analysis::sdk::Client> client) {
auto owner = GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
if (!client) {
LOGE("CancelAllRequests got a null client");
return;
}
content_analysis::sdk::ContentAnalysisCancelRequests requests;
requests.set_user_action_id(owner->GetUserActionId().get());
int err = client->CancelRequests(requests);
if (err != 0) {
LOGE("CancelAllRequests got error %d", err);
} else {
LOGD("CancelAllRequests did cancelling of requests");
}
},
[&](nsresult rv) { LOGE("CancelAllRequests failed to get the client"); });
return NS_OK;
}
NS_IMETHODIMP
ContentAnalysis::RespondToWarnDialog(const nsACString& aRequestToken,
bool aAllowContent) {
nsCString requestToken(aRequestToken);
NS_DispatchToMainThread(NS_NewCancelableRunnableFunction(
"RespondToWarnDialog",
[aAllowContent, requestToken = std::move(requestToken)]() {
RefPtr<ContentAnalysis> self = GetContentAnalysisFromService();
if (!self) {
// May be shutting down
return;
}
LOGD("Content analysis getting warn response %d for request %s",
aAllowContent ? 1 : 0, requestToken.get());
Maybe<WarnResponseData> entry;
{
auto warnResponseDataMap = self->mWarnResponseDataMap.Lock();
entry = warnResponseDataMap->Extract(requestToken);
}
if (!entry) {
LOGD(
"Content analysis request not found when trying to send warn "
"response for request %s",
requestToken.get());
return;
}
entry->mResponse->ResolveWarnAction(aAllowContent);
nsIContentAnalysisResponse::Action action;
DebugOnly<nsresult> rv = entry->mResponse->GetAction(&action);
MOZ_ASSERT(NS_SUCCEEDED(rv));
if (entry->mCallbackData.AutoAcknowledge()) {
RefPtr<ContentAnalysisAcknowledgement> acknowledgement =
new ContentAnalysisAcknowledgement(
nsIContentAnalysisAcknowledgement::Result::eSuccess,
ConvertResult(action));
entry->mResponse->Acknowledge(acknowledgement);
}
nsMainThreadPtrHandle<nsIContentAnalysisCallback> callbackHolder =
entry->mCallbackData.TakeCallbackHolder();
if (callbackHolder) {
RefPtr<ContentAnalysisResponse> response =
ContentAnalysisResponse::FromAction(action, requestToken);
response->SetOwner(self);
callbackHolder.get()->ContentResult(response.get());
} else {
LOGD(
"Content analysis had no callback to send warn final response "
"to for request %s",
requestToken.get());
}
}));
return NS_OK;
}
#if defined(XP_WIN)
RefPtr<ContentAnalysis::PrintAllowedPromise>
ContentAnalysis::PrintToPDFToDetermineIfPrintAllowed(
dom::CanonicalBrowsingContext* aBrowsingContext,
nsIPrintSettings* aPrintSettings) {
// Note that the IsChrome() check here excludes a few
// common about pages like about:config, about:preferences,
// and about:support, but other about: pages may still
// go through content analysis.
if (aBrowsingContext->IsChrome()) {
return PrintAllowedPromise::CreateAndResolve(PrintAllowedResult(true),
__func__);
}
nsCOMPtr<nsIPrintSettings> contentAnalysisPrintSettings;
if (NS_WARN_IF(NS_FAILED(aPrintSettings->Clone(
getter_AddRefs(contentAnalysisPrintSettings)))) ||
NS_WARN_IF(!aBrowsingContext->GetCurrentWindowGlobal())) {
return PrintAllowedPromise::CreateAndReject(
PrintAllowedError(NS_ERROR_FAILURE), __func__);
}
contentAnalysisPrintSettings->SetOutputDestination(
nsIPrintSettings::OutputDestinationType::kOutputDestinationStream);
contentAnalysisPrintSettings->SetOutputFormat(
nsIPrintSettings::kOutputFormatPDF);
nsCOMPtr<nsIStorageStream> storageStream =
do_CreateInstance("@mozilla.org/storagestream;1");
if (!storageStream) {
return PrintAllowedPromise::CreateAndReject(
PrintAllowedError(NS_ERROR_FAILURE), __func__);
}
// Use segment size of 512K
nsresult rv = storageStream->Init(0x80000, UINT32_MAX);
if (NS_WARN_IF(NS_FAILED(rv))) {
return PrintAllowedPromise::CreateAndReject(PrintAllowedError(rv),
__func__);
}
nsCOMPtr<nsIOutputStream> outputStream;
storageStream->QueryInterface(NS_GET_IID(nsIOutputStream),
getter_AddRefs(outputStream));
MOZ_ASSERT(outputStream);
contentAnalysisPrintSettings->SetOutputStream(outputStream.get());
RefPtr<dom::CanonicalBrowsingContext> browsingContext = aBrowsingContext;
auto promise = MakeRefPtr<PrintAllowedPromise::Private>(__func__);
nsCOMPtr<nsIPrintSettings> finalPrintSettings(aPrintSettings);
aBrowsingContext
->PrintWithNoContentAnalysis(contentAnalysisPrintSettings, true, nullptr)
->Then(
GetCurrentSerialEventTarget(), __func__,
[browsingContext, contentAnalysisPrintSettings, finalPrintSettings,
promise](
dom::MaybeDiscardedBrowsingContext cachedStaticBrowsingContext)
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA mutable {
nsCOMPtr<nsIOutputStream> outputStream;
contentAnalysisPrintSettings->GetOutputStream(
getter_AddRefs(outputStream));
nsCOMPtr<nsIStorageStream> storageStream =
do_QueryInterface(outputStream);
MOZ_ASSERT(storageStream);
nsTArray<uint8_t> printData;
uint32_t length = 0;
storageStream->GetLength(&length);
if (!printData.SetLength(length, fallible)) {
promise->Reject(
PrintAllowedError(NS_ERROR_OUT_OF_MEMORY,
cachedStaticBrowsingContext),
__func__);
return;
}
nsCOMPtr<nsIInputStream> inputStream;
nsresult rv = storageStream->NewInputStream(
0, getter_AddRefs(inputStream));
if (NS_FAILED(rv)) {
promise->Reject(
PrintAllowedError(rv, cachedStaticBrowsingContext),
__func__);
return;
}
uint32_t currentPosition = 0;
while (currentPosition < length) {
uint32_t elementsRead = 0;
// Make sure the reinterpret_cast<> below is safe
static_assert(std::is_trivially_assignable_v<
decltype(*printData.Elements()), char>);
rv = inputStream->Read(
reinterpret_cast<char*>(printData.Elements()) +
currentPosition,
length - currentPosition, &elementsRead);
if (NS_WARN_IF(NS_FAILED(rv) || !elementsRead)) {
promise->Reject(
PrintAllowedError(NS_FAILED(rv) ? rv : NS_ERROR_FAILURE,
cachedStaticBrowsingContext),
__func__);
return;
}
currentPosition += elementsRead;
}
nsString printerName;
rv = contentAnalysisPrintSettings->GetPrinterName(printerName);
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->Reject(
PrintAllowedError(rv, cachedStaticBrowsingContext),
__func__);
return;
}
auto* windowParent = browsingContext->GetCurrentWindowGlobal();
if (!windowParent) {
// The print window may have been closed by the user by now.
// Cancel the print.
promise->Reject(
PrintAllowedError(NS_ERROR_ABORT,
cachedStaticBrowsingContext),
__func__);
return;
}
nsCOMPtr<nsIURI> uri = windowParent->GetDocumentURI();
nsCOMPtr<nsIContentAnalysisRequest> contentAnalysisRequest =
new contentanalysis::ContentAnalysisRequest(
std::move(printData), std::move(uri),
std::move(printerName), windowParent);
auto callback =
MakeRefPtr<contentanalysis::ContentAnalysisCallback>(
[browsingContext, cachedStaticBrowsingContext, promise,
finalPrintSettings = std::move(finalPrintSettings)](
nsIContentAnalysisResponse* aResponse)
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA mutable {
bool shouldAllow = false;
DebugOnly<nsresult> rv =
aResponse->GetShouldAllowContent(
&shouldAllow);
MOZ_ASSERT(NS_SUCCEEDED(rv));
promise->Resolve(
PrintAllowedResult(
shouldAllow, cachedStaticBrowsingContext),
__func__);
},
[promise,
cachedStaticBrowsingContext](nsresult aError) {
promise->Reject(
PrintAllowedError(aError,
cachedStaticBrowsingContext),
__func__);
});
nsCOMPtr<nsIContentAnalysis> contentAnalysis =
mozilla::components::nsIContentAnalysis::Service();
if (NS_WARN_IF(!contentAnalysis)) {
promise->Reject(
PrintAllowedError(rv, cachedStaticBrowsingContext),
__func__);
} else {
bool isActive = false;
nsresult rv = contentAnalysis->GetIsActive(&isActive);
// Should not be called if content analysis is not active
MOZ_ASSERT(isActive);
Unused << NS_WARN_IF(NS_FAILED(rv));
rv = contentAnalysis->AnalyzeContentRequestCallback(
contentAnalysisRequest, /* aAutoAcknowledge */ true,
callback);
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->Reject(
PrintAllowedError(rv, cachedStaticBrowsingContext),
__func__);
}
}
},
[promise](nsresult aError) {
promise->Reject(PrintAllowedError(aError), __func__);
});
return promise;
}
#endif
NS_IMPL_ISUPPORTS(ContentAnalysis::SafeContentAnalysisResultCallback,
nsIContentAnalysisCallback);
// - true means a content analysis request was fired
// - false means there is no text data in the transferable
// - NoContentAnalysisResult means there was an error
using ClipboardContentAnalysisResult =
mozilla::Result<bool, mozilla::contentanalysis::NoContentAnalysisResult>;
NS_IMETHODIMP ContentAnalysis::SafeContentAnalysisResultCallback::ContentResult(
nsIContentAnalysisResponse* aResponse) {
RefPtr<ContentAnalysisResult> result =
ContentAnalysisResult::FromContentAnalysisResponse(aResponse);
Callback(result);
return NS_OK;
}
NS_IMETHODIMP ContentAnalysis::SafeContentAnalysisResultCallback::Error(
nsresult aError) {
Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR));
return NS_OK;
}
ClipboardContentAnalysisResult CheckClipboardContentAnalysisAsText(
uint64_t aInnerWindowId,
ContentAnalysis::SafeContentAnalysisResultCallback* aResolver,
nsIURI* aDocumentURI, nsIContentAnalysis* aContentAnalysis,
nsITransferable* aTextTrans, const char* aFlavor) {
nsCOMPtr<nsISupports> transferData;
if (NS_FAILED(
aTextTrans->GetTransferData(aFlavor, getter_AddRefs(transferData)))) {
return false;
}
nsCOMPtr<nsISupportsString> textData = do_QueryInterface(transferData);
if (MOZ_UNLIKELY(!textData)) {
return false;
}
nsString text;
if (NS_FAILED(textData->GetData(text))) {
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
if (text.IsEmpty()) {
// Content Analysis doesn't expect to analyze an empty string.
// Just approve it.
return true;
}
RefPtr<mozilla::dom::WindowGlobalParent> window =
mozilla::dom::WindowGlobalParent::GetByInnerWindowId(aInnerWindowId);
if (!window) {
// The window has gone away in the meantime
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
nsCOMPtr<nsIContentAnalysisRequest> contentAnalysisRequest =
new ContentAnalysisRequest(
nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry,
std::move(text), false, EmptyCString(), aDocumentURI,
nsIContentAnalysisRequest::OperationType::eClipboard, window);
nsresult rv = aContentAnalysis->AnalyzeContentRequestCallback(
contentAnalysisRequest, /* aAutoAcknowledge */ true, aResolver);
if (NS_FAILED(rv)) {
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
return true;
}
ClipboardContentAnalysisResult CheckClipboardContentAnalysisAsFile(
uint64_t aInnerWindowId,
ContentAnalysis::SafeContentAnalysisResultCallback* aResolver,
nsIURI* aDocumentURI, nsIContentAnalysis* aContentAnalysis,
nsITransferable* aFileTrans) {
nsCOMPtr<nsISupports> transferData;
nsresult rv =
aFileTrans->GetTransferData(kFileMime, getter_AddRefs(transferData));
nsString filePath;
if (NS_SUCCEEDED(rv)) {
if (nsCOMPtr<nsIFile> file = do_QueryInterface(transferData)) {
rv = file->GetPath(filePath);
} else {
MOZ_ASSERT_UNREACHABLE("clipboard data had kFileMime but no nsIFile!");
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
}
if (NS_FAILED(rv) || filePath.IsEmpty()) {
return false;
}
RefPtr<mozilla::dom::WindowGlobalParent> window =
mozilla::dom::WindowGlobalParent::GetByInnerWindowId(aInnerWindowId);
if (!window) {
// The window has gone away in the meantime
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
// Let the content analysis code calculate the digest
nsCOMPtr<nsIContentAnalysisRequest> contentAnalysisRequest =
new ContentAnalysisRequest(
nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry,
std::move(filePath), true, EmptyCString(), aDocumentURI,
nsIContentAnalysisRequest::OperationType::eCustomDisplayString,
window);
rv = aContentAnalysis->AnalyzeContentRequestCallback(
contentAnalysisRequest,
/* aAutoAcknowledge */ true, aResolver);
if (NS_FAILED(rv)) {
return mozilla::Err(NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR);
}
return true;
}
void ContentAnalysis::CheckClipboardContentAnalysis(
nsBaseClipboard* aClipboard, mozilla::dom::WindowGlobalParent* aWindow,
nsITransferable* aTransferable, int32_t aClipboardType,
SafeContentAnalysisResultCallback* aResolver) {
using namespace mozilla::contentanalysis;
// Content analysis is only needed if an outside webpage has access to
// the data. So, skip content analysis if there is:
// - no associated window (for example, scripted clipboard read by system
// code)
// - the window is a chrome docshell
// - the window is being rendered in the parent process (for example,
// about:support and the like)
if (!aWindow || aWindow->GetBrowsingContext()->IsChrome() ||
aWindow->IsInProcess()) {
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::
ALLOW_DUE_TO_CONTEXT_EXEMPT_FROM_CONTENT_ANALYSIS));
return;
}
nsCOMPtr<nsIContentAnalysis> contentAnalysis =
mozilla::components::nsIContentAnalysis::Service();
if (!contentAnalysis) {
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR));
return;
}
bool contentAnalysisIsActive;
nsresult rv = contentAnalysis->GetIsActive(&contentAnalysisIsActive);
if (MOZ_LIKELY(NS_FAILED(rv) || !contentAnalysisIsActive)) {
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::ALLOW_DUE_TO_CONTENT_ANALYSIS_NOT_ACTIVE));
return;
}
uint64_t innerWindowId = aWindow->InnerWindowId();
if (mozilla::StaticPrefs::
browser_contentanalysis_bypass_for_same_tab_operations()) {
mozilla::Maybe<uint64_t> cacheInnerWindowId =
aClipboard->GetClipboardCacheInnerWindowId(aClipboardType);
if (cacheInnerWindowId.isSome() && *cacheInnerWindowId == innerWindowId) {
// If the same page copied this data to the clipboard (and the above
// preference is set) we can skip content analysis and immediately allow
// this.
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::ALLOW_DUE_TO_SAME_TAB_SOURCE));
return;
}
}
nsCOMPtr<nsIURI> currentURI = aWindow->Canonical()->GetDocumentURI();
nsTArray<nsCString> flavors;
rv = aTransferable->FlavorsTransferableCanExport(flavors);
if (NS_WARN_IF(NS_FAILED(rv))) {
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::DENY_DUE_TO_OTHER_ERROR));
return;
}
bool keepChecking = true;
if (flavors.Contains(kFileMime)) {
auto fileResult = CheckClipboardContentAnalysisAsFile(
innerWindowId, aResolver, currentURI, contentAnalysis, aTransferable);
if (fileResult.isErr()) {
aResolver->Callback(
ContentAnalysisResult::FromNoResult(fileResult.unwrapErr()));
return;
}
keepChecking = !fileResult.unwrap();
}
if (keepChecking) {
// Failed to get the clipboard data as a file, so try as text
auto textResult = CheckClipboardContentAnalysisAsText(
innerWindowId, aResolver, currentURI, contentAnalysis, aTransferable,
kTextMime);
if (textResult.isErr()) {
aResolver->Callback(
ContentAnalysisResult::FromNoResult(textResult.unwrapErr()));
return;
}
keepChecking = !textResult.unwrap();
}
if (keepChecking) {
// Failed to get the clipboard data as a file or text, so try as html
auto htmlResult = CheckClipboardContentAnalysisAsText(
innerWindowId, aResolver, currentURI, contentAnalysis, aTransferable,
kHTMLMime);
if (htmlResult.isErr()) {
aResolver->Callback(
ContentAnalysisResult::FromNoResult(htmlResult.unwrapErr()));
return;
}
if (!htmlResult.unwrap()) {
// Couldn't get file or text or html data from this
aResolver->Callback(ContentAnalysisResult::FromNoResult(
NoContentAnalysisResult::ALLOW_DUE_TO_COULD_NOT_GET_DATA));
return;
}
}
}
bool ContentAnalysis::CheckClipboardContentAnalysisSync(
nsBaseClipboard* aClipboard, mozilla::dom::WindowGlobalParent* aWindow,
const nsCOMPtr<nsITransferable>& trans, int32_t aClipboardType) {
bool requestDone = false;
RefPtr<nsIContentAnalysisResult> result;
auto callback = mozilla::MakeRefPtr<SafeContentAnalysisResultCallback>(
[&requestDone, &result](RefPtr<nsIContentAnalysisResult>&& aResult) {
result = std::move(aResult);
requestDone = true;
});
CheckClipboardContentAnalysis(aClipboard, aWindow, trans, aClipboardType,
callback);
mozilla::SpinEventLoopUntil("CheckClipboardContentAnalysisSync"_ns,
[&requestDone]() -> bool { return requestDone; });
return result->GetShouldAllowContent();
}
NS_IMETHODIMP
ContentAnalysisResponse::Acknowledge(
nsIContentAnalysisAcknowledgement* aAcknowledgement) {
MOZ_ASSERT(mOwner);
if (mHasAcknowledged) {
MOZ_ASSERT(false, "Already acknowledged this ContentAnalysisResponse!");
return NS_ERROR_FAILURE;
}
mHasAcknowledged = true;
if (mDoNotAcknowledge) {
return NS_OK;
}
return mOwner->RunAcknowledgeTask(aAcknowledgement, mRequestToken);
};
nsresult ContentAnalysis::RunAcknowledgeTask(
nsIContentAnalysisAcknowledgement* aAcknowledgement,
const nsACString& aRequestToken) {
bool isActive;
nsresult rv = GetIsActive(&isActive);
NS_ENSURE_SUCCESS(rv, rv);
if (!isActive) {
return NS_ERROR_NOT_AVAILABLE;
}
content_analysis::sdk::ContentAnalysisAcknowledgement pbAck;
rv = ConvertToProtobuf(aAcknowledgement, aRequestToken, &pbAck);
NS_ENSURE_SUCCESS(rv, rv);
LOGD("Issuing ContentAnalysisAcknowledgement");
LogAcknowledgement(&pbAck);
// The content analysis connection is synchronous so run in the background.
LOGD("RunAcknowledgeTask dispatching acknowledge task");
mCaClientPromise->Then(
GetCurrentSerialEventTarget(), __func__,
[pbAck = std::move(pbAck)](
std::shared_ptr<content_analysis::sdk::Client> client) mutable {
NS_DispatchBackgroundTask(
NS_NewCancelableRunnableFunction(
__func__,
[pbAck = std::move(pbAck),
client = std::move(client)]() mutable {
RefPtr<ContentAnalysis> owner =
GetContentAnalysisFromService();
if (!owner) {
// May be shutting down
return;
}
if (!client) {
return;
}
int err = client->Acknowledge(pbAck);
MOZ_ASSERT(err == 0);
LOGD(
"RunAcknowledgeTask sent transaction acknowledgement, "
"err=%d",
err);
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
},
[](nsresult rv) { LOGD("RunAcknowledgeTask failed to get the client"); });
return rv;
}
bool ContentAnalysis::LastRequestSucceeded() {
return mLastResult != NS_ERROR_NOT_AVAILABLE &&
mLastResult != NS_ERROR_INVALID_SIGNATURE &&
mLastResult != NS_ERROR_FAILURE;
}
NS_IMETHODIMP
ContentAnalysis::GetDiagnosticInfo(JSContext* aCx,
mozilla::dom::Promise** aPromise) {
RefPtr<mozilla::dom::Promise> promise;
nsresult rv = MakePromise(aCx, &promise);
NS_ENSURE_SUCCESS(rv, rv);
mCaClientPromise->Then(
GetCurrentSerialEventTarget(), __func__,
[promise](std::shared_ptr<content_analysis::sdk::Client> client) mutable {
if (!client) {
auto info = MakeRefPtr<ContentAnalysisDiagnosticInfo>(
false, EmptyString(), false, 0);
promise->MaybeResolve(info);
return;
}
RefPtr<ContentAnalysis> self = GetContentAnalysisFromService();
std::string agentPath = client->GetAgentInfo().binary_path;
nsString agentWidePath = NS_ConvertUTF8toUTF16(agentPath);
auto info = MakeRefPtr<ContentAnalysisDiagnosticInfo>(
self->LastRequestSucceeded(), std::move(agentWidePath), false,
self ? self->mRequestCount : 0);
promise->MaybeResolve(info);
},
[promise](nsresult rv) {
RefPtr<ContentAnalysis> self = GetContentAnalysisFromService();
auto info = MakeRefPtr<ContentAnalysisDiagnosticInfo>(
false, EmptyString(), rv == NS_ERROR_INVALID_SIGNATURE,
self ? self->mRequestCount : 0);
promise->MaybeResolve(info);
});
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisCallback::ContentResult(
nsIContentAnalysisResponse* aResponse) {
if (mPromise.isSome()) {
mPromise->get()->MaybeResolve(aResponse);
} else {
mContentResponseCallback(aResponse);
}
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisCallback::Error(nsresult aError) {
if (mPromise.isSome()) {
mPromise->get()->MaybeReject(aError);
} else {
mErrorCallback(aError);
}
return NS_OK;
}
ContentAnalysisCallback::ContentAnalysisCallback(RefPtr<dom::Promise> aPromise)
: mPromise(Some(new nsMainThreadPtrHolder<dom::Promise>(
"content analysis promise", aPromise))) {}
NS_IMETHODIMP ContentAnalysisDiagnosticInfo::GetConnectedToAgent(
bool* aConnectedToAgent) {
*aConnectedToAgent = mConnectedToAgent;
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisDiagnosticInfo::GetAgentPath(
nsAString& aAgentPath) {
aAgentPath = mAgentPath;
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisDiagnosticInfo::GetFailedSignatureVerification(
bool* aFailedSignatureVerification) {
*aFailedSignatureVerification = mFailedSignatureVerification;
return NS_OK;
}
NS_IMETHODIMP ContentAnalysisDiagnosticInfo::GetRequestCount(
int64_t* aRequestCount) {
*aRequestCount = mRequestCount;
return NS_OK;
}
#undef LOGD
#undef LOGE
} // namespace mozilla::contentanalysis
|