summaryrefslogtreecommitdiffstats
path: root/browser/components/attribution/ProvenanceData.sys.mjs
blob: 128b0214aa6f08280c3e6b0028f09f20e7f91cd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/* 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/. */

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  AttributionIOUtils: "resource:///modules/AttributionCode.sys.mjs",
});

let gReadZoneIdPromise = null;
let gTelemetryPromise = null;

export var ProvenanceData = {
  /**
   * Clears cached code/Promises. For testing only.
   */
  _clearCache() {
    if (Services.env.exists("XPCSHELL_TEST_PROFILE_DIR")) {
      gReadZoneIdPromise = null;
      gTelemetryPromise = null;
    }
  },

  /**
   * Returns an nsIFile for the file containing the zone identifier-based
   * provenance data. This currently only exists on Windows. On other platforms,
   * this will return null.
   */
  get zoneIdProvenanceFile() {
    if (AppConstants.platform == "win") {
      let file = Services.dirsvc.get("GreD", Ci.nsIFile);
      file.append("zoneIdProvenanceData");
      return file;
    }
    return null;
  },

  /**
   * Loads the provenance data that the installer copied (along with some
   * metadata) from the Firefox installer used to create the current
   * installation.
   *
   * If it doesn't already exist, creates a global Promise that loads the data
   * from the file and caches it. Subsequent calls get the same Promise. There
   * is no support for re-reading the file from the disk because there is no
   * good reason that the contents of the file should change.
   *
   * Only expected contents will be pulled out of the file. This does not
   * extract arbitrary, unexpected data. Data will be validated, to the extent
   * possible. Most possible data returned has a potential key indicating that
   * we read an unexpected value out of the file.
   *
   * @returns `null` on unsupported OSs. Otherwise, an object with these
   *          possible keys:
   *    `readProvenanceError`
   *      Will be present if there was a problem when Firefox tried to read the
   *      file that ought to have been written by the installer. Possible values
   *      are:
   *        `noSuchFile`, `readError`, `parseError`
   *      If this key is present, no other keys will be present.
   *    `fileSystem`
   *      What filesystem the installer was on. If available, this will be a
   *      string returned from `GetVolumeInformationByHandleW` via its
   *      `lpFileSystemNameBuffer` parameter. Possible values are:
   *        `NTFS`, `FAT32`, `other`, `missing`, `readIniError`
   *      `other` will be used if the value read does not match one of the
   *      expected file systems.
   *      `missing` will be used if the file didn't contain `fileSystem` or
   *      `readFsError` information.
   *      `readIniError` will be used if an error is encountered when reading
   *      the key from the file in the installation directory.
   *    `readFsError`
   *      The reason why the installer file system could not be determined. Will
   *      be present if `readProvenanceError` and `fileSystem` are not. Possible
   *      values are:
   *        `openFile`, `getVolInfo`, `fsUnterminated`, `getBufferSize`,
   *        `convertString`, `unexpected`, `readIniError`
   *      `unexpected` will be used if the value read from the file didn't match
   *      any of the expected values, for some reason.
   *      `missing` will be used if the file didn't contain `fileSystem` or
   *      `readFsError` information.
   *      `readIniError` will be used if an error is encountered when reading
   *      the key from the file in the installation directory.
   *    `readFsErrorCode`
   *      An integer returned by `GetLastError()` indicating, in more detail,
   *      why we failed to obtain the file system. This key may exist if
   *      `readFsError` exists.
   *    `readZoneIdError`
   *      The reason why the installer was unable to read its zone identifier
   *      ADS. Possible values are:
   *        `openFile`, `readFile`, `unexpected`, `readIniError`
   *      `unexpected` will be used if the value read from the file didn't match
   *      any of the expected values, for some reason.
   *      `readIniError` will be used if an error is encountered when reading
   *      the key from the file in the installation directory.
   *    `readZoneIdErrorCode`
   *      An integer returned by `GetLastError()` indicating, in more detail,
   *      why we failed to read the zone identifier ADS. This key may exist if
   *      `readZoneIdError` exists.
   *    `zoneIdFileSize`
   *      This key should exist if Firefox successfully read the file in the
   *      installation directory and the installer successfully opened the ADS.
   *      If the installer failed to get the size of the ADS prior to reading
   *      it, this will be `unknown`. If the installer was able to get the ADS
   *      size, this will be an integer describing how many bytes long it was.
   *      If this value in installation directory's file isn't `unknown` or an
   *      integer, this will be `unexpected`. If an error is encountered when
   *      reading the key from the file in the installation directory, this will
   *      be `readIniError`.
   *    `zoneIdBufferLargeEnough`
   *      This key should exist if Firefox successfully read the file in the
   *      installation directory and the installer successfully opened the ADS.
   *      Indicates whether the zone identifier ADS size was bigger than the
   *      maximum size that the installer will read from it. If we failed to
   *      determine the ADS size, this will be `unknown`. If the installation
   *      directory's file contains an invalid value, this will be `unexpected`.
   *      If an error is encountered when reading the key from the file in the
   *      installation directory, this will be `readIniError`.
   *      Otherwise, this will be a boolean indicating whether or not the buffer
   *      was large enough to fit the ADS data into.
   *    `zoneIdTruncated`
   *      This key should exist if Firefox successfully read the file in the
   *      installation directory and the installer successfully read the ADS.
   *      Indicates whether or not we read through the end of the ADS data when
   *      we copied it. If the installer failed to determine this, this value
   *      will be `unknown`. If the installation directory's file contains an
   *      invalid value, this will be `unexpected`. If an error is encountered
   *      when reading the key from the file in the installation directory, this
   *      will be `readIniError`. Otherwise, this will be a boolean value
   *      indicating whether or not the data that we copied was truncated.
   *    `zoneId`
   *      The Security Zone that the Zone Identifier data indicates that
   *      installer was downloaded from. See this documentation:
   *      https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms537183(v=vs.85)
   *      This key will be present if `readProvenanceError` and
   *      `readZoneIdError` are not. It will either be a valid zone ID (an
   *      integer between 0 and 4, inclusive), or else it will be `unexpected`,
   *      `missing`, or `readIniError`.
   *    `referrerUrl`
   *      The URL of the download referrer. This key will be present if
   *      `readProvenanceError` and `readZoneIdError` are not. It will either be
   *      a `URL` object, or else it will be `unexpected`, `missing`, or
   *      `readIniError`.
   *    `referrerUrlIsMozilla`
   *      This key will be present if `ReferrerUrl` is a `URL` object. It will
   *      be `true`` if the download referrer appears to be a Mozilla URL.
   *      Otherwise it will be `false`.
   *    `hostUrl`
   *      The URL of the download source. This key will be present if
   *      `readProvenanceError` and `readZoneIdError` are not. It will either be
   *      a `URL` object, or else it will be `unexpected`, `missing`, or
   *      `readIniError`
   *    `hostUrlIsMozilla`
   *      This key will be present if `HostUrl` is a `URL` object. It will
   *      be `true`` if the download source appears to be a Mozilla URL.
   *      Otherwise it will be `false`.
   */
  async readZoneIdProvenanceFile() {
    if (gReadZoneIdPromise) {
      return gReadZoneIdPromise;
    }
    gReadZoneIdPromise = (async () => {
      let file = this.zoneIdProvenanceFile;
      if (!file) {
        return null;
      }
      let iniData;
      try {
        iniData = await lazy.AttributionIOUtils.readUTF8(file.path);
      } catch (ex) {
        if (DOMException.isInstance(ex) && ex.name == "NotFoundError") {
          return { readProvenanceError: "noSuchFile" };
        }
        return { readProvenanceError: "readError" };
      }

      let ini;
      try {
        // We would rather use asynchronous I/O, so we are going to read the
        // file with IOUtils and then pass the result into the INI parser
        // rather than just giving the INI parser factory the file.
        ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"]
          .getService(Ci.nsIINIParserFactory)
          .createINIParser(null);
        ini.initFromString(iniData);
      } catch (ex) {
        return { readProvenanceError: "parseError" };
      }

      const unexpectedValueError = "unexpected";
      const missingKeyError = "missing";
      const readIniError = "readIniError";
      const possibleIniErrors = [missingKeyError, readIniError];

      // Format is {"IniSectionName": {"IniKeyName": "IniValue"}}
      let iniValues = {
        Mozilla: {
          fileSystem: null,
          readFsError: null,
          readFsErrorCode: null,
          readZoneIdError: null,
          readZoneIdErrorCode: null,
          zoneIdFileSize: null,
          zoneIdBufferLargeEnough: null,
          zoneIdTruncated: null,
        },
        ZoneTransfer: {
          ZoneId: null,
          ReferrerUrl: null,
          HostUrl: null,
        },
      };

      // The ini reader interface is a little weird in that if we just try to
      // read a value from a known section/key and the section/key doesn't
      // exist, we just get a generic error rather than an indication that
      // the section/key doesn't exist. To distinguish missing keys from any
      // other potential errors, we are going to enumerate the sections and
      // keys use that to determine if we should try to read from them.
      let existingSections;
      try {
        existingSections = Array.from(ini.getSections());
      } catch (ex) {
        return { readProvenanceError: "parseError" };
      }
      for (const section in iniValues) {
        if (!existingSections.includes(section)) {
          for (const key in iniValues[section]) {
            iniValues[section][key] = missingKeyError;
          }
          continue;
        }

        let existingKeys;
        try {
          existingKeys = Array.from(ini.getKeys(section));
        } catch (ex) {
          for (const key in iniValues[section]) {
            iniValues[section][key] = readIniError;
          }
          continue;
        }

        for (const key in iniValues[section]) {
          if (!existingKeys.includes(key)) {
            iniValues[section][key] = missingKeyError;
            continue;
          }

          let value;
          try {
            value = ini.getString(section, key).trim();
          } catch (ex) {
            value = readIniError;
          }
          iniValues[section][key] = value;
        }
      }

      // This helps with how verbose the validation gets.
      const fileSystem = iniValues.Mozilla.fileSystem;
      const readFsError = iniValues.Mozilla.readFsError;
      const readFsErrorCode = iniValues.Mozilla.readFsErrorCode;
      const readZoneIdError = iniValues.Mozilla.readZoneIdError;
      const readZoneIdErrorCode = iniValues.Mozilla.readZoneIdErrorCode;
      const zoneIdFileSize = iniValues.Mozilla.zoneIdFileSize;
      const zoneIdBufferLargeEnough = iniValues.Mozilla.zoneIdBufferLargeEnough;
      const zoneIdTruncated = iniValues.Mozilla.zoneIdTruncated;
      const zoneId = iniValues.ZoneTransfer.ZoneId;
      const referrerUrl = iniValues.ZoneTransfer.ReferrerUrl;
      const hostUrl = iniValues.ZoneTransfer.HostUrl;

      let returnObject = {};

      // readFsError, readFsErrorCode, fileSystem
      const validReadFsErrors = [
        "openFile",
        "getVolInfo",
        "fsUnterminated",
        "getBufferSize",
        "convertString",
      ];
      // These must be upper case
      const validFileSystemValues = ["NTFS", "FAT32"];
      if (fileSystem == missingKeyError && readFsError != missingKeyError) {
        if (
          possibleIniErrors.includes(readFsError) ||
          validReadFsErrors.includes(readFsError)
        ) {
          returnObject.readFsError = readFsError;
        } else {
          returnObject.readFsError = unexpectedValueError;
        }
        if (readFsErrorCode != missingKeyError) {
          let code = parseInt(readFsErrorCode, 10);
          if (!isNaN(code)) {
            returnObject.readFsErrorCode = code;
          }
        }
      } else if (possibleIniErrors.includes(fileSystem)) {
        returnObject.fileSystem = fileSystem;
      } else if (validFileSystemValues.includes(fileSystem.toUpperCase())) {
        returnObject.fileSystem = fileSystem.toUpperCase();
      } else {
        returnObject.fileSystem = "other";
      }

      // zoneIdFileSize
      if (zoneIdFileSize == missingKeyError) {
        // We don't include this one if it's missing.
      } else if (
        zoneIdFileSize == readIniError ||
        zoneIdFileSize == "unknown"
      ) {
        returnObject.zoneIdFileSize = zoneIdFileSize;
      } else {
        let size = parseInt(zoneIdFileSize, 10);
        if (isNaN(size)) {
          returnObject.zoneIdFileSize = unexpectedValueError;
        } else {
          returnObject.zoneIdFileSize = size;
        }
      }

      // zoneIdBufferLargeEnough
      if (zoneIdBufferLargeEnough == missingKeyError) {
        // We don't include this one if it's missing.
      } else if (
        zoneIdBufferLargeEnough == readIniError ||
        zoneIdBufferLargeEnough == "unknown"
      ) {
        returnObject.zoneIdBufferLargeEnough = zoneIdBufferLargeEnough;
      } else if (zoneIdBufferLargeEnough.toLowerCase() == "true") {
        returnObject.zoneIdBufferLargeEnough = true;
      } else if (zoneIdBufferLargeEnough.toLowerCase() == "false") {
        returnObject.zoneIdBufferLargeEnough = false;
      } else {
        returnObject.zoneIdBufferLargeEnough = unexpectedValueError;
      }

      // zoneIdTruncated
      if (zoneIdTruncated == missingKeyError) {
        // We don't include this one if it's missing.
      } else if (
        zoneIdTruncated == readIniError ||
        zoneIdTruncated == "unknown"
      ) {
        returnObject.zoneIdTruncated = zoneIdTruncated;
      } else if (zoneIdTruncated.toLowerCase() == "true") {
        returnObject.zoneIdTruncated = true;
      } else if (zoneIdTruncated.toLowerCase() == "false") {
        returnObject.zoneIdTruncated = false;
      } else {
        returnObject.zoneIdTruncated = unexpectedValueError;
      }

      // readZoneIdError, readZoneIdErrorCode, zoneId, referrerUrl, hostUrl,
      // referrerUrlIsMozilla, hostUrlIsMozilla
      const validReadZoneIdErrors = ["openFile", "readFile"];
      if (
        readZoneIdError != missingKeyError &&
        zoneId == missingKeyError &&
        referrerUrl == missingKeyError &&
        hostUrl == missingKeyError
      ) {
        if (
          possibleIniErrors.includes(readZoneIdError) ||
          validReadZoneIdErrors.includes(readZoneIdError)
        ) {
          returnObject.readZoneIdError = readZoneIdError;
        } else {
          returnObject.readZoneIdError = unexpectedValueError;
        }
        if (readZoneIdErrorCode != missingKeyError) {
          let code = parseInt(readZoneIdErrorCode, 10);
          if (!isNaN(code)) {
            returnObject.readZoneIdErrorCode = code;
          }
        }
      } else {
        if (possibleIniErrors.includes(zoneId)) {
          returnObject.zoneId = zoneId;
        } else {
          let id = parseInt(zoneId, 10);
          if (isNaN(id) || id < 0 || id > 4) {
            returnObject.zoneId = unexpectedValueError;
          } else {
            returnObject.zoneId = id;
          }
        }

        let isMozillaURL = url => {
          const mozillaDomains = ["mozilla.com", "mozilla.net", "mozilla.org"];
          for (const domain of mozillaDomains) {
            if (url.hostname == domain) {
              return true;
            }
            if (url.hostname.endsWith("." + domain)) {
              return true;
            }
          }
          return false;
        };

        if (possibleIniErrors.includes(referrerUrl)) {
          returnObject.referrerUrl = referrerUrl;
        } else {
          try {
            returnObject.referrerUrl = new URL(referrerUrl);
          } catch (ex) {
            returnObject.referrerUrl = unexpectedValueError;
          }
          if (URL.isInstance(returnObject.referrerUrl)) {
            returnObject.referrerUrlIsMozilla = isMozillaURL(
              returnObject.referrerUrl
            );
          }
        }

        if (possibleIniErrors.includes(hostUrl)) {
          returnObject.hostUrl = hostUrl;
        } else {
          try {
            returnObject.hostUrl = new URL(hostUrl);
          } catch (ex) {
            returnObject.hostUrl = unexpectedValueError;
          }
          if (URL.isInstance(returnObject.hostUrl)) {
            returnObject.hostUrlIsMozilla = isMozillaURL(returnObject.hostUrl);
          }
        }
      }

      return returnObject;
    })();
    return gReadZoneIdPromise;
  },

  /**
   * Only submits telemetry once, no matter how many times it is called.
   * Has no effect on OSs where provenance data is not supported.
   *
   * @returns An object indicating the values submitted. Keys may not match the
   *          Scalar names since the returned object is intended to be suitable
   *          for use as a Telemetry Event's `extra` object, which has shorter
   *          limits for extra key names than the limits for Scalar names.
   *          Values will be converted to strings since Telemetry Event's
   *          `extra` objects must have string values.
   *          On platforms that do not support provenance data, this will always
   *          return an empty object.
   */
  async submitProvenanceTelemetry() {
    if (gTelemetryPromise) {
      return gTelemetryPromise;
    }
    gTelemetryPromise = (async () => {
      const errorValue = "error";

      let extra = {};

      let provenance = await this.readZoneIdProvenanceFile();
      if (!provenance) {
        return extra;
      }

      let setTelemetry = (scalarName, extraKey, value) => {
        Services.telemetry.scalarSet(scalarName, value);
        extra[extraKey] = value.toString();
      };

      setTelemetry(
        "attribution.provenance.data_exists",
        "data_exists",
        !provenance.readProvenanceError
      );
      if (provenance.readProvenanceError) {
        return extra;
      }

      setTelemetry(
        "attribution.provenance.file_system",
        "file_system",
        provenance.fileSystem ?? errorValue
      );

      // https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-#ERROR_FILE_NOT_FOUND
      const ERROR_FILE_NOT_FOUND = 2;

      let ads_exists =
        !provenance.readProvenanceError &&
        !(
          provenance.readZoneIdError == "openFile" &&
          provenance.readZoneIdErrorCode == ERROR_FILE_NOT_FOUND
        );
      setTelemetry(
        "attribution.provenance.ads_exists",
        "ads_exists",
        ads_exists
      );
      if (!ads_exists) {
        return extra;
      }

      setTelemetry(
        "attribution.provenance.security_zone",
        "security_zone",
        "zoneId" in provenance ? provenance.zoneId.toString() : errorValue
      );

      let haveReferrerUrl = URL.isInstance(provenance.referrerUrl);
      setTelemetry(
        "attribution.provenance.referrer_url_exists",
        "refer_url_exist",
        haveReferrerUrl
      );
      if (haveReferrerUrl) {
        setTelemetry(
          "attribution.provenance.referrer_url_is_mozilla",
          "refer_url_moz",
          provenance.referrerUrlIsMozilla
        );
      }

      let haveHostUrl = URL.isInstance(provenance.hostUrl);
      setTelemetry(
        "attribution.provenance.host_url_exists",
        "host_url_exist",
        haveHostUrl
      );
      if (haveHostUrl) {
        setTelemetry(
          "attribution.provenance.host_url_is_mozilla",
          "host_url_moz",
          provenance.hostUrlIsMozilla
        );
      }

      return extra;
    })();
    return gTelemetryPromise;
  },
};