Policies.jsm 47.2 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
  FileUtils: "resource://gre/modules/FileUtils.jsm",
21
22
  ProxyPolicies: "resource:///modules/policies/ProxyPolicies.jsm",
  WebsiteFilter: "resource:///modules/policies/WebsiteFilter.jsm",
23
24
});

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

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

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

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

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

82
83
84
85
86
87
88
89
90
91
92
  "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(", "));
      }
93
94
95
96
97
98
99
100
      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);
        }
      }
101
    },
102
103
  },

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

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

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

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

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

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

149
150
151
  "Certificates": {
    onBeforeAddons(manager, param) {
      if ("ImportEnterpriseRoots" in param) {
152
        setAndLockPref("security.enterprise_roots.enabled", param.ImportEnterpriseRoots);
153
      }
154
155
156
157
158
159
      if ("Install" in param) {
        (async () => {
          let dirs = [];
          let platform = AppConstants.platform;
          if (platform == "win") {
            dirs = [
160
              // Ugly, but there is no official way to get %USERNAME\AppData\Roaming\Mozilla.
161
              Services.dirsvc.get("XREUSysExt", Ci.nsIFile).parent,
162
163
              // Even more ugly, but there is no official way to get %USERNAME\AppData\Local\Mozilla.
              Services.dirsvc.get("DefProfLRt", Ci.nsIFile).parent.parent,
164
165
166
167
168
169
170
171
            ];
          } 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),
            ];
          }
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;
              }
201
202
              let certFile = reader.result;
              let cert;
203
              try {
204
                cert = gCertDB.constructX509(certFile);
205
              } catch (e) {
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
                try {
                  // It might be PEM instead of DER.
                  cert = gCertDB.constructX509FromBase64(pemToBase64(certFile));
                } catch (ex) {
                  log.error(`Unable to add certificate - ${certfile.path}`);
                }
              }
              let now = Date.now() / 1000;
              if (cert) {
                gCertDB.asyncVerifyCertAtTime(cert, 0x0008 /* certificateUsageSSLCA */,
                                              0, null, now, (aPRErrorCode, aVerifiedChain, aHasEVPolicy) => {
                  if (aPRErrorCode == Cr.NS_OK) {
                    // Certificate is already installed.
                    return;
                  }
                  try {
                    gCertDB.addCert(certFile, "CT,CT,");
                  } catch (e) {
                    // It might be PEM instead of DER.
                    gCertDB.addCertFromBase64(pemToBase64(certFile), "CT,CT,");
                  }
                });
228
              }
229
230
            };
            reader.readAsBinaryString(file);
231
232
233
          }
        })();
      }
234
    },
235
236
  },

237
  "Cookies": {
238
    onBeforeUIStartup(manager, param) {
239
      addAllowDenyPermissions("cookie", param.Allow, param.Block);
240
241

      if (param.Block) {
242
        const hosts = param.Block.map(url => url.hostname).sort().join("\n");
243
244
        runOncePerModification("clearCookiesForBlockedHosts", hosts, () => {
          for (let blocked of param.Block) {
245
            Services.cookies.removeCookiesWithOriginAttributes("{}", blocked.hostname);
246
247
248
          }
        });
      }
249
250
251

      if (param.Default !== undefined ||
          param.AcceptThirdParty !== undefined ||
252
          param.RejectTracker !== undefined ||
253
254
255
256
257
          param.Locked) {
        const ACCEPT_COOKIES = 0;
        const REJECT_THIRD_PARTY_COOKIES = 1;
        const REJECT_ALL_COOKIES = 2;
        const REJECT_UNVISITED_THIRD_PARTY = 3;
258
        const REJECT_TRACKER = 4;
259
260
261
262
263

        let newCookieBehavior = ACCEPT_COOKIES;
        if (param.Default !== undefined && !param.Default) {
          newCookieBehavior = REJECT_ALL_COOKIES;
        } else if (param.AcceptThirdParty) {
264
          if (param.AcceptThirdParty == "never") {
265
266
267
268
            newCookieBehavior = REJECT_THIRD_PARTY_COOKIES;
          } else if (param.AcceptThirdParty == "from-visited") {
            newCookieBehavior = REJECT_UNVISITED_THIRD_PARTY;
          }
269
270
        } else if (param.RejectTracker !== undefined && param.RejectTracker) {
          newCookieBehavior = REJECT_TRACKER;
271
272
        }

273
        setDefaultPref("network.cookie.cookieBehavior", newCookieBehavior, param.Locked);
274
275
276
277
278
279
280
281
282
283
284
      }

      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;
        }

285
        setDefaultPref("network.cookie.lifetimePolicy", newLifetimePolicy, param.Locked);
286
      }
