Policies.jsm 21.9 KB
Newer Older
1
2
3
4
5
6
/* 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/. */

"use strict";

7
8
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");
9
10
11
XPCOMUtils.defineLazyServiceGetter(this, "gXulStore",
                                   "@mozilla.org/xul/xulstore;1",
                                   "nsIXULStore");
12

13
14
XPCOMUtils.defineLazyModuleGetters(this, {
  BookmarksPolicies: "resource:///modules/policies/BookmarksPolicies.jsm",
15
  ProxyPolicies: "resource:///modules/policies/ProxyPolicies.jsm",
16
  AddonManager: "resource://gre/modules/AddonManager.jsm",
17
  CustomizableUI: "resource:///modules/CustomizableUI.jsm",
18
19
});

20
const PREF_LOGLEVEL           = "browser.policies.loglevel";
21
const BROWSER_DOCUMENT_URL    = "chrome://browser/content/browser.xul";
22
23

XPCOMUtils.defineLazyGetter(this, "log", () => {
24
  let { ConsoleAPI } = ChromeUtils.import("resource://gre/modules/Console.jsm", {});
25
26
27
28
29
30
31
32
33
  return new ConsoleAPI({
    prefix: "Policies.jsm",
    // tip: set maxLogLevel to "debug" and use log.debug() to create detailed
    // messages during development. See LOG_LEVELS in Console.jsm for details.
    maxLogLevel: "error",
    maxLogLevelPref: PREF_LOGLEVEL,
  });
});

34
var EXPORTED_SYMBOLS = ["Policies"];
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
/*
 * ============================
 * = POLICIES IMPLEMENTATIONS =
 * ============================
 *
 * The Policies object below is where the implementation for each policy
 * happens. An object for each policy should be defined, containing
 * callback functions that will be called by the engine.
 *
 * See the _callbacks object in EnterprisePolicies.js for the list of
 * possible callbacks and an explanation of each.
 *
 * Each callback will be called with two parameters:
 * - manager
 *   This is the EnterprisePoliciesManager singleton object from
 *   EnterprisePolicies.js
 *
 * - param
 *   The parameter defined for this policy in policies-schema.json.
 *   It will be different for each policy. It could be a boolean,
 *   a string, an array or a complex object. All parameters have
 *   been validated according to the schema, and no unknown
 *   properties will be present on them.
 *
 * The callbacks will be bound to their parent policy object.
 */
62
var Policies = {
63
64
65
66
67
68
69
70
  "BlockAboutAddons": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("about:addons", true);
      }
    }
  },

71
  "BlockAboutConfig": {
72
    onBeforeUIStartup(manager, param) {
73
      if (param) {
74
        manager.disallowFeature("about:config", true);
75
        setAndLockPref("devtools.chrome.enabled", false);
76
77
78
      }
    }
  },
79

80
81
82
83
84
85
86
87
  "BlockAboutProfiles": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("about:profiles", true);
      }
    }
  },

88
89
90
91
92
93
94
95
  "BlockAboutSupport": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("about:support", true);
      }
    }
  },

96
  "BlockSetDesktopBackground": {
97
    onBeforeUIStartup(manager, param) {
98
      if (param) {
99
        manager.disallowFeature("setDesktopBackground", true);
100
101
102
103
      }
    }
  },

104
105
106
107
108
109
  "Bookmarks": {
    onAllWindowsRestored(manager, param) {
      BookmarksPolicies.processBookmarks(param);
    }
  },

