Policies.jsm 38.8 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
9
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
10
11
12
13
14

XPCOMUtils.defineLazyServiceGetters(this, {
  gCertDB: ["@mozilla.org/security/x509certdb;1", "nsIX509CertDB"],
  gXulStore: ["@mozilla.org/xul/xulstore;1", "nsIXULStore"],
});
15

16
XPCOMUtils.defineLazyModuleGetters(this, {
17
  AddonManager: "resource://gre/modules/AddonManager.jsm",
18
  BookmarksPolicies: "resource:///modules/policies/BookmarksPolicies.jsm",
19
  CustomizableUI: "resource:///modules/CustomizableUI.jsm",
20
21
  ProxyPolicies: "resource:///modules/policies/ProxyPolicies.jsm",
  WebsiteFilter: "resource:///modules/policies/WebsiteFilter.jsm",
22
23
});

24
25
XPCOMUtils.defineLazyGlobalGetters(this, ["File", "FileReader"]);

26
const PREF_LOGLEVEL           = "browser.policies.loglevel";
27
const BROWSER_DOCUMENT_URL    = AppConstants.BROWSER_CHROME_URL;
28
29

XPCOMUtils.defineLazyGetter(this, "log", () => {
30
  let { ConsoleAPI } = ChromeUtils.import("resource://gre/modules/Console.jsm");
31
32
33
34
35
36
37
38
39
  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,
  });
});

40
var EXPORTED_SYMBOLS = ["Policies"];
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
/*
 * ============================
 * = 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.
 */