287
    },
288
289
  },

290
291
292
293
294
295
296
297
  "DefaultDownloadDirectory": {
    onBeforeAddons(manager, param) {
      setDefaultPref("browser.download.dir", replacePathVariables(param));
      // If a custom download directory is being used, just lock folder list to 2.
      setAndLockPref("browser.download.folderList", 2);
    },
  },

298
299
300
301
  "DisableAppUpdate": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("appUpdate");
302
      }
303
    },
304
305
  },

306
  "DisableBuiltinPDFViewer": {
307
    onBeforeAddons(manager, param) {
308
      if (param) {
309
        setAndLockPref("pdfjs.disabled", true);
310
      }
311
    },
312
313
  },

314
315
316
317
318
319
320
  "DisableDeveloperTools": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("devtools.policy.disabled", true);
        setAndLockPref("devtools.chrome.enabled", false);

        manager.disallowFeature("devtools");
321
322
323
        blockAboutPage(manager, "about:devtools");
        blockAboutPage(manager, "about:debugging");
        blockAboutPage(manager, "about:devtools-toolbox");
324
      }
325
    },
326
327
  },

328
329
330
331
332
  "DisableFeedbackCommands": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("feedbackCommands");
      }
333
    },
334
335
  },

336
337
338
339
340
  "DisableFirefoxAccounts": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("identity.fxaccounts.enabled", false);
      }
341
    },
342
343
  },

344
345
  "DisableFirefoxScreenshots": {
    onBeforeAddons(manager, param) {
346
      if (param) {
347
348
        setAndLockPref("extensions.screenshots.disabled", true);
      }
349
    },
350
351
  },

352
353
  "DisableFirefoxStudies": {
    onBeforeAddons(manager, param) {
354
      if (param) {
355
        manager.disallowFeature("Shield");
356
357
        setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
        setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
358
      }
359
    },
360
361
  },

362
363
364
  "DisableForgetButton": {
    onProfileAfterChange(manager, param) {
      if (param) {
365
        setAndLockPref("privacy.panicButton.enabled", false);
366
      }
367
    },
368
369
  },

370
371
  "DisableFormHistory": {
    onBeforeUIStartup(manager, param) {
372
      if (param) {
373
374
        setAndLockPref("browser.formfill.enable", false);
      }
375
    },
376
377
  },

378
379
380
381
382
  "DisableMasterPasswordCreation": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("createMasterPassword");
      }
383
    },
384
385
  },

386
387
388
389
390
  "DisablePocket": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("extensions.pocket.enabled", false);
      }
391
    },
392
393
  },

394
395
396
397
  "DisablePrivateBrowsing": {
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("privatebrowsing");
398
        blockAboutPage(manager, "about:privatebrowsing", true);
399
400
        setAndLockPref("browser.privatebrowsing.autostart", false);
      }
401
    },
402
403
  },

404
405
406
407
408
409
  "DisableProfileImport": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("profileImport");
        setAndLockPref("browser.newtabpage.activity-stream.migrationExpired", true);
      }
410
    },
411
412
  },

413
414
415
416
417
418
  "DisableProfileRefresh": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("profileRefresh");
        setAndLockPref("browser.disableResetPrompt", true);
      }
419
    },
420
421
  },

422
423
424
425
426
  "DisableSafeMode": {
    onBeforeUIStartup(manager, param) {
      if (param) {
        manager.disallowFeature("safeMode");
      }
427
    },
428
429
  },

430
431
  "DisableSecurityBypass": {
    onBeforeUIStartup(manager, param) {
432
433
434
435
      if ("InvalidCertificate" in param) {
        setAndLockPref("security.certerror.hideAddException", param.InvalidCertificate);
      }

436
437
438
      if ("SafeBrowsing" in param) {
        setAndLockPref("browser.safebrowsing.allowOverride", !param.SafeBrowsing);
      }
439
    },
440
441
  },