110
  "Cookies": {
111
    onBeforeUIStartup(manager, param) {
112
      addAllowDenyPermissions("cookie", param.Allow, param.Block);
113
114
115
116
117
118
119
120
121

      if (param.Block) {
        const hosts = param.Block.map(uri => uri.host).sort().join("\n");
        runOncePerModification("clearCookiesForBlockedHosts", hosts, () => {
          for (let blocked of param.Block) {
            Services.cookies.removeCookiesWithOriginAttributes("{}", blocked.host);
          }
        });
      }
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

      if (param.Default !== undefined ||
          param.AcceptThirdParty !== undefined ||
          param.Locked) {
        const ACCEPT_COOKIES = 0;
        const REJECT_THIRD_PARTY_COOKIES = 1;
        const REJECT_ALL_COOKIES = 2;
        const REJECT_UNVISITED_THIRD_PARTY = 3;

        let newCookieBehavior = ACCEPT_COOKIES;
        if (param.Default !== undefined && !param.Default) {
          newCookieBehavior = REJECT_ALL_COOKIES;
        } else if (param.AcceptThirdParty) {
          if (param.AcceptThirdParty == "none") {
            newCookieBehavior = REJECT_THIRD_PARTY_COOKIES;
          } else if (param.AcceptThirdParty == "from-visited") {
            newCookieBehavior = REJECT_UNVISITED_THIRD_PARTY;
          }
        }

        if (param.Locked) {
          setAndLockPref("network.cookie.cookieBehavior", newCookieBehavior);
        } else {
          setDefaultPref("network.cookie.cookieBehavior", newCookieBehavior);
        }
      }

      const KEEP_COOKIES_UNTIL_EXPIRATION = 0;
      const KEEP_COOKIES_UNTIL_END_OF_SESSION = 2;

      if (param.ExpireAtSessionEnd !== undefined || param.Locked) {
        let newLifetimePolicy = KEEP_COOKIES_UNTIL_EXPIRATION;
        if (param.ExpireAtSessionEnd) {
          newLifetimePolicy = KEEP_COOKIES_UNTIL_END_OF_SESSION;
        }

        if (param.Locked) {
          setAndLockPref("network.cookie.lifetimePolicy", newLifetimePolicy);
        } else {
          setDefaultPref("network.cookie.lifetimePolicy", newLifetimePolicy);
        }
      }
164
165
166
    }
  },

167
  "CreateMasterPassword": {
168
    onBeforeUIStartup(manager, param) {
169
170
      if (!param) {
        manager.disallowFeature("createMasterPassword");
171
172
173
174
      }
    }
  },

175
176
177
178
  "DisableAppUpdate": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("appUpdate");
179
180
181
182
      }
    }
  },

183
184
185
186
187
188
189
190
  "DisableBuiltinPDFViewer": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("PDF.js");
      }
    }
  },

191
192
193
194
195
196
197
198
199
200
201
202
203
204
  "DisableDeveloperTools": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("devtools.policy.disabled", true);
        setAndLockPref("devtools.chrome.enabled", false);

        manager.disallowFeature("devtools");
        manager.disallowFeature("about:devtools");
        manager.disallowFeature("about:debugging");
        manager.disallowFeature("about:devtools-toolbox");
      }
    }
  },

205
206
207
208
209
210
211
212
  "DisableFeedbackCommands": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("feedbackCommands");
      }
    }
  },

213
214
215
216
217
218
219
220
  "DisableFirefoxAccounts": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("identity.fxaccounts.enabled", false);
      }
    }
  },

221
222
  "DisableFirefoxScreenshots": {
    onBeforeAddons(manager, param) {
223
      if (param) {
224
225
226
227
228
        setAndLockPref("extensions.screenshots.disabled", true);
      }
    }
  },

229
230
  "DisableFirefoxStudies": {
    onBeforeAddons(manager, param) {
231
      if (param) {
232
233
234
235
236
        manager.disallowFeature("Shield");
      }
    }
  },

237
238
  "DisableFormHistory": {
    onBeforeUIStartup(manager, param) {
239
      if (param) {
240
241
242
243
244
        setAndLockPref("browser.formfill.enable", false);
      }
    }
  },

245
246
247
248
249
250
251
252
  "DisablePocket": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("extensions.pocket.enabled", false);
      }
    }
  },

253
254
255
256
257
258
259
260
261
262
  "DisablePrivateBrowsing": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("privatebrowsing");
        manager.disallowFeature("about:privatebrowsing", true);
        setAndLockPref("browser.privatebrowsing.autostart", false);
      }
    }
  },

263
264
265
266
267
268
269
270
  "DisableSafeMode": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("safeMode");
      }
    }
  },

271
272
273
274
275
276
277
278
  "DisableSysAddonUpdate": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("SysAddonUpdate");
      }
    }
  },

279
280
281
282
283
284
285
286
287
  "DisableTelemetry": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("datareporting.healthreport.uploadEnabled", false);
        setAndLockPref("datareporting.policy.dataSubmissionEnabled", false);
      }
    }
  },

288
  "DisplayBookmarksToolbar": {
289
    onBeforeUIStartup(manager, param) {
290
291
292
293
294
295
296
      let value = (!param).toString();
      // This policy is meant to change the default behavior, not to force it.
      // If this policy was alreay applied and the user chose to re-hide the
      // bookmarks toolbar, do not show it again.
      runOncePerModification("displayBookmarksToolbar", value, () => {
        gXulStore.setValue(BROWSER_DOCUMENT_URL, "PersonalToolbar", "collapsed", value);
      });
297
    }
298
299
  },