68
var Policies = {
69
70
71
72
73
74
  "3rdparty": {
    onBeforeAddons(manager, param) {
      manager.setExtensionPolicies(param.Extensions);
    },
  },

75
76
77
  "AppUpdateURL": {
    onBeforeAddons(manager, param) {
      setDefaultPref("app.update.url", param.href);
78
    },
79
80
  },

81
82
83
84
85
86
87
88
89
90
91
  "Authentication": {
    onBeforeAddons(manager, param) {
      if ("SPNEGO" in param) {
        setAndLockPref("network.negotiate-auth.trusted-uris", param.SPNEGO.join(", "));
      }
      if ("Delegated" in param) {
        setAndLockPref("network.negotiate-auth.delegation-uris", param.Delegated.join(", "));
      }
      if ("NTLM" in param) {
        setAndLockPref("network.automatic-ntlm-auth.trusted-uris", param.NTLM.join(", "));
      }
92
93
94
95
96
97
98
99
      if ("AllowNonFQDN" in param) {
        if (param.AllowNonFQDN.NTLM) {
          setAndLockPref("network.automatic-ntlm-auth.allow-non-fqdn", param.AllowNonFQDN.NTLM);
        }
        if (param.AllowNonFQDN.SPNEGO) {
          setAndLockPref("network.negotiate-auth.allow-non-fqdn", param.AllowNonFQDN.SPNEGO);
        }
      }
100
    },
101
102
  },

103
104
105
  "BlockAboutAddons": {
    onBeforeUIStartup(manager, param) {
      if (param) {
106
        blockAboutPage(manager, "about:addons", true);
107
      }
108
    },
109
110
  },

111
  "BlockAboutConfig": {
112
    onBeforeUIStartup(manager, param) {
113
      if (param) {
114
        blockAboutPage(manager, "about:config");
115
        setAndLockPref("devtools.chrome.enabled", false);
116
      }
117
    },
118
  },
119

120
121
122
  "BlockAboutProfiles": {
    onBeforeUIStartup(manager, param) {
      if (param) {
123
        blockAboutPage(manager, "about:profiles");
124
      }
125
    },
126
127
  },

128
129
130
  "BlockAboutSupport": {
    onBeforeUIStartup(manager, param) {
      if (param) {
131
        blockAboutPage(manager, "about:support");
132
      }
133
    },
134
135
  },

136
137
138
  "Bookmarks": {
    onAllWindowsRestored(manager, param) {
      BookmarksPolicies.processBookmarks(param);
139
    },
140
141
  },

142
143
144
145
146
147
  "CaptivePortal": {
    onBeforeAddons(manager, param) {
      setAndLockPref("network.captive-portal-service.enabled", param);
    },
  },

148
149
150
  "Certificates": {
    onBeforeAddons(manager, param) {
      if ("ImportEnterpriseRoots" in param) {
151
        setAndLockPref("security.enterprise_roots.enabled", param.ImportEnterpriseRoots);
152
      }
153
154
155
156
157
158
      if ("Install" in param) {
        (async () => {
          let dirs = [];
          let platform = AppConstants.platform;
          if (platform == "win") {
            dirs = [
159
              // Ugly, but there is no official way to get %USERNAME\AppData\Roaming\Mozilla.
160
              Services.dirsvc.get("XREUSysExt", Ci.nsIFile).parent,
161
162
              // Even more ugly, but there is no official way to get %USERNAME\AppData\Local\Mozilla.
              Services.dirsvc.get("DefProfLRt", Ci.nsIFile).parent.parent,
163
164
165
166
167
168
169
170
            ];
          } else if (platform == "macosx" || platform == "linux") {
            dirs = [
              // These two keys are named wrong. They return the Mozilla directory.
              Services.dirsvc.get("XREUserNativeManifests", Ci.nsIFile),
              Services.dirsvc.get("XRESysNativeManifests", Ci.nsIFile),
            ];
          }
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
          dirs.unshift(Services.dirsvc.get("XREAppDist", Ci.nsIFile));
          for (let certfilename of param.Install) {
            let certfile;
            try {
              certfile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
              certfile.initWithPath(certfilename);
            } catch (e) {
              for (let dir of dirs) {
                certfile = dir.clone();
                certfile.append(platform == "linux" ? "certificates" : "Certificates");
                certfile.append(certfilename);
                if (certfile.exists()) {
                  break;
                }
              }
            }
            let file;
            try {
              file = await File.createFromNsIFile(certfile);
            } catch (e) {
              log.error(`Unable to find certificate - ${certfilename}`);
              continue;
            }
            let reader = new FileReader();
            reader.onloadend = function() {
              if (reader.readyState != reader.DONE) {
                log.error(`Unable to read certificate - ${certfile.path}`);
                return;
              }
              let cert = reader.result;
201
              try {
202
203
204
205
206
                if (/-----BEGIN CERTIFICATE-----/.test(cert)) {
                  gCertDB.addCertFromBase64(pemToBase64(cert), "CTu,CTu,");
                } else {
                  gCertDB.addCert(cert, "CTu,CTu,");
                }
207
              } catch (e) {
208
                log.error(`Unable to add certificate - ${certfile.path}`);
209
              }
210
211
            };
            reader.readAsBinaryString(file);
212
213
214
          }
        })();
      }
215
    },
216
217
  },

218
  "Cookies": {
219
    onBeforeUIStartup(manager, param) {
220
      addAllowDenyPermissions("cookie", param.Allow, param.Block);
221
222

      if (param.Block) {
223
        const hosts = param.Block.map(url => url.hostname).sort().join("\n");
224
225
        runOncePerModification("clearCookiesForBlockedHosts", hosts, () => {
          for (let blocked of param.Block) {
226
            Services.cookies.removeCookiesWithOriginAttributes("{}", blocked.hostname);
227
228
229
          }
        });
      }
230
231
232

      if (param.Default !== undefined ||
          param.AcceptThirdParty !== undefined ||
233
          param.RejectTracker !== undefined ||
234
235
236
237
238
          param.Locked) {
        const ACCEPT_COOKIES = 0;
        const REJECT_THIRD_PARTY_COOKIES = 1;
        const REJECT_ALL_COOKIES = 2;
        const REJECT_UNVISITED_THIRD_PARTY = 3;
239
        const REJECT_TRACKER = 4;
240
241
242
243
244

        let newCookieBehavior = ACCEPT_COOKIES;
        if (param.Default !== undefined && !param.Default) {
          newCookieBehavior = REJECT_ALL_COOKIES;
        } else if (param.AcceptThirdParty) {
245
          if (param.AcceptThirdParty == "never") {
246
247
248
249
            newCookieBehavior = REJECT_THIRD_PARTY_COOKIES;
          } else if (param.AcceptThirdParty == "from-visited") {
            newCookieBehavior = REJECT_UNVISITED_THIRD_PARTY;
          }
250
251
        } else if (param.RejectTracker !== undefined && param.RejectTracker) {
          newCookieBehavior = REJECT_TRACKER;
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        }

        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);
        }
      }
276
    },