442
443
444
  "DisableSetDesktopBackground": {
    onBeforeUIStartup(manager, param) {
      if (param) {
445
        manager.disallowFeature("setDesktopBackground");
446
      }
447
    },
448
449
450
  },

  "DisableSystemAddonUpdate": {
451
452
453
454
    onBeforeAddons(manager, param) {
      if (param) {
        manager.disallowFeature("SysAddonUpdate");
      }
455
    },
456
457
  },

458
459
460
461
462
  "DisableTelemetry": {
    onBeforeAddons(manager, param) {
      if (param) {
        setAndLockPref("datareporting.healthreport.uploadEnabled", false);
        setAndLockPref("datareporting.policy.dataSubmissionEnabled", false);
463
        blockAboutPage(manager, "about:telemetry");
464
      }
465
    },
466
467
  },

468
  "DisplayBookmarksToolbar": {
469
    onBeforeUIStartup(manager, param) {
470
471
472
473
474
475
476
      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);
      });
477
    },
478
479
  },

480
  "DisplayMenuBar": {
481
    onBeforeUIStartup(manager, param) {
482
      let value = (!param).toString();
483
484
485
        // 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.
486
487
488
      runOncePerModification("displayMenuBar", value, () => {
        gXulStore.setValue(BROWSER_DOCUMENT_URL, "toolbar-menubar", "autohide", value);
      });
489
    },
490
491
  },

492
493
494
495
  "DNSOverHTTPS": {
    onBeforeAddons(manager, param) {
      if ("Enabled" in param) {
        let mode = param.Enabled ? 2 : 5;
496
        setDefaultPref("network.trr.mode", mode, param.Locked);
497
498
      }
      if (param.ProviderURL) {
499
        setDefaultPref("network.trr.uri", param.ProviderURL.href, param.Locked);
500
501
502
503
      }
    },
  },

504
  "DontCheckDefaultBrowser": {
505
    onBeforeUIStartup(manager, param) {
506
      setAndLockPref("browser.shell.checkDefaultBrowser", !param);
507
    },
508
509
  },

510
511
512
513
514
  "DownloadDirectory": {
    onBeforeAddons(manager, param) {
      setAndLockPref("browser.download.dir", replacePathVariables(param));
      // If a custom download directory is being used, just lock folder list to 2.
      setAndLockPref("browser.download.folderList", 2);
515
516
517
      // Per Chrome spec, user can't choose to download every time
      // if this is set.
      setAndLockPref("browser.download.useDownloadDir", true);
518
519
520
    },
  },

521
522
  "EnableTrackingProtection": {
    onBeforeUIStartup(manager, param) {
523
      if (param.Value) {
524
525
        setDefaultPref("privacy.trackingprotection.enabled", true, param.Locked);
        setDefaultPref("privacy.trackingprotection.pbmode.enabled", true, param.Locked);
526
      } else {
527
528
        setAndLockPref("privacy.trackingprotection.enabled", false);
        setAndLockPref("privacy.trackingprotection.pbmode.enabled", false);
529
      }
530
    },
531
532
  },

533
534
  "Extensions": {
    onBeforeUIStartup(manager, param) {
535
536
537
538
539
540
541
542
543
544
545
546
547
      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.
548
                log.debug(`Add-on ID (${addon.id}) couldn't be uninstalled.`);
549
550
551
552
553
              }
            }
          }
        });
      }
554
      if ("Install" in param) {
555
556
        runOncePerModification("extensionsInstall", JSON.stringify(param.Install), async () => {
          await uninstallingPromise;
557
          for (let location of param.Install) {
558
559
560
561
562
            let uri;
            try {
              uri = Services.io.newURI(location);
            } catch (e) {
              // If it's not a URL, it's probably a file path.
563
              // Assume location is a file path
564
              // This is done for legacy support (old API)
565
              try {
566
567
568
                let xpiFile = new FileUtils.File(location);
                uri = Services.io.newFileURI(xpiFile);
              } catch (ex) {
569
                log.error(`Invalid extension path location - ${location}`);
570
571
                return;
              }
572
573
            }
            installAddonFromURL(uri.spec);
574
575
576
577
578
          }
        });
      }
      if ("Locked" in param) {
        for (let ID of param.Locked) {
579
580
          manager.disallowFeature(`uninstall-extension:${ID}`);
          manager.disallowFeature(`disable-extension:${ID}`);
581
582
        }
      }