300
  "DisplayMenuBar": {
301
    onBeforeUIStartup(manager, param) {
302
      let value = (!param).toString();
303
304
305
        // This policy is meant to change the default behavior, not to force it.
        // If this policy was alreay applied and the user chose to re-hide the
        // menu bar, do not show it again.
306
307
308
      runOncePerModification("displayMenuBar", value, () => {
        gXulStore.setValue(BROWSER_DOCUMENT_URL, "toolbar-menubar", "autohide", value);
      });
309
310
311
    }
  },

312
  "DontCheckDefaultBrowser": {
313
    onBeforeUIStartup(manager, param) {
314
      setAndLockPref("browser.shell.checkDefaultBrowser", false);
315
316
317
    }
  },

318
319
  "EnableTrackingProtection": {
    onBeforeUIStartup(manager, param) {
320
321
322
323
324
325
326
327
      if (param.Value) {
        if (param.Locked) {
          setAndLockPref("privacy.trackingprotection.enabled", true);
          setAndLockPref("privacy.trackingprotection.pbmode.enabled", true);
        } else {
          setDefaultPref("privacy.trackingprotection.enabled", true);
          setDefaultPref("privacy.trackingprotection.pbmode.enabled", true);
        }
328
      } else {
329
330
        setAndLockPref("privacy.trackingprotection.enabled", false);
        setAndLockPref("privacy.trackingprotection.pbmode.enabled", false);
331
332
333
334
      }
    }
  },

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
  "Extensions": {
    onBeforeUIStartup(manager, param) {
      if ("Install" in param) {
        runOncePerModification("extensionsInstall", JSON.stringify(param.Install), () => {
          for (let location of param.Install) {
            let url;
            if (location.includes("://")) {
              // Assume location is an URI
              url = location;
            } else {
              // Assume location is a file path
              let xpiFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
              try {
                xpiFile.initWithPath(location);
              } catch (e) {
                log.error(`Invalid extension path location - ${location}`);
                continue;
              }
              url = Services.io.newFileURI(xpiFile).spec;
            }
355
356
357
358
359
360
            AddonManager.getInstallForURL(url, null, "application/x-xpinstall").then(install => {
              if (install.addon && install.addon.appDisabled) {
                log.error(`Incompatible add-on - ${location}`);
                install.cancel();
                return;
              }
361
              let listener = {
362
363
364
365
366
367
368
369
              /* eslint-disable-next-line no-shadow */
                onDownloadEnded: (install) => {
                  if (install.addon && install.addon.appDisabled) {
                    log.error(`Incompatible add-on - ${location}`);
                    install.removeListener(listener);
                    install.cancel();
                  }
                },
370
                onDownloadFailed: () => {
371
                  install.removeListener(listener);
372
373
374
                  log.error(`Download failed - ${location}`);
                },
                onInstallFailed: () => {
375
                  install.removeListener(listener);
376
377
378
                  log.error(`Installation failed - ${location}`);
                },
                onInstallEnded: () => {
379
                  install.removeListener(listener);
380
381
382
383
384
                  log.debug(`Installation succeeded - ${location}`);
                }
              };
              install.addListener(listener);
              install.install();
385
            });
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
          }
        });
      }
      if ("Uninstall" in param) {
        runOncePerModification("extensionsUninstall", JSON.stringify(param.Uninstall), () => {
          AddonManager.getAddonsByIDs(param.Uninstall, (addons) => {
            for (let addon of addons) {
              if (addon) {
                addon.uninstall();
              }
            }
          });
        });
      }
      if ("Locked" in param) {
        for (let ID of param.Locked) {
          manager.disallowFeature(`modify-extension:${ID}`);
        }
      }
    }
  },