277
278
  },

279
280
281
282
  "DisableAppUpdate": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("appUpdate");
283
      }
284
    },
285
286
  },

287
  "DisableBuiltinPDFViewer": {
288
    onBeforeAddons(manager, param) {
289
      if (param) {
290
        setAndLockPref("pdfjs.disabled", true);
291
      }
292
    },
293
294
  },

295
296
297
298
299
300
301
  "DisableDeveloperTools": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("devtools.policy.disabled", true);
        setAndLockPref("devtools.chrome.enabled", false);

        manager.disallowFeature("devtools");
302
303
304
        blockAboutPage(manager, "about:devtools");
        blockAboutPage(manager, "about:debugging");
        blockAboutPage(manager, "about:devtools-toolbox");
305
      }
306
    },
307
308
  },

309
310
311
312
313
  "DisableFeedbackCommands": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("feedbackCommands");
      }
314
    },
315
316
  },

317
318
319
320
321
  "DisableFirefoxAccounts": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("identity.fxaccounts.enabled", false);
      }
322
    },
323
324
  },

325
326
  "DisableFirefoxScreenshots": {
    onBeforeAddons(manager, param) {
327
      if (param) {
328
329
        setAndLockPref("extensions.screenshots.disabled", true);
      }
330
    },
331
332
  },

333
334
  "DisableFirefoxStudies": {
    onBeforeAddons(manager, param) {
335
      if (param) {
336
        manager.disallowFeature("Shield");
337
338
        setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
        setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
339
      }
340
    },
341
342
  },

343
344
345
  "DisableForgetButton": {
    onProfileAfterChange(manager, param) {
      if (param) {
346
        setAndLockPref("privacy.panicButton.enabled", false);
347
      }
348
    },
349
350
  },

351
352
  "DisableFormHistory": {
    onBeforeUIStartup(manager, param) {
353
      if (param) {
354
355
        setAndLockPref("browser.formfill.enable", false);
      }
356
    },
357
358
  },

359
360
361
362
363
  "DisableMasterPasswordCreation": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("createMasterPassword");
      }
364
    },
365
366
  },

367
368
369
370
371
  "DisablePocket": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("extensions.pocket.enabled", false);
      }
372
    },
373
374
  },

375
376
377
378
  "DisablePrivateBrowsing": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("privatebrowsing");
379
        blockAboutPage(manager, "about:privatebrowsing", true);
380
381
        setAndLockPref("browser.privatebrowsing.autostart", false);
      }
382
    },
383
384
  },

385
386
387
388
389
390
  "DisableProfileImport": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("profileImport");
        setAndLockPref("browser.newtabpage.activity-stream.migrationExpired", true);
      }
391
    },
392
393
  },

394
395
396
397
398
399
  "DisableProfileRefresh": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("profileRefresh");
        setAndLockPref("browser.disableResetPrompt", true);
      }
400
    },
401
402
  },

403
404
405
406
407
  "DisableSafeMode": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("safeMode");
      }
408
    },
409
410
  },

411
412
  "DisableSecurityBypass": {
    onBeforeUIStartup(manager, param) {
413
414
415
416
      if ("InvalidCertificate" in param) {
        setAndLockPref("security.certerror.hideAddException", param.InvalidCertificate);
      }

417
418
419
      if ("SafeBrowsing" in param) {
        setAndLockPref("browser.safebrowsing.allowOverride", !param.SafeBrowsing);
      }
420
    },
421
422
  },

423
424
425
  "DisableSetDesktopBackground": {
    onBeforeUIStartup(manager, param) {
      if (param) {
426
        manager.disallowFeature("setDesktopBackground");
427
      }
428
    },
429
430
431
  },

  "DisableSystemAddonUpdate": {
432
433
434
435
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("SysAddonUpdate");
      }