583
    },
584
585
  },

586
587
  "ExtensionSettings": {
    onBeforeAddons(manager, param) {
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
      try {
        manager.setExtensionSettings(param);
      } catch (e) {
       log.error("Invalid ExtensionSettings");
      }
    },
    async onBeforeUIStartup(manager, param) {
      let extensionSettings = param;
      let blockAllExtensions = false;
      if ("*" in extensionSettings) {
        if ("installation_mode" in extensionSettings["*"] &&
            extensionSettings["*"].installation_mode == "blocked") {
          blockAllExtensions = true;
          // Turn off discovery pane in about:addons
          setAndLockPref("extensions.getAddons.showPane", false);
          // Block about:debugging
          blockAboutPage(manager, "about:debugging");
        }
      }
      let {addons} = await AddonManager.getActiveAddons();
      let allowedExtensions = [];
      for (let extensionID in extensionSettings) {
        if (extensionID == "*") {
          // Ignore global settings
          continue;
        }
        if ("installation_mode" in extensionSettings[extensionID]) {
          if (extensionSettings[extensionID].installation_mode == "force_installed" ||
              extensionSettings[extensionID].installation_mode == "normal_installed") {
            if (!extensionSettings[extensionID].install_url) {
              throw new Error(`Missing install_url for ${extensionID}`);
            }
            if (!addons.find(addon => addon.id == extensionID)) {
              installAddonFromURL(extensionSettings[extensionID].install_url, extensionID);
            }
            manager.disallowFeature(`uninstall-extension:${extensionID}`);
            if (extensionSettings[extensionID].installation_mode == "force_installed") {
              manager.disallowFeature(`disable-extension:${extensionID}`);
            }
            allowedExtensions.push(extensionID);
          } else if (extensionSettings[extensionID].installation_mode == "allowed") {
            allowedExtensions.push(extensionID);
          } else if (extensionSettings[extensionID].installation_mode == "blocked") {
            if (addons.find(addon => addon.id == extensionID)) {
              // Can't use the addon from getActiveAddons since it doesn't have uninstall.
              let addon = await AddonManager.getAddonByID(extensionID);
              try {
                await addon.uninstall();
              } catch (e) {
                // This can fail for add-ons that can't be uninstalled.
                log.debug(`Add-on ID (${addon.id}) couldn't be uninstalled.`);
              }
            }
          }
        }
      }
      if (blockAllExtensions) {
        for (let addon of addons) {
          if (addon.isSystem || addon.isBuiltin) {
            continue;
          }
          if (!allowedExtensions.includes(addon.id)) {
            try {
              // Can't use the addon from getActiveAddons since it doesn't have uninstall.
              let addonToUninstall = await AddonManager.getAddonByID(addon.id);
              await addonToUninstall.uninstall();
            } catch (e) {
              // This can fail for add-ons that can't be uninstalled.
              log.debug(`Add-on ID (${addon.id}) couldn't be uninstalled.`);
            }
          }
        }
      }
661
662
663
    },
  },

664
665
666
667
668
669
670
671
  "ExtensionUpdate": {
    onBeforeAddons(manager, param) {
      if (!param) {
        setAndLockPref("extensions.update.enabled", param);
      }
    },
  },

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
  "FirefoxHome": {
    onBeforeAddons(manager, param) {
      let locked = param.Locked || false;
      if ("Search" in param) {
        setDefaultPref("browser.newtabpage.activity-stream.showSearch", param.Search, locked);
      }
      if ("TopSites" in param) {
        setDefaultPref("browser.newtabpage.activity-stream.feeds.topsites", param.TopSites, locked);
      }
      if ("Highlights" in param) {
        setDefaultPref("browser.newtabpage.activity-stream.feeds.section.highlights", param.Highlights, locked);
      }
      if ("Pocket" in param) {
        setDefaultPref("browser.newtabpage.activity-stream.feeds.section.topstories", param.Pocket, locked);
      }
      if ("Snippets" in param) {
        setDefaultPref("browser.newtabpage.activity-stream.feeds.snippets", param.Snippets, locked);
      }
    },
  },