408
  "FlashPlugin": {
409
    onBeforeUIStartup(manager, param) {
410
      addAllowDenyPermissions("plugin:flash", param.Allow, param.Block);
411
412
413
    }
  },

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
  "Homepage": {
    onBeforeUIStartup(manager, param) {
      // |homepages| will be a string containing a pipe-separated ('|') list of
      // URLs because that is what the "Home page" section of about:preferences
      // (and therefore what the pref |browser.startup.homepage|) accepts.
      let homepages = param.URL.spec;
      if (param.Additional && param.Additional.length > 0) {
        homepages += "|" + param.Additional.map(url => url.spec).join("|");
      }
      if (param.Locked) {
        setAndLockPref("browser.startup.homepage", homepages);
        setAndLockPref("browser.startup.page", 1);
        setAndLockPref("pref.browser.homepage.disable_button.current_page", true);
        setAndLockPref("pref.browser.homepage.disable_button.bookmark_page", true);
        setAndLockPref("pref.browser.homepage.disable_button.restore_default", true);
      } else {
430
431
432
433
434
        // The default pref for homepage is actually a complex pref. We need to
        // set it in a special way such that it works properly
        let homepagePrefVal = "data:text/plain,browser.startup.homepage=" +
                               homepages;
        setDefaultPref("browser.startup.homepage", homepagePrefVal);
435
        setDefaultPref("browser.startup.page", 1);
436
        runOncePerModification("setHomepage", homepages, () => {
437
438
          Services.prefs.clearUserPref("browser.startup.homepage");
          Services.prefs.clearUserPref("browser.startup.page");
439
440
441
442
443
        });
      }
    }
  },

444
  "InstallAddons": {
445
    onBeforeUIStartup(manager, param) {
446
      addAllowDenyPermissions("install", param.Allow, null);
447
448
449
    }
  },

450
451
452
453
454
455
456
457
  "NoDefaultBookmarks": {
    onProfileAfterChange(manager, param) {
      if (param) {
        manager.disallowFeature("defaultBookmarks");
      }
    }
  },

458
  "Popups": {
459
    onBeforeUIStartup(manager, param) {
460
      addAllowDenyPermissions("popup", param.Allow, null);
461
462
463
    }
  },

464
465
466
467
468
469
470
471
472
473
474
  "Proxy": {
    onBeforeAddons(manager, param) {
      if (param.Locked) {
        manager.disallowFeature("changeProxySettings");
        ProxyPolicies.configureProxySettings(param, setAndLockPref);
      } else {
        ProxyPolicies.configureProxySettings(param, setDefaultPref);
      }
    }
  },

475
476
477
  "RememberPasswords": {
    onBeforeUIStartup(manager, param) {
      setAndLockPref("signon.rememberSignons", param);
478
479
    }
  },
480

481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
  "SearchBar": {
    onAllWindowsRestored(manager, param) {
      // This policy is meant to change the default behavior, not to force it.
      // If this policy was already applied and the user chose move the search
      // bar, don't move it again.
      runOncePerModification("searchInNavBar", param, () => {
        if (param == "separate") {
          CustomizableUI.addWidgetToArea("search-container", CustomizableUI.AREA_NAVBAR,
          CustomizableUI.getPlacementOfWidget("urlbar-container").position + 1);
        } else if (param == "unified") {
          CustomizableUI.removeWidgetFromArea("search-container");
        }
      });
    }
  },

497
  "SearchEngines": {
498
499
500
501
502
    onBeforeUIStartup(manager, param) {
      if (param.PreventInstalls) {
        manager.disallowFeature("installSearchEngine", true);
      }
    },
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
    onAllWindowsRestored(manager, param) {
      Services.search.init(() => {
        if (param.Add) {
          // Only rerun if the list of engine names has changed.
          let engineNameList = param.Add.map(engine => engine.Name);
          runOncePerModification("addSearchEngines",
                                 JSON.stringify(engineNameList),
                                 () => {
            for (let newEngine of param.Add) {
              let newEngineParameters = {
                template:    newEngine.URLTemplate,
                iconURL:     newEngine.IconURL,
                alias:       newEngine.Alias,
                description: newEngine.Description,
                method:      newEngine.Method,
                suggestURL:  newEngine.SuggestURLTemplate,
                extensionID: "set-via-policy"
              };
              try {
                Services.search.addEngineWithDetails(newEngine.Name,
                                                     newEngineParameters);
              } catch (ex) {
                log.error("Unable to add search engine", ex);
              }
            }
          });
        }
        if (param.Default) {
          runOnce("setDefaultSearchEngine", () => {
            let defaultEngine;
            try {
              defaultEngine = Services.search.getEngineByName(param.Default);
              if (!defaultEngine) {
                throw "No engine by that name could be found";
              }
            } catch (ex) {
              log.error(`Search engine lookup failed when attempting to set ` +
                        `the default engine. Requested engine was ` +
                        `"${param.Default}".`, ex);
            }
            if (defaultEngine) {
              try {
                Services.search.currentEngine = defaultEngine;
              } catch (ex) {
                log.error("Unable to set the default search engine", ex);
              }
            }
          });
        }
      });
    }
  }
555
};
556
557
558
559
560
561
562
563
564

