/
requestpolicyService.js
2277 lines (2003 loc) · 86.8 KB
/
requestpolicyService.js
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
/*
* ***** BEGIN LICENSE BLOCK *****
*
* RequestPolicy - A Firefox extension for control over cross-site requests.
* Copyright (c) 2008-2009 Justin Samuel
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* ***** END LICENSE BLOCK *****
*/
const CI = Components.interfaces;
const CC = Components.classes;
const CP_OK = CI.nsIContentPolicy.ACCEPT;
const CP_NOP = function() {
return CP_OK;
};
const CP_REJECT = CI.nsIContentPolicy.REJECT_SERVER;
const EXTENSION_ID = "requestpolicy@requestpolicy.com";
// A value intended to not conflict with aExtra passed to shouldLoad() by any
// other callers. Was chosen randomly.
const CP_MAPPEDDESTINATION = 0x178c40bf;
const HTTPS_EVERYWHERE_REWRITE_TOPIC = "https-everywhere-uri-rewrite";
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
// Scope for imported modules.
if (!requestpolicy) {
var requestpolicy = {
mod : {}
};
}
function RequestPolicyService() {
this.wrappedJSObject = this;
}
RequestPolicyService.prototype = {
classDescription : "RequestPolicy JavaScript XPCOM Component",
classID : Components.ID("{14027e96-1afb-4066-8846-e6c89b5faf3b}"),
contractID : "@requestpolicy.com/requestpolicy-service;1",
_xpcom_categories : [{
category : "profile-after-change"
}, {
category : "content-policy"
}],
QueryInterface : XPCOMUtils.generateQI([CI.nsIRequestPolicy, CI.nsIObserver,
CI.nsIContentPolicy]),
/* Factory that creates a singleton instance of the component */
_xpcom_factory : {
createInstance : function() {
if (RequestPolicyService.instance == null) {
RequestPolicyService.instance = new RequestPolicyService();
}
return RequestPolicyService.instance;
}
},
// /////////////////////////////////////////////////////////////////////////
// Internal Data
// /////////////////////////////////////////////////////////////////////////
_initialized : false,
_profileAfterChangeCompleted : false,
_blockingDisabled : false,
_conflictingExtensions : [],
_rejectedRequests : {},
_allowedRequests : {},
/**
* These are redirects that the user allowed when presented with a redirect
* notification.
*/
_userAllowedRedirects : {},
_blockedRedirects : {},
_allowedRedirectsReverse : {},
_prefService : null,
_rootPrefs : null,
_historyRequests : {},
_submittedForms : {},
_submittedFormsReverse : {},
_clickedLinks : {},
_clickedLinksReverse : {},
_faviconRequests : {},
_mappedDestinations : {},
_requestObservers : [],
_uriIdentificationLevel : 0,
/**
* Number of elapsed milliseconds from the time of the last shouldLoad() call
* at which the cached results of the last shouldLoad() call are discarded.
*
* @type Number
*/
_lastShouldLoadCheckTimeout : 200,
// Calls to shouldLoad appear to be repeated, so successive repeated calls and
// their result (accept or reject) are tracked to avoid duplicate processing
// and duplicate logging.
/**
* Object that caches the last shouldLoad
*/
_lastShouldLoadCheck : {
"origin" : null,
"destination" : null,
"time" : 0,
"result" : null
},
_temporarilyAllowedOriginsCount : 0,
_temporarilyAllowedDestinationsCount : 0,
_temporarilyAllowedOriginsToDestinationsCount : 0,
_temporarilyAllowedOrigins : {},
_temporarilyAllowedDestinations : {},
_temporarilyAllowedOriginsToDestinations : {},
_allowedOrigins : {},
_allowedDestinations : {},
_allowedOriginsToDestinations : {},
_prefNameToObjectMap : null,
_compatibilityRules : [],
_topLevelDocTranslationRules : [],
_privateBrowsingEnabled : false,
_uninstall : false,
// /////////////////////////////////////////////////////////////////////////
// Utility
// /////////////////////////////////////////////////////////////////////////
_init : function() {
if (this._initialized) {
return;
}
this._initialized = true;
this._loadLibraries();
this._initContentPolicy();
this._register();
this._initializePrefSystem();
this._initializePrivateBrowsing();
// Note that we don't load user preferences at this point because the user
// preferences may not be ready. If we tried right now, we may get the
// default preferences.
},
_checkForLegacyRP : function () {
function addonCallback(addon) {
if (addon === null) {
// RP is not installed
return;
}
if (addon.isActive === false) {
// RP is disabled
return;
}
const url = "chrome://rpcontinued/content/rp-and-rpc.html";
var wm = CC["@mozilla.org/appshell/window-mediator;1"]
.getService(CI.nsIWindowMediator);
var mostRecentWindow = wm.getMostRecentWindow("navigator:browser");
// the gBrowser object of the firefox window
var _gBrowser = mostRecentWindow.getBrowser();
if (typeof(_gBrowser.addTab) !== "function") {
return;
}
_gBrowser.selectedTab = _gBrowser.addTab(url);
}
AddonManager.getAddonByID("requestpolicy@requestpolicy.com",
addonCallback);
},
_initializeExtensionCompatibility : function() {
if (this._compatibilityRules.length != 0) {
return;
}
var idArray = [];
idArray.push("greasefire@skrul.com"); // GreaseFire
idArray.push("{0f9daf7e-2ee2-4fcf-9d4f-d43d93963420}"); // Sage-Too
idArray.push("{899DF1F8-2F43-4394-8315-37F6744E6319}"); // NewsFox
idArray.push("brief@mozdev.org"); // Brief
idArray.push("foxmarks@kei.com"); // Xmarks Sync (a.k.a. Foxmarks)
// Norton Safe Web Lite Toolbar
idArray.push("{203FB6B2-2E1E-4474-863B-4C483ECCE78E}");
// Norton Toolbar (a.k.a. NIS Toolbar)
idArray.push("{0C55C096-0F1D-4F28-AAA2-85EF591126E7}");
// Norton Toolbar 2011.7.0.8
idArray.push("{2D3F3651-74B9-4795-BDEC-6DA2F431CB62}");
idArray.push("{c45c406e-ab73-11d8-be73-000a95be3b12}"); // Web Developer
idArray.push("{c07d1a49-9894-49ff-a594-38960ede8fb9}"); // Update Scanner
idArray.push("FirefoxAddon@similarWeb.com"); // SimilarWeb
idArray.push("{6614d11d-d21d-b211-ae23-815234e1ebb5}"); // Dr. Web Link Checker
const rpService = this;
var callback = function(ext) {
rpService._initializeExtCompatCallback(ext)
};
for (var i = 0; i < idArray.length; i++) {
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Extension new-style check: " + idArray[i]);
AddonManager.getAddonByID(idArray[i], callback);
}
},
_initializeExtCompatCallback : function(ext) {
if (!ext) {
return;
}
if (ext.isActive == false) {
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Extension is not active: " + ext.name);
return;
}
switch (ext.id) {
case "greasefire@skrul.com" : // Greasefire
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push(["file://", "http://userscripts.org/",
ext.name]);
this._compatibilityRules.push(["file://",
"http://static.userscripts.org/", ext.name]);
break;
case "{0f9daf7e-2ee2-4fcf-9d4f-d43d93963420}" : // Sage-Too
case "{899DF1F8-2F43-4394-8315-37F6744E6319}" : // NewsFox
case "brief@mozdev.org" : // Brief
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Conflicting extension: " + ext.name);
this._compatibilityRules.push(["resource://brief-content/", null,
ext.name]);
this._conflictingExtensions.push({
"id" : ext.id,
"name" : ext.name,
"version" : ext.version
});
break;
case "foxmarks@kei.com" : // Xmarks Sync
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push(["https://login.xmarks.com/",
"https://static.xmarks.com/", ext.name]);
break;
case "{203FB6B2-2E1E-4474-863B-4C483ECCE78E}" : // Norton Safe Web Lite
case "{0C55C096-0F1D-4F28-AAA2-85EF591126E7}" : // Norton NIS Toolbar
case "{2D3F3651-74B9-4795-BDEC-6DA2F431CB62}" : // Norton Toolbar
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push([null, "symnst:", ext.name]);
this._compatibilityRules.push([null, "symres:", ext.name]);
break;
case "{c45c406e-ab73-11d8-be73-000a95be3b12}" : // Web Developer
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push(["about:blank",
"http://jigsaw.w3.org/css-validator/validator", ext.name]);
this._compatibilityRules.push(["about:blank",
"http://validator.w3.org/check", ext.name]);
break;
case "{c07d1a49-9894-49ff-a594-38960ede8fb9}" : // Update Scanner
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
var orig = "chrome://updatescan/content/diffPage.xul";
var translated = "data:text/html";
this._topLevelDocTranslationRules.push([orig, translated]);
break;
case "FirefoxAddon@similarWeb.com" : // SimilarWeb
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push(["http://api2.similarsites.com/",
"http://images2.similargroup.com/", ext.name]);
this._compatibilityRules.push(["http://www.similarweb.com/",
"http://go.similarsites.com/", ext.name]);
break;
case "{6614d11d-d21d-b211-ae23-815234e1ebb5}" : // Dr. Web Link Checker
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Using extension compatibility rules for: " + ext.name);
this._compatibilityRules.push([null, "http://st.drweb.com/", ext.name]);
break;
default :
requestpolicy.mod.Logger.severe(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Unhandled extension (id typo?): " + ext.name);
break;
}
},
_initializeApplicationCompatibility : function() {
var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
.getService(Components.interfaces.nsIXULAppInfo);
// Mozilla updates (doing this for all applications, not just individual
// applications from the Mozilla community that I'm aware of).
// At least the http url is needed for Firefox updates, adding the https
// one as well to be safe.
this._compatibilityRules.push(["http://download.mozilla.org/", null,
appInfo.vendor]);
this._compatibilityRules.push(["https://download.mozilla.org/", null,
appInfo.vendor]);
// There are redirects from 'addons' to 'releases' when installing addons
// from AMO. Adding the origin of 'releases' to be safe in case those
// start redirecting elsewhere at some point.
this._compatibilityRules.push(["http://addons.mozilla.org/", null,
appInfo.vendor]);
this._compatibilityRules.push(["https://addons.mozilla.org/", null,
appInfo.vendor]);
this._compatibilityRules.push(["http://releases.mozilla.org/", null,
appInfo.vendor]);
this._compatibilityRules.push(["https://releases.mozilla.org/", null,
appInfo.vendor]);
// Firefox 4 has the about:addons page open an iframe to the mozilla site.
// That opened page grabs content from other mozilla domains.
this._compatibilityRules.push(["about:addons",
"https://services.addons.mozilla.org/", appInfo.vendor]);
this._compatibilityRules.push(["https://services.addons.mozilla.org/",
"https://static.addons.mozilla.net/", appInfo.vendor]);
this._compatibilityRules.push(["https://services.addons.mozilla.org/",
"https://addons.mozilla.org/", appInfo.vendor]);
this._compatibilityRules.push(["https://services.addons.mozilla.org/",
"https://www.mozilla.com/", appInfo.vendor]);
this._compatibilityRules.push(["https://services.addons.mozilla.org/",
"https://www.getpersonas.com/", appInfo.vendor]);
this._compatibilityRules.push(["https://services.addons.mozilla.org/",
"https://static-cdn.addons.mozilla.net/", appInfo.vendor]);
// Firefox 4 uses an about:home page that is locally stored but can be
// the origin for remote requests. See bug #140 for more info.
this._compatibilityRules.push(["about:home", null, appInfo.vendor]);
// Firefox Sync uses a google captcha.
this._compatibilityRules.push(["https://auth.services.mozilla.com/",
"https://api-secure.recaptcha.net/challenge?", appInfo.vendor]);
this._compatibilityRules.push([
"https://api-secure.recaptcha.net/challenge?",
"https://www.google.com/recaptcha/api/challenge?", appInfo.vendor]);
this._compatibilityRules.push(["https://auth.services.mozilla.com/",
"https://www.google.com/recaptcha/api/", appInfo.vendor]);
// Firefox 13 added links from about:newtab
this._compatibilityRules.push(["about:newtab", null, appInfo.vendor]);
// Flock
if (appInfo.ID == "{a463f10c-3994-11da-9945-000d60ca027b}") {
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Application detected: " + appInfo.vendor);
this._compatibilityRules.push(["about:myworld", "http://www.flock.com/",
appInfo.vendor]);
this._compatibilityRules.push(["about:flock", null, appInfo.vendor]);
this._compatibilityRules.push(["http://www.flock.com/rss",
"http://feeds.feedburner.com/flock", appInfo.vendor]);
this._compatibilityRules.push(["http://feeds.feedburner.com/",
"http://www.flock.com/", appInfo.vendor]);
}
// Seamonkey
if (appInfo.ID == "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}") {
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Application detected: Seamonkey");
this._compatibilityRules.push(["mailbox:", null, "Seamonkey"]);
this._compatibilityRules.push([null, "mailbox:", "Seamonkey"]);
}
},
_clearPref: function(name) {
if (this.prefs.prefHasUserValue(name)) {
this.prefs.clearUserPref(name);
}
},
_syncFromPrefs : function() {
// Load the logging preferences before the others.
this._updateLoggingSettings();
this._uriIdentificationLevel = this.prefs
.getIntPref("uriIdentificationLevel");
// origins
this._allowedOrigins = this._getPreferenceObj("allowedOrigins");
requestpolicy.mod.Logger.vardump(this._allowedOrigins,
"this._allowedOrigins");
// destinations
this._allowedDestinations = this._getPreferenceObj("allowedDestinations");
requestpolicy.mod.Logger.vardump(this._allowedDestinations,
"this._allowedDestinations");
// origins to destinations
this._allowedOriginsToDestinations = this
._getPreferenceObj("allowedOriginsToDestinations");
requestpolicy.mod.Logger.vardump(this._allowedOriginsToDestinations,
"this._allowedOriginsToDestinations");
this._prefNameToObjectMap = {
"allowedOrigins" : this._allowedOrigins,
"allowedDestinations" : this._allowedDestinations,
"allowedOriginsToDestinations" : this._allowedOriginsToDestinations
};
this._blockingDisabled = this.prefs.getBoolPref("startWithAllowAllEnabled");
// Disable link prefetch.
if (this.prefs.getBoolPref("prefetch.link.disableOnStartup")) {
if (this._rootPrefs.getBoolPref("network.prefetch-next")) {
this._rootPrefs.setBoolPref("network.prefetch-next", false);
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Disabled link prefetch.");
}
}
// Disable DNS prefetch.
if (this.prefs.getBoolPref("prefetch.dns.disableOnStartup")) {
// network.dns.disablePrefetch only exists starting in Firefox 3.1 (and it
// doesn't have a default value, at least in 3.1b2, but if and when it
// does have a default it will be false).
if (!this._rootPrefs.prefHasUserValue("network.dns.disablePrefetch") ||
!this._rootPrefs.getBoolPref("network.dns.disablePrefetch")) {
this._rootPrefs.setBoolPref("network.dns.disablePrefetch", true);
requestpolicy.mod.Logger.info(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Disabled DNS prefetch.");
}
}
// Study is over.
if (this.prefs.getBoolPref('study.participate')) {
this.endParticipationInStudy();
}
this._clearPref('study.participate');
this._clearPref('study.profileID');
this._clearPref('study.consentID');
this._clearPref('study.consentVersion');
this._clearPref('study.sessionID');
this._clearPref('study.globalEventID');
this._prefService.savePrefFile(null);
// Clean up old, unused prefs (removed in 0.2.0).
this._clearPref("temporarilyAllowedOrigins");
this._clearPref("temporarilyAllowedDestinations");
this._clearPref("temporarilyAllowedOriginsToDestinations");
this._prefService.savePrefFile(null);
},
endParticipationInStudy : function() {
this.prefs.setBoolPref('study.participate', false);
this._clearPref('study.consentVersion');
this._prefService.savePrefFile(null);
requestpolicy.mod.Stats.deleteFile();
},
_updateLoggingSettings : function() {
requestpolicy.mod.Logger.enabled = this.prefs.getBoolPref("log");
requestpolicy.mod.Logger.level = this.prefs.getIntPref("log.level");
requestpolicy.mod.Logger.types = this.prefs.getIntPref("log.types");
},
_registerAddonListener : function() {
const rpService = this;
var addonListener = {
onDisabling : function(addon, needsRestart) {
if (addon.id != EXTENSION_ID) {
return;
}
requestpolicy.mod.Logger.debug(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Addon set to be disabled.");
rpService._uninstall = true;
},
onUninstalling : function(addon, needsRestart) {
if (addon.id != EXTENSION_ID) {
return;
}
requestpolicy.mod.Logger.debug(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Addon set to be uninstalled.");
rpService._uninstall = true;
},
onOperationCancelled : function(addon, needsRestart) {
if (addon.id != EXTENSION_ID) {
return;
}
requestpolicy.mod.Logger.debug(requestpolicy.mod.Logger.TYPE_INTERNAL,
"Addon operation cancelled.");
// Just because an operation was cancelled doesn't mean there isn't
// a pending operation we care about. For example, a user can choose
// disable and then uninstall, then clicking "undo" once will cancel
// the uninstall but not the disable.
var pending = addon.pendingOperations &
(AddonManager.PENDING_DISABLE | AddonManager.PENDING_UNINSTALL);
if (!pending) {
requestpolicy.mod.Logger.debug(requestpolicy.mod.Logger.TYPE_INTERNAL,
"No pending uninstall or disable.");
rpService._uninstall = false;
}
}
};
AddonManager.addAddonListener(addonListener);
},
_register : function() {
var os = CC['@mozilla.org/observer-service;1']
.getService(CI.nsIObserverService);
os.addObserver(this, "http-on-examine-response", false);
os.addObserver(this, "http-on-modify-request", false);
os.addObserver(this, "xpcom-shutdown", false);
os.addObserver(this, "profile-after-change", false);
os.addObserver(this, "sessionstore-windows-restored", false);
os.addObserver(this, "quit-application", false);
os.addObserver(this, "private-browsing", false);
os.addObserver(this, HTTPS_EVERYWHERE_REWRITE_TOPIC, false);
this._registerAddonListener();
},
_unregister : function() {
try {
var os = CC['@mozilla.org/observer-service;1']
.getService(CI.nsIObserverService);
os.removeObserver(this, "http-on-examine-response");
os.removeObserver(this, "http-on-modify-request");
os.removeObserver(this, "xpcom-shutdown");
os.removeObserver(this, "profile-after-change");
os.removeObserver(this, "sessionstore-windows-restored");
os.removeObserver(this, "quit-application");
} catch (e) {
requestpolicy.mod.Logger.dump(e + " while unregistering.");
}
},
_shutdown : function() {
this._unregister();
},
_initializePrefSystem : function() {
// Get the preferences branch and setup the preferences observer.
this._prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
this.prefs = this._prefService.getBranch("extensions.requestpolicy.")
.QueryInterface(CI.nsIPrefBranch2);
this.prefs.addObserver("", this, false);
this._rootPrefs = this._prefService.getBranch("")
.QueryInterface(CI.nsIPrefBranch2);
},
_initVersionInfo : function() {
try {
const util = requestpolicy.mod.Util;
// Set the last version values in the Util module based on the prefs.
util.lastVersion = this.prefs.getCharPref("lastVersion");
util.lastAppVersion = this.prefs.getCharPref("lastAppVersion");
// Now update the last version prefs and set current version values.
util.initCurAppVersion();
this.prefs.setCharPref("lastAppVersion", util.curAppVersion);
var versionChanged = false;
const usePrefs = this.prefs;
const prefService = this._prefService;
AddonManager.getAddonByID(EXTENSION_ID, function(addon) {
usePrefs.setCharPref("lastVersion", addon.version);
util.curVersion = addon.version;
if (util.lastVersion != util.curVersion) {
prefService.savePrefFile(null);
}
});
if (versionChanged || util.lastAppVersion != util.curAppVersion) {
this._prefService.savePrefFile(null);
}
} catch (e) {
requestpolicy.mod.Logger.error(requestpolicy.mod.Logger.TYPE_INTERNAL,
"_initVersionInfo failed: " + e);
}
},
/**
* Take necessary actions when preferences are updated.
*
* @paramString{} prefName NAme of the preference that was updated.
*/
_updatePref : function(prefName) {
switch (prefName) {
case "log" :
case "log.level" :
case "log.types" :
this._updateLoggingSettings();
break;
case "uriIdentificationLevel" :
this._uriIdentificationLevel = this.prefs
.getIntPref("uriIdentificationLevel");
break;
default :
break;
}
},
_loadLibraries : function() {
Components.utils.import("resource://requestpolicy/Logger.jsm",
requestpolicy.mod);
Components.utils.import("resource://requestpolicy/DomainUtil.jsm",
requestpolicy.mod);
Components.utils.import("resource://requestpolicy/Util.jsm",
requestpolicy.mod);
Components.utils.import("resource://requestpolicy/Stats.jsm",
requestpolicy.mod);
Components.utils.import("resource://gre/modules/AddonManager.jsm");
},
_initializePrivateBrowsing : function() {
try {
var pbs = Components.classes["@mozilla.org/privatebrowsing;1"]
.getService(Components.interfaces.nsIPrivateBrowsingService);
this._privateBrowsingEnabled = pbs.privateBrowsingEnabled;
} catch (e) {
// Ignore exceptions from browsers that do not support private browsing.
}
},
/**
* Checks whether a request is initiated by a content window. If it's from a
* content window, then it's from unprivileged code.
*/
_isContentRequest : function(channel) {
var callbacks = [];
if (channel.notificationCallbacks) {
callbacks.push(channel.notificationCallbacks);
}
if (channel.loadGroup && channel.loadGroup.notificationCallbacks) {
callbacks.push(channel.loadGroup.notificationCallbacks);
}
for (var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
try {
return callback.getInterface(CI.nsILoadContext).isContent;
} catch (e) {
}
}
return false;
},
_examineHttpResponse : function(observedSubject) {
// Currently, if a user clicks a link to download a file and that link
// redirects and is subsequently blocked, the user will see the blocked
// destination in the menu. However, after they have allowed it from
// the menu and attempted the download again, they won't see the allowed
// request in the menu. Fixing that might be a pain and also runs the
// risk of making the menu cluttered and confusing with destinations of
// followed links from the current page.
// TODO: Make user aware of blocked headers so they can allow them if
// desired.
var httpChannel = observedSubject
.QueryInterface(Components.interfaces.nsIHttpChannel);
var headerType;
var dest;
try {
// If there is no such header, getResponseHeader() will throw
// NS_ERROR_NOT_AVAILABLE. If there is more than header, the last one is
// the one that will be used.
headerType = "Location";
dest = httpChannel.getResponseHeader(headerType);
} catch (e) {
// No location header. Look for a Refresh header.
try {
headerType = "Refresh";
var refreshString = httpChannel.getResponseHeader(headerType);
} catch (e) {
// No Location header or Refresh header.
return;
}
try {
var parts = requestpolicy.mod.DomainUtil.parseRefresh(refreshString);
} catch (e) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"Invalid refresh header: <" + refreshString + ">");
if (!this._blockingDisabled) {
httpChannel.setResponseHeader(headerType, "", false);
}
return;
}
// We can ignore the delay (parts[0]) because we aren't manually doing
// the refreshes. Allowed refreshes we still leave to the browser.
// The dest may be empty if the origin is what should be refreshed. This
// will be handled by DomainUtil.determineRedirectUri().
dest = parts[1];
}
// For origins that are IDNs, this will always be in ACE format. We want
// it in UTF8 format if it's a TLD that Mozilla allows to be in UTF8.
var origin = requestpolicy.mod.DomainUtil.formatIDNUri(httpChannel.name);
// Allow redirects of requests from privileged code.
if (!this._isContentRequest(httpChannel)) {
// However, favicon requests that are redirected appear as non-content
// requests. So, check if the original request was for a favicon.
var originPath = requestpolicy.mod.DomainUtil.getPath(httpChannel.name);
// We always have to check "/favicon.ico" because Firefox will use this
// as a default path and that request won't pass through shouldLoad().
if (originPath == "/favicon.ico" || this._faviconRequests[origin]) {
// If the redirected request is allowed, we need to know that was a
// favicon request in case it is further redirected.
this._faviconRequests[dest] = true;
requestpolicy.mod.Logger.info(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT, "'" + headerType
+ "' header to <" + dest + "> " + "from <" + origin
+ "> appears to be a redirected favicon request. "
+ "This will be treated as a content request.");
} else {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT, "** ALLOWED ** '"
+ headerType + "' header to <" + dest + "> " + "from <"
+ origin + ">. Original request is from privileged code.");
return;
}
}
// If it's not a valid uri, the redirect is relative to the origin host.
// The way we have things written currently, without this check the full
// dest string will get treated as the destination and displayed in the
// menu because DomainUtil.getIdentifier() doesn't raise exceptions.
// We add this to fix https://www.requestpolicy.com/dev/ticket/39.
if (!requestpolicy.mod.DomainUtil.isValidUri(dest)) {
var destAsUri = requestpolicy.mod.DomainUtil.determineRedirectUri(origin,
dest);
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"Redirect destination is not a valid uri, assuming dest <" + dest
+ "> from origin <" + origin + "> is actually dest <" + destAsUri
+ ">.");
dest = destAsUri;
}
// Ignore redirects to javascript. The browser will ignore them, as well.
if (requestpolicy.mod.DomainUtil.getUriObject(dest)
.schemeIs("javascript")) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"Ignoring redirect to javascript URI <" + dest + ">");
return;
}
if (this.isAllowedRedirect(origin, dest)) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT, "** ALLOWED ** '"
+ headerType + "' header to <" + dest + "> " + "from <" + origin
+ ">. Same hosts or allowed origin/destination.");
this._recordAllowedRequest(origin, dest);
this._allowedRedirectsReverse[dest] = origin;
// If this was a link click or a form submission, we register an
// additional click/submit with the original source but with a new
// destination of the target of the redirect. This is because future
// requests (such as using back/forward) might show up as directly from
// the initial origin to the ultimate redirected destination.
if (httpChannel.referrer) {
var realOrigin = httpChannel.referrer.spec;
if (this._clickedLinks[realOrigin]
&& this._clickedLinks[realOrigin][origin]) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"This redirect was from a link click."
+ " Registering an additional click to <" + dest + "> "
+ "from <" + realOrigin + ">");
this.registerLinkClicked(realOrigin, dest);
} else if (this._submittedForms[realOrigin]
&& this._submittedForms[realOrigin][origin.split("?")[0]]) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"This redirect was from a form submission."
+ " Registering an additional form submission to <" + dest
+ "> " + "from <" + realOrigin + ">");
this.registerFormSubmitted(realOrigin, dest);
}
}
return;
}
// The header isn't allowed, so remove it.
try {
if (!this._blockingDisabled) {
httpChannel.setResponseHeader(headerType, "", false);
this._blockedRedirects[origin] = dest;
try {
contentDisp = httpChannel.getResponseHeader("Content-Disposition");
if (contentDisp.indexOf("attachment") != -1) {
try {
httpChannel.setResponseHeader("Content-Disposition", "", false);
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"Removed 'Content-Disposition: attachment' header to "
+ "prevent display of about:neterror.");
} catch (e) {
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT,
"Unable to remove 'Content-Disposition: attachment' header "
+ "to prevent display of about:neterror. " + e);
}
}
} catch (e) {
// No Content-Disposition header.
}
// We try to trace the blocked redirect back to a link click or form
// submission if we can. It may indicate, for example, a link that
// was to download a file but a redirect got blocked at some point.
var initialOrigin = origin;
var initialDest = dest;
// To prevent infinite loops, bound the number of iterations.
// Note that an apparent redirect loop doesn't mean a problem with a
// website as the site may be using other information, such as cookies
// that get set in the redirection process, to stop the redirection.
var iterations = 0;
const ASSUME_REDIRECT_LOOP = 100; // Chosen arbitrarily.
while (this._allowedRedirectsReverse[initialOrigin]) {
if (iterations++ >= ASSUME_REDIRECT_LOOP) {
break;
}
initialDest = initialOrigin;
initialOrigin = this._allowedRedirectsReverse[initialOrigin];
}
if (this._clickedLinksReverse[initialOrigin]) {
for (var i in this._clickedLinksReverse[initialOrigin]) {
// We hope there's only one possibility of a source page (that is,
// ideally there will be one iteration of this loop).
var sourcePage = i;
}
this._notifyRequestObserversOfBlockedLinkClickRedirect(sourcePage,
origin, dest);
// Maybe we just record the clicked link and each step in between as
// an allowed request, and the final blocked one as a blocked request.
// That is, make it show up in the requestpolicy menu like anything
// else.
// We set the "isInsert" parameter so we don't clobber the existing
// info about allowed and deleted requests.
this._recordAllowedRequest(sourcePage, initialOrigin, true);
}
// if (this._submittedFormsReverse[initialOrigin]) {
// // TODO: implement for form submissions whose redirects are blocked
// }
this._recordRejectedRequest(origin, dest);
}
requestpolicy.mod.Logger.warning(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT, "** BLOCKED ** '"
+ headerType + "' header to <" + dest + ">"
+ " found in response from <" + origin + ">");
} catch (e) {
requestpolicy.mod.Logger.severe(
requestpolicy.mod.Logger.TYPE_HEADER_REDIRECT, "Failed removing "
+ "'" + headerType + "' header to <" + dest + ">"
+ " in response from <" + origin + ">." + e);
}
},
/**
* Currently this just looks for prefetch requests that are getting through
* which we currently can't stop.
*/
_examineHttpRequest : function(observedSubject) {
var httpChannel = observedSubject
.QueryInterface(Components.interfaces.nsIHttpChannel);
try {
// Determine if prefetch requests are slipping through.
if (httpChannel.getRequestHeader("X-moz") == "prefetch") {
// Seems to be too late to block it at this point. Calling the
// cancel(status) method didn't stop it.
requestpolicy.mod.Logger.warning(requestpolicy.mod.Logger.TYPE_CONTENT,
"Discovered prefetch request being sent to: " + httpChannel.name);
}
} catch (e) {
// No X-moz header.
}
},
_printAllowedRequests : function() {
requestpolicy.mod.Logger
.dump("-------------------------------------------------");
requestpolicy.mod.Logger.dump("Allowed Requests");
for (i in this._allowedRequests) {
requestpolicy.mod.Logger.dump("\t" + "Origin uri: <" + i + ">");
for (var j in this._allowedRequests[i]) {
requestpolicy.mod.Logger.dump("\t\t" + "Dest identifier: <" + j + ">");
for (var k in this._allowedRequests[i][j]) {
if (k == "count") {
continue;
}
requestpolicy.mod.Logger.dump("\t\t\t" + k);
}
}
}
requestpolicy.mod.Logger
.dump("-------------------------------------------------");
},
_printRejectedRequests : function() {
requestpolicy.mod.Logger
.dump("-------------------------------------------------");
requestpolicy.mod.Logger.dump("Rejected Requests");
for (i in this._rejectedRequests) {
requestpolicy.mod.Logger.dump("\t" + "Origin uri: <" + i + ">");
for (var j in this._rejectedRequests[i]) {
requestpolicy.mod.Logger.dump("\t\t" + "Dest identifier: <" + j + ">");
for (var k in this._rejectedRequests[i][j]) {
if (k == "count") {
continue;
}
requestpolicy.mod.Logger.dump("\t\t\t" + k);
}
}
}
requestpolicy.mod.Logger
.dump("-------------------------------------------------");
},
_notifyRequestObserversOfBlockedRequest : function(originUri, destUri) {
for (var i = 0; i < this._requestObservers.length; i++) {
if (!this._requestObservers[i]) {
continue;
}
this._requestObservers[i].observeBlockedRequest(originUri, destUri);
}
},
_notifyRequestObserversOfAllowedRequest : function(originUri, destUri) {
for (var i = 0; i < this._requestObservers.length; i++) {
if (!this._requestObservers[i]) {
continue;
}
this._requestObservers[i].observeAllowedRequest(originUri, destUri);
}
},
_notifyRequestObserversOfBlockedLinkClickRedirect : function(sourcePageUri,
linkDestUri, blockedRedirectUri) {
for (var i = 0; i < this._requestObservers.length; i++) {
if (!this._requestObservers[i]) {
continue;
}
this._requestObservers[i].observeBlockedLinkClickRedirect(sourcePageUri,
linkDestUri, blockedRedirectUri);
}
},
_notifyBlockedTopLevelDocRequest : function(originUri, destUri) {
for (var i = 0; i < this._requestObservers.length; i++) {
if (!this._requestObservers[i]) {
continue;
}
this._requestObservers[i].observeBlockedTopLevelDocRequest(originUri,
destUri);
}
},
// /////////////////////////////////////////////////////////////////////////
// nsIRequestPolicy interface
// /////////////////////////////////////////////////////////////////////////