693
  "FlashPlugin": {
694
    onBeforeUIStartup(manager, param) {
695
      addAllowDenyPermissions("plugin:flash", param.Allow, param.Block);
696
697
698

      const FLASH_NEVER_ACTIVATE = 0;
      const FLASH_ASK_TO_ACTIVATE = 1;
699
      const FLASH_ALWAYS_ACTIVATE = 2;
700
701

      let flashPrefVal;
702
      if (param.Default === undefined) {
703
        flashPrefVal = FLASH_ASK_TO_ACTIVATE;
704
705
      } else if (param.Default) {
        flashPrefVal = FLASH_ALWAYS_ACTIVATE;
706
707
708
709
710
711
712
713
      } else {
        flashPrefVal = FLASH_NEVER_ACTIVATE;
      }
      if (param.Locked) {
        setAndLockPref("plugin.state.flash", flashPrefVal);
      } else if (param.Default !== undefined) {
        setDefaultPref("plugin.state.flash", flashPrefVal);
      }
714
    },
715
716
  },

717
718
719
720
721
  "HardwareAcceleration": {
    onBeforeAddons(manager, param) {
      if (!param) {
        setAndLockPref("layers.acceleration.disabled", true);
      }
722
    },
723
724
  },

725
726
727
728
729
  "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.
730
731
732
733
734
      if (param.URL) {
        let homepages = param.URL.href;
        if (param.Additional && param.Additional.length > 0) {
          homepages += "|" + param.Additional.map(url => url.href).join("|");
        }
735
        setDefaultPref("browser.startup.homepage", homepages, param.Locked);
736
737
738
739
740
741
742
743
744
        if (param.Locked) {
          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 {
          runOncePerModification("setHomepage", homepages, () => {
            Services.prefs.clearUserPref("browser.startup.homepage");
          });
        }
745
      }
746
747
748
749
750
751
752
753
754
755
756
757
758
      if (param.StartPage) {
        let prefValue;
        switch (param.StartPage) {
          case "none":
            prefValue = 0;
            break;
          case "homepage":
            prefValue = 1;
            break;
          case "previous-session":
            prefValue = 3;
            break;
        }
759
        setDefaultPref("browser.startup.page", prefValue, param.Locked);
760
      }
761
    },
762
763
  },

764
  "InstallAddonsPermission": {
765
    onBeforeUIStartup(manager, param) {
766
767
768
769
770
      if ("Allow" in param) {
        addAllowDenyPermissions("install", param.Allow, null);
      }
      if ("Default" in param) {
        setAndLockPref("xpinstall.enabled", param.Default);
771
        if (!param.Default) {
772
          blockAboutPage(manager, "about:debugging");
773
774
          setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
          setAndLockPref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
775
          manager.disallowFeature("xpinstall");
776
        }
777
      }
778
    },
779
780
  },

781
782
783
784
785
786
787
788
789
790
791
  "LocalFileLinks": {
    onBeforeAddons(manager, param) {
      // If there are existing capabilities, lock them with the policy pref.
      let policyNames = Services.prefs.getCharPref("capability.policy.policynames", "").split(" ");
      policyNames.push("localfilelinks_policy");
      setAndLockPref("capability.policy.policynames", policyNames.join(" "));
      setAndLockPref("capability.policy.localfilelinks_policy.checkloaduri.enabled", "allAccess");
      setAndLockPref("capability.policy.localfilelinks_policy.sites", param.join(" "));
    },
  },

792
793
794
795
796
797
798
  "NetworkPrediction": {
    onBeforeAddons(manager, param) {
      setAndLockPref("network.dns.disablePrefetch", !param);
      setAndLockPref("network.dns.disablePrefetchFromHTTPS", !param);
    },
  },

799
800
801
802
803
804
  "NewTabPage": {
    onBeforeAddons(manager, param) {
      setAndLockPref("browser.newtabpage.enabled", param);
    },
  },

805
806
807
808
809
  "NoDefaultBookmarks": {
    onProfileAfterChange(manager, param) {
      if (param) {
        manager.disallowFeature("defaultBookmarks");
      }
810
    },
811
812
  },

813
814
815
  "OfferToSaveLogins": {
    onBeforeUIStartup(manager, param) {
      setAndLockPref("signon.rememberSignons", param);
816
    },
817
818
  },

819
820
  "OverrideFirstRunPage": {
    onProfileAfterChange(manager, param) {
821
      let url = param ? param.href : "";
822
      setAndLockPref("startup.homepage_welcome_url", url);
823
    },
824
825
  },