436
    },
437
438
  },

439
440
441
442
443
  "DisableTelemetry": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("datareporting.healthreport.uploadEnabled", false);
        setAndLockPref("datareporting.policy.dataSubmissionEnabled", false);
444
        blockAboutPage(manager, "about:telemetry");
445
      }
446
    },
447
448
  },

449
  "DisplayBookmarksToolbar": {
450
    onBeforeUIStartup(manager, param) {
451
452
453
454
455
456
457
      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);
      });
458
    },
459
460
  },

461
  "DisplayMenuBar": {
462
    onBeforeUIStartup(manager, param) {
463
      let value = (!param).toString();
464
465
466
        // 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.
467
468
469
      runOncePerModification("displayMenuBar", value, () => {
        gXulStore.setValue(BROWSER_DOCUMENT_URL, "toolbar-menubar", "autohide", value);
      });
470
    },
471
472
  },

473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
  "DNSOverHTTPS": {
    onBeforeAddons(manager, param) {
      if ("Enabled" in param) {
        let mode = param.Enabled ? 2 : 5;
        if (param.Locked) {
          setAndLockPref("network.trr.mode", mode);
        } else {
          setDefaultPref("network.trr.mode", mode);
        }
      }
      if (param.ProviderURL) {
        if (param.Locked) {
          setAndLockPref("network.trr.uri", param.ProviderURL.href);
        } else {
          setDefaultPref("network.trr.uri", param.ProviderURL.href);
        }
      }
    },
  },

493
  "DontCheckDefaultBrowser": {
494
    onBeforeUIStartup(manager, param) {
495
      setAndLockPref("browser.shell.checkDefaultBrowser", !param);
496
    },
497
498
  },

499
500
  "EnableTrackingProtection": {
    onBeforeUIStartup(manager, param) {
501
502
503
504
505
506
507
508
      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);
        }
509
      } else {
510
511
        setAndLockPref("privacy.trackingprotection.enabled", false);
        setAndLockPref("privacy.trackingprotection.pbmode.enabled", false);
512
      }
513
    },
514
515
  },