/*
 * ====================
 * = HELPER FUNCTIONS =
 * ====================
 *
 * The functions below are helpers to be used by several policies.
 */

565
566
567
568
569
570
571
572
573
574
575
576
577
/**
 * setAndLockPref
 *
 * Sets the _default_ value of a pref, and locks it (meaning that
 * the default value will always be returned, independent from what
 * is stored as the user value).
 * The value is only changed in memory, and not stored to disk.
 *
 * @param {string} prefName
 *        The pref to be changed
 * @param {boolean,number,string} prefValue
 *        The value to set and lock
 */
578
579
580
581
582
function setAndLockPref(prefName, prefValue) {
  if (Services.prefs.prefIsLocked(prefName)) {
    Services.prefs.unlockPref(prefName);
  }

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
  setDefaultPref(prefName, prefValue);

  Services.prefs.lockPref(prefName);
}

/**
 * setDefaultPref
 *
 * Sets the _default_ value of a pref.
 * The value is only changed in memory, and not stored to disk.
 *
 * @param {string} prefName
 *        The pref to be changed
 * @param {boolean,number,string} prefValue
 *        The value to set
 */
function setDefaultPref(prefName, prefValue) {
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
  let defaults = Services.prefs.getDefaultBranch("");

  switch (typeof(prefValue)) {
    case "boolean":
      defaults.setBoolPref(prefName, prefValue);
      break;

    case "number":
      if (!Number.isInteger(prefValue)) {
        throw new Error(`Non-integer value for ${prefName}`);
      }

      defaults.setIntPref(prefName, prefValue);
      break;

    case "string":
      defaults.setStringPref(prefName, prefValue);
      break;
  }
}
620

621
622
623
624
625
626
627
628
629
630
631
632
633
/**
 * addAllowDenyPermissions
 *
 * Helper function to call the permissions manager (Services.perms.add)
 * for two arrays of URLs.
 *
 * @param {string} permissionName
 *        The name of the permission to change
 * @param {array} allowList
 *        The list of URLs to be set as ALLOW_ACTION for the chosen permission.
 * @param {array} blockList
 *        The list of URLs to be set as DENY_ACTION for the chosen permission.
 */
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
function addAllowDenyPermissions(permissionName, allowList, blockList) {
  allowList = allowList || [];
  blockList = blockList || [];

  for (let origin of allowList) {
    Services.perms.add(origin,
                       permissionName,
                       Ci.nsIPermissionManager.ALLOW_ACTION,
                       Ci.nsIPermissionManager.EXPIRE_POLICY);
  }

  for (let origin of blockList) {
    Services.perms.add(origin,
                       permissionName,
                       Ci.nsIPermissionManager.DENY_ACTION,
                       Ci.nsIPermissionManager.EXPIRE_POLICY);
  }
}
652
653
654
655
656
657
658
659
660
661
662

/**
 * runOnce
 *
 * Helper function to run a callback only once per policy.
 *
 * @param {string} actionName
 *        A given name which will be used to track if this callback has run.
 * @param {Functon} callback
 *        The callback to run only once.
 */
663
 // eslint-disable-next-line no-unused-vars
664
665
666
667
668
669
670
function runOnce(actionName, callback) {
  let prefName = `browser.policies.runonce.${actionName}`;
  if (Services.prefs.getBoolPref(prefName, false)) {
    log.debug(`Not running action ${actionName} again because it has already run.`);
    return;
  }
  Services.prefs.setBoolPref(prefName, true);
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
  callback();
}

/**
 * runOncePerModification
 *
 * Helper function similar to runOnce. The difference is that runOnce runs the
 * callback once when the policy is set, then never again.
 * runOncePerModification runs the callback once each time the policy value
 * changes from its previous value.
 *
 * @param {string} actionName
 *        A given name which will be used to track if this callback has run.
 *        This string will be part of a pref name.
 * @param {string} policyValue
 *        The current value of the policy. This will be compared to previous
 *        values given to this function to determine if the policy value has
 *        changed. Regardless of the data type of the policy, this must be a
 *        string.
 * @param {Function} callback
 *        The callback to be run when the pref value changes
 */
function runOncePerModification(actionName, policyValue, callback) {
  let prefName = `browser.policies.runOncePerModification.${actionName}`;
  let oldPolicyValue = Services.prefs.getStringPref(prefName, undefined);
  if (policyValue === oldPolicyValue) {
    log.debug(`Not running action ${actionName} again because the policy's value is unchanged`);
    return;
  }
  Services.prefs.setStringPref(prefName, policyValue);
  callback();
702
}