826
827
  "OverridePostUpdatePage": {
    onProfileAfterChange(manager, param) {
828
      let url = param ? param.href : "";
829
830
831
832
833
      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");
834
    },
835
836
  },

837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
  "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);
      }
858
    },
859
860
  },

861
  "PopupBlocking": {
862
    onBeforeUIStartup(manager, param) {
863
      addAllowDenyPermissions("popup", param.Allow, null);
864
865
866
867
868
869
870
871
872
873

      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);
      }
874
    },
875
876
  },

877
878
879
880
881
882
883
884
  "Preferences": {
    onBeforeAddons(manager, param) {
      for (let preference in param) {
        setAndLockPref(preference, param[preference]);
      }
    },
  },

885
886
887
888
889
890
  "PromptForDownloadLocation": {
    onBeforeAddons(manager, param) {
      setAndLockPref("browser.download.useDownloadDir", !param);
    },
  },

891
892
893
894
895
896
897
898
  "Proxy": {
    onBeforeAddons(manager, param) {
      if (param.Locked) {
        manager.disallowFeature("changeProxySettings");
        ProxyPolicies.configureProxySettings(param, setAndLockPref);
      } else {
        ProxyPolicies.configureProxySettings(param, setDefaultPref);
      }
899
    },
900
  },
901

902
903
  "RequestedLocales": {
    onBeforeAddons(manager, param) {
904
905
906
907
908
      if (Array.isArray(param)) {
        Services.locale.requestedLocales = param;
      } else {
        Services.locale.requestedLocales = param.split(",");
      }
909
910
911
    },
  },

912
913
  "SanitizeOnShutdown": {
    onBeforeUIStartup(manager, param) {
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
      if (typeof param === "boolean") {
        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);
        }
      } else {
        setAndLockPref("privacy.sanitize.sanitizeOnShutdown", true);
        if ("Cache" in param) {
          setAndLockPref("privacy.clearOnShutdown.cache", param.Cache);
        } else {
          setAndLockPref("privacy.clearOnShutdown.cache", false);
        }
        if ("Cookies" in param) {
          setAndLockPref("privacy.clearOnShutdown.cookies", param.Cookies);
        } else {
          setAndLockPref("privacy.clearOnShutdown.cookies", false);
        }
        if ("Downloads" in param) {
          setAndLockPref("privacy.clearOnShutdown.downloads", param.Downloads);
        } else {
          setAndLockPref("privacy.clearOnShutdown.downloads", false);
        }
        if ("FormData" in param) {
          setAndLockPref("privacy.clearOnShutdown.formdata", param.FormData);
        } else {
          setAndLockPref("privacy.clearOnShutdown.formdata", false);
        }
        if ("History" in param) {
          setAndLockPref("privacy.clearOnShutdown.history", param.History);
        } else {
          setAndLockPref("privacy.clearOnShutdown.history", false);
        }
        if ("Sessions" in param) {
          setAndLockPref("privacy.clearOnShutdown.sessions", param.Sessions);
        } else {
          setAndLockPref("privacy.clearOnShutdown.sessions", false);
        }
        if ("SiteSettings" in param) {
          setAndLockPref("privacy.clearOnShutdown.siteSettings", param.SiteSettings);
        }
        if ("OfflineApps" in param) {
          setAndLockPref("privacy.clearOnShutdown.offlineApps", param.OfflineApps);
        }
964
      }
965
    },
966
967
  },

968
969
970
971
972
973
974
975
976
977
978
979
980
  "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");
        }
      });
981
    },
982
983
  },

984
  "SearchEngines": {
985
986
987
988
989
    onBeforeUIStartup(manager, param) {
      if (param.PreventInstalls) {
        manager.disallowFeature("installSearchEngine", true);
      }
    },
990
    onAllWindowsRestored(manager, param) {
991
      Services.search.init().then(async () => {
992
993
        if (param.Remove) {
          // Only rerun if the list of engine names has changed.
994
995
996
          await runOncePerModification("removeSearchEngines",
                                       JSON.stringify(param.Remove),
                                       async function() {
997
998
999
1000
            for (let engineName of param.Remove) {
              let engine = Services.search.getEngineByName(engineName);
              if (engine) {
                try {