516
517
  "Extensions": {
    onBeforeUIStartup(manager, param) {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
      let uninstallingPromise = Promise.resolve();
      if ("Uninstall" in param) {
        uninstallingPromise = runOncePerModification("extensionsUninstall", JSON.stringify(param.Uninstall), async () => {
          // If we're uninstalling add-ons, re-run the extensionsInstall runOnce even if it hasn't
          // changed, which will allow add-ons to be updated.
          Services.prefs.clearUserPref("browser.policies.runOncePerModification.extensionsInstall");
          let addons = await AddonManager.getAddonsByIDs(param.Uninstall);
          for (let addon of addons) {
            if (addon) {
              try {
                await addon.uninstall();
              } catch (e) {
                // This can fail for add-ons that can't be uninstalled.
                // Just ignore.
              }
            }
          }
        });
      }
537
      if ("Install" in param) {
538
539
        runOncePerModification("extensionsInstall", JSON.stringify(param.Install), async () => {
          await uninstallingPromise;
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
          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;
            }
556
557
558
            AddonManager.getInstallForURL(url, {
              telemetryInfo: {source: "enterprise-policy"},
            }).then(install => {
559
560
561
562
563
              if (install.addon && install.addon.appDisabled) {
                log.error(`Incompatible add-on - ${location}`);
                install.cancel();
                return;
              }
564
              let listener = {
565
566
567
568
569
570
571
572
              /* 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();
                  }
                },
573
                onDownloadFailed: () => {
574
                  install.removeListener(listener);
575
576
577
                  log.error(`Download failed - ${location}`);
                },
                onInstallFailed: () => {
578
                  install.removeListener(listener);
579
580
581
                  log.error(`Installation failed - ${location}`);
                },
                onInstallEnded: () => {
582
                  install.removeListener(listener);
583
                  log.debug(`Installation succeeded - ${location}`);
584
                },
585
586
587
              };
              install.addListener(listener);
              install.install();
588
            });
589
590
591
592
593
594
595
596
          }
        });
      }
      if ("Locked" in param) {
        for (let ID of param.Locked) {
          manager.disallowFeature(`modify-extension:${ID}`);
        }
      }
597
    },
598
599
  },

600
601
602
603
604
605
606
607
  "ExtensionUpdate": {
    onBeforeAddons(manager, param) {
      if (!param) {
        setAndLockPref("extensions.update.enabled", param);
      }
    },
  },

608
  "FlashPlugin": {
609
    onBeforeUIStartup(manager, param) {
610
      addAllowDenyPermissions("plugin:flash", param.Allow, param.Block);
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628

      const FLASH_NEVER_ACTIVATE = 0;
      const FLASH_ASK_TO_ACTIVATE = 1;
      const FLASH_ALWAYS_ACTIVATE = 2;

      let flashPrefVal;
      if (param.Default === undefined) {
        flashPrefVal = FLASH_ASK_TO_ACTIVATE;
      } else if (param.Default) {
        flashPrefVal = FLASH_ALWAYS_ACTIVATE;
      } else {
        flashPrefVal = FLASH_NEVER_ACTIVATE;
      }
      if (param.Locked) {
        setAndLockPref("plugin.state.flash", flashPrefVal);
      } else if (param.Default !== undefined) {
        setDefaultPref("plugin.state.flash", flashPrefVal);
      }
629
    },
630
631
  },

632
633
634
635
636
  "HardwareAcceleration": {
    onBeforeAddons(manager, param) {
      if (!param) {
        setAndLockPref("layers.acceleration.disabled", true);
      }
637
    },
638
639
  },

640
641
642
643
644
  "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.
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
      if (param.URL) {
        let homepages = param.URL.href;
        if (param.Additional && param.Additional.length > 0) {
          homepages += "|" + param.Additional.map(url => url.href).join("|");
        }
        if (param.Locked) {
          setAndLockPref("browser.startup.homepage", homepages);
          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 {
          setDefaultPref("browser.startup.homepage", homepages);
          runOncePerModification("setHomepage", homepages, () => {
            Services.prefs.clearUserPref("browser.startup.homepage");
          });
        }
661
      }
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
      if (param.StartPage) {
        let prefValue;
        switch (param.StartPage) {
          case "none":
            prefValue = 0;
            break;
          case "homepage":
            prefValue = 1;
            break;
          case "previous-session":
            prefValue = 3;
            break;
        }
        if (param.Locked) {
          setAndLockPref("browser.startup.page", prefValue);
        } else {
          setDefaultPref("browser.startup.page", prefValue);
        }
680
      }
681
    },
682
683
  },

684
  "InstallAddonsPermission": {
685
    onBeforeUIStartup(manager, param) {
686
687
688
689
690
      if ("Allow" in param) {
        addAllowDenyPermissions("install", param.Allow, null);
      }
      if ("Default" in param) {
        setAndLockPref("xpinstall.enabled", param.Default);
691
        if (!param.Default) {
692
          blockAboutPage(manager, "about:debugging");
693
694
          setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
          setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
695
          manager.disallowFeature("xpinstall");
696
        }
697
      }
698
    },
699
700
  },

701
702
703
704
705
706
707
  "NetworkPrediction": {
    onBeforeAddons(manager, param) {
      setAndLockPref("network.dns.disablePrefetch", !param);
      setAndLockPref("network.dns.disablePrefetchFromHTTPS", !param);
    },
  },

708
709
710
711
712
  "NoDefaultBookmarks": {
    onProfileAfterChange(manager, param) {
      if (param) {
        manager.disallowFeature("defaultBookmarks");
      }
713
    },
714
715
  },

716
717
718
  "OfferToSaveLogins": {
    onBeforeUIStartup(manager, param) {
      setAndLockPref("signon.rememberSignons", param);
719
    },
720
721
  },

722
723
  "OverrideFirstRunPage": {
    onProfileAfterChange(manager, param) {
724
      let url = param ? param.href : "";
725
      setAndLockPref("startup.homepage_welcome_url", url);
726
    },
727
728
  },

729
730
  "OverridePostUpdatePage": {
    onProfileAfterChange(manager, param) {
731
      let url = param ? param.href : "";
732
733
734
735
736
      setAndLockPref("startup.homepage_override_url", url);
      // The pref startup.homepage_override_url is only used
      // as a fallback when the update.xml file hasn't provided
      // a specific post-update URL.
      manager.disallowFeature("postUpdateCustomPage");
737
    },
738
739
  },

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
  "Permissions": {
    onBeforeUIStartup(manager, param) {
      if (param.Camera) {
        addAllowDenyPermissions("camera", param.Camera.Allow, param.Camera.Block);
        setDefaultPermission("camera", param.Camera);
      }

      if (param.Microphone) {
        addAllowDenyPermissions("microphone", param.Microphone.Allow, param.Microphone.Block);
        setDefaultPermission("microphone", param.Microphone);
      }

      if (param.Location) {
        addAllowDenyPermissions("geo", param.Location.Allow, param.Location.Block);
        setDefaultPermission("geo", param.Location);
      }

      if (param.Notifications) {
        addAllowDenyPermissions("desktop-notification", param.Notifications.Allow, param.Notifications.Block);
        setDefaultPermission("desktop-notification", param.Notifications);
      }
761
    },
762
763
  },

764
  "PopupBlocking": {
765
    onBeforeUIStartup(manager, param) {
766
      addAllowDenyPermissions("popup", param.Allow, null);
767
768
769
770
771
772
773
774
775
776

      if (param.Locked) {
        let blockValue = true;
        if (param.Default !== undefined && !param.Default) {
          blockValue = false;
        }
        setAndLockPref("dom.disable_open_during_load", blockValue);
      } else if (param.Default !== undefined) {
        setDefaultPref("dom.disable_open_during_load", !!param.Default);
      }
777
    },
778
779
  },

780
781
782
783
784
785
786
787
  "Proxy": {
    onBeforeAddons(manager, param) {
      if (param.Locked) {
        manager.disallowFeature("changeProxySettings");
        ProxyPolicies.configureProxySettings(param, setAndLockPref);
      } else {
        ProxyPolicies.configureProxySettings(param, setDefaultPref);
      }
788
    },
789
  },
790

791
792
793
794
795
796
  "RequestedLocales": {
    onBeforeAddons(manager, param) {
      Services.locale.requestedLocales = param;
    },
  },

797
798
799
800
801
802
803
804
805
806
807
808
809
  "SanitizeOnShutdown": {
    onBeforeUIStartup(manager, param) {
      setAndLockPref("privacy.sanitize.sanitizeOnShutdown", param);
      if (param) {
        setAndLockPref("privacy.clearOnShutdown.cache", true);
        setAndLockPref("privacy.clearOnShutdown.cookies", true);
        setAndLockPref("privacy.clearOnShutdown.downloads", true);
        setAndLockPref("privacy.clearOnShutdown.formdata", true);
        setAndLockPref("privacy.clearOnShutdown.history", true);
        setAndLockPref("privacy.clearOnShutdown.sessions", true);
        setAndLockPref("privacy.clearOnShutdown.siteSettings", true);
        setAndLockPref("privacy.clearOnShutdown.offlineApps", true);
      }
810
    },
811
812
  },

813
814
815
816
817
818
819
820
821
822
823
824
825
  "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");
        }
      });
826
    },
827
828
  },

829
  "SearchEngines": {
830
831
832
833
834
    onBeforeUIStartup(manager, param) {
      if (param.PreventInstalls) {
        manager.disallowFeature("installSearchEngine", true);
      }
    },
835
    onAllWindowsRestored(manager, param) {
836
      Services.search.init().then(async () => {
837
838
        if (param.Remove) {
          // Only rerun if the list of engine names has changed.
839
840
841
          await runOncePerModification("removeSearchEngines",
                                       JSON.stringify(param.Remove),
                                       async function() {
842
843
844
845
            for (let engineName of param.Remove) {
              let engine = Services.search.getEngineByName(engineName);
              if (engine) {
                try {
846
                  await Services.search.removeEngine(engine);
847
848
849
850
851
852
853
                } catch (ex) {
                  log.error("Unable to remove the search engine", ex);
                }
              }
            }
          });
        }
854
855
856
        if (param.Add) {
          // Only rerun if the list of engine names has changed.
          let engineNameList = param.Add.map(engine => engine.Name);
857
858
859
          await runOncePerModification("addSearchEngines",
                                       JSON.stringify(engineNameList),
                                       async function() {
860
861
862
            for (let newEngine of param.Add) {
              let newEngineParameters = {
                template:    newEngine.URLTemplate,
863
                iconURL:     newEngine.IconURL ? newEngine.IconURL.href : null,
864
865
866
                alias:       newEngine.Alias,
                description: newEngine.Description,
                method:      newEngine.Method,
867
                postData:    newEngine.PostData,
868
                suggestURL:  newEngine.SuggestURLTemplate,
869
                extensionID: "set-via-policy",
870
                queryCharset: "UTF-8",
871
872
              };
              try {
873
874
                await Services.search.addEngineWithDetails(newEngine.Name,
                                                           newEngineParameters);
875
876
877
878
879
880
881
              } catch (ex) {
                log.error("Unable to add search engine", ex);
              }
            }
          });
        }
        if (param.Default) {
882
          await runOncePerModification("setDefaultSearchEngine", param.Default, async () => {
883
884
885
886
887
888
889
890
891
892
893
894
895
            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 {
896
                await Services.search.setDefault(defaultEngine);
897
898
899
900
901
902
903
              } catch (ex) {
                log.error("Unable to set the default search engine", ex);
              }
            }
          });
        }
      });
904
    },
905
906
  },

907
908
909
  "SecurityDevices": {
    onProfileAfterChange(manager, param) {
      let securityDevices = param;
910
911
912
913
914
915
916
917
      let pkcs11db = Cc["@mozilla.org/security/pkcs11moduledb;1"].getService(Ci.nsIPKCS11ModuleDB);
      let moduleList = pkcs11db.listModules();
      for (let deviceName in securityDevices) {
        let foundModule = false;
        for (let module of moduleList) {
          if (module && module.libName === securityDevices[deviceName]) {
            foundModule = true;
            break;
918
919
          }
        }
920
921
922
923
924
925
926
927
928
929
        if (foundModule) {
          continue;
        }
        try {
          pkcs11db.addModule(deviceName, securityDevices[deviceName], 0, 0);
        } catch (ex) {
          log.error(`Unable to add security device ${deviceName}`);
          log.debug(ex);
        }
      }
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
  "SSLVersionMax": {
    onBeforeAddons(manager, param) {
      let tlsVersion;
      switch (param) {
        case "tls1":
          tlsVersion = 1;
          break;
        case "tls1.1":
          tlsVersion = 2;
          break;
        case "tls1.2":
          tlsVersion = 3;
          break;
        case "tls1.3":
          tlsVersion = 4;
          break;
      }
      setAndLockPref("security.tls.version.max", tlsVersion);
    },
  },

  "SSLVersionMin": {
    onBeforeAddons(manager, param) {
      let tlsVersion;
      switch (param) {
        case "tls1":
          tlsVersion = 1;
          break;
        case "tls1.1":
          tlsVersion = 2;
          break;
        case "tls1.2":
          tlsVersion = 3;
          break;
        case "tls1.3":
          tlsVersion = 4;
          break;
      }
      setAndLockPref("security.tls.version.min", tlsVersion);
    },
  },

975
976
977
978
979
980
  "SupportMenu": {
    onProfileAfterChange(manager, param) {
      manager.setSupportMenu(param);
    },
  },

981
982
983
  "WebsiteFilter": {
    onBeforeUIStartup(manager, param) {
      this.filter = new WebsiteFilter(param.Block || [], param.Exceptions || []);
984
    },
985
986
  },

987
};
988
989
990
991
992
993
994
995
996

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

997
998
999
1000
/**
 * setAndLockPref
 *
 * Sets the _default_ value of a pref, and locks it (meaning that
For faster browsing, not all history is shown. View entire blame