summaryrefslogtreecommitdiffstats
path: root/comm/mail/extensions/openpgp/content/modules/keyObj.jsm
blob: ed9137cb3a0fa154f2a8fd8e51a1ead559b1f30a (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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
 * 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";

var EXPORTED_SYMBOLS = ["newEnigmailKeyObj"];

/**
 This module implements the EnigmailKeyObj class with the following members:

  - keyId           - 16 digits (8-byte) public key ID (/not/ preceded with 0x)
  - userId          - main user ID
  - fpr             - fingerprint
  - fprFormatted    - a formatted version of the fingerprint following the scheme .... .... ....
  - expiry          - Expiry date as printable string
  - expiryTime      - Expiry time as seconds after 01/01/1970
  - created         - Key creation date as printable string
  - keyCreated      - Key creation date/time as number
  - keyTrust        - key trust code as provided by GnuPG (calculated key validity)
  - keyUseFor       - key usage type as provided by GnuPG (key capabilities)
  - ownerTrust      - owner trust as provided by GnuPG
  - photoAvailable  - [Boolean] true if photo is available
  - secretAvailable - [Boolean] true if secret key is available
  - algoSym         - public key algorithm type (String, e.g. RSA)
  - keySize         - size of public key
  - type            - "pub" or "grp"
  - userIds  - [Array]: - Contains ALL UIDs (including the primary UID)
                    * userId     - User ID
                    * keyTrust   - trust level of user ID
                    * uidFpr     - fingerprint of the user ID
                    * type       - one of "uid" (regular user ID), "uat" (photo)
                    * uatNum     - photo number (starting with 0 for each key)
  - subKeys     - [Array]:
                    * keyId      - subkey ID (16 digits (8-byte))
                    * expiry     - Expiry date as printable string
                    * expiryTime - Expiry time as seconds after 01/01/1970
                    * created    - Subkey creation date as printable string
                    * keyCreated - Subkey creation date/time as number
                    * keyTrust   - key trust code as provided by GnuPG
                    * keyUseFor  - key usage type as provided by GnuPG
                    * algoSym    - subkey algorithm type (String, e.g. RSA)
                    * keySize    - subkey size
                    * type       -  "sub"

  - methods:
     * hasSubUserIds
     * getKeyExpiry
     * getEncryptionValidity
     * getSigningValidity
     * getPubKeyValidity
     * clone
     * getMinimalPubKey
     * getVirtualKeySize
*/

const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

XPCOMUtils.defineLazyModuleGetters(lazy, {
  EnigmailCryptoAPI: "chrome://openpgp/content/modules/cryptoAPI.jsm",
  EnigmailFuncs: "chrome://openpgp/content/modules/funcs.jsm",
  EnigmailKey: "chrome://openpgp/content/modules/key.jsm",
  EnigmailLog: "chrome://openpgp/content/modules/log.jsm",
});

XPCOMUtils.defineLazyGetter(lazy, "l10n", () => {
  return new Localization(["messenger/openpgp/openpgp.ftl"], true);
});

function newEnigmailKeyObj(keyData) {
  return new EnigmailKeyObj(keyData);
}

class EnigmailKeyObj {
  constructor(keyData) {
    this.keyId = "";
    this.expiry = "";
    this.expiryTime = 0;
    this.created = "";
    this.keyTrust = "";
    this.keyUseFor = "";
    this.ownerTrust = "";
    this.algoSym = "";
    this.keySize = "";
    this.userId = "";
    this.userIds = [];
    this.subKeys = [];
    this.fpr = "";
    this.minimalKeyBlock = [];
    this.photoAvailable = false;
    this.secretAvailable = false;
    this.secretMaterial = false;

    this.type = keyData.type;
    if ("keyId" in keyData) {
      this.keyId = keyData.keyId;
    }
    if ("expiryTime" in keyData) {
      this.expiryTime = keyData.expiryTime;
      this.expiry = keyData.expiryTime
        ? new Services.intl.DateTimeFormat().format(
            new Date(keyData.expiryTime * 1000)
          )
        : "";
    }
    if ("effectiveExpiryTime" in keyData) {
      this.effectiveExpiryTime = keyData.effectiveExpiryTime;
      this.effectiveExpiry = keyData.effectiveExpiryTime
        ? new Services.intl.DateTimeFormat().format(
            new Date(keyData.effectiveExpiryTime * 1000)
          )
        : "";
    }

    const ATTRS = [
      "created",
      "keyCreated",
      "keyTrust",
      "keyUseFor",
      "ownerTrust",
      "algoSym",
      "keySize",
      "userIds",
      "subKeys",
      "fpr",
      "secretAvailable",
      "secretMaterial",
      "photoAvailable",
      "userId",
      "hasIgnoredAttributes",
    ];
    for (let i of ATTRS) {
      if (i in keyData) {
        this[i] = keyData[i];
      }
    }
  }

  /**
   * create a copy of the object
   */
  clone() {
    let cp = new EnigmailKeyObj(["copy"]);
    for (let i in this) {
      if (i !== "fprFormatted") {
        if (typeof this[i] !== "function") {
          if (typeof this[i] === "object") {
            cp[i] = lazy.EnigmailFuncs.cloneObj(this[i]);
          } else {
            cp[i] = this[i];
          }
        }
      }
    }

    return cp;
  }

  /**
   * Does the key have secondary user IDs?
   *
   * @return: Boolean - true if yes; false if no
   */
  hasSubUserIds() {
    let nUid = 0;
    for (let i in this.userIds) {
      if (this.userIds[i].type === "uid") {
        ++nUid;
      }
    }

    return nUid >= 2;
  }

  /**
   * Get a formatted version of the fingerprint:
   * 1234 5678 90AB CDEF .... ....
   *
   * @returns String - the formatted fingerprint
   */
  get fprFormatted() {
    let f = lazy.EnigmailKey.formatFpr(this.fpr);
    if (f.length === 0) {
      f = this.fpr;
    }
    return f;
  }

  /**
   * Determine if the public key is valid. If not, return a description why it's not
   *
   * @returns Object:
   *   - keyValid: Boolean (true if key is valid)
   *   - reason: String (explanation of invalidity)
   */
  getPubKeyValidity(exceptionReason = null) {
    let retVal = {
      keyValid: false,
      reason: "",
    };
    if (this.keyTrust.search(/r/i) >= 0) {
      // public key revoked
      retVal.reason = lazy.l10n.formatValueSync("key-ring-pub-key-revoked", {
        userId: this.userId,
        keyId: "0x" + this.keyId,
      });
    } else if (
      exceptionReason != "ignoreExpired" &&
      this.keyTrust.search(/e/i) >= 0
    ) {
      // public key expired
      retVal.reason = lazy.l10n.formatValueSync("key-ring-pub-key-expired", {
        userId: this.userId,
        keyId: "0x" + this.keyId,
      });
    } else {
      retVal.keyValid = true;
    }

    return retVal;
  }

  /**
   * Check whether a key can be used for signing and return a description of why not
   *
   * @returns Object:
   *   - keyValid: Boolean (true if key is valid)
   *   - reason: String (explanation of invalidity)
   */
  getSigningValidity(exceptionReason = null) {
    let retVal = this.getPubKeyValidity(exceptionReason);

    if (!retVal.keyValid) {
      return retVal;
    }

    if (!this.secretAvailable) {
      retVal.keyValid = false;
      retVal.reason = lazy.l10n.formatValueSync("key-ring-no-secret-key", {
        userId: this.userId,
        keyId: "0x" + this.keyId,
      });
      return retVal;
    }

    if (/s/.test(this.keyUseFor) && this.secretMaterial) {
      return retVal;
    }

    retVal.keyValid = false;
    let expired = 0;
    let revoked = 0;
    let found = 0;
    let noSecret = 0;

    for (let sk in this.subKeys) {
      if (this.subKeys[sk].keyUseFor.search(/s/) >= 0) {
        if (
          this.subKeys[sk].keyTrust.search(/e/i) >= 0 &&
          exceptionReason != "ignoreExpired"
        ) {
          ++expired;
        } else if (this.subKeys[sk].keyTrust.search(/r/i) >= 0) {
          ++revoked;
        } else if (!this.subKeys[sk].secretMaterial) {
          ++noSecret;
        } else {
          // found subkey usable
          ++found;
        }
      }
    }

    if (!found) {
      if (exceptionReason != "ignoreExpired" && expired) {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-sign-sub-keys-expired",
          {
            userId: this.userId,
            keyId: "0x" + this.keyId,
          }
        );
      } else if (revoked) {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-sign-sub-keys-revoked",
          {
            userId: this.userId,
            keyId: "0x" + this.keyId,
          }
        );
      } else if (noSecret) {
        retVal.reason = lazy.l10n.formatValueSync("key-ring-no-secret-key", {
          userId: this.userId,
          keyId: "0x" + this.keyId,
        });
      } else {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-pub-key-not-for-signing",
          {
            userId: this.userId,
            keyId: "0x" + this.keyId,
          }
        );
      }
    } else {
      retVal.keyValid = true;
    }

    return retVal;
  }

  /**
   * Check whether a key can be used for encryption and return a description of why not
   *
   * @param {boolean} requireDecryptionKey:
   *                  If true, require secret key material to be available
   *                  for at least one encryption key.
   * @param {string} exceptionReason:
   *                 Can be used to override the requirement to check for
   *                 full validity, and accept certain scenarios as valid.
   *                 If value is set to "ignoreExpired",
   *                 then an expired key isn't treated as invalid.
   *                 Set to null to get the default behavior.
   * @param {string} subId:
   *                 A key ID of a subkey or null.
   *                 If subId is null, any part of the key will be
   *                 considered when looking for a valid encryption key.
   *                 If subId is non-null, only this subkey will be
   *                 checked.
   *
   * @returns Object:
   *   - keyValid: Boolean (true if key is valid)
   *   - reason: String (explanation of invalidity)
   */
  getEncryptionValidity(
    requireDecryptionKey,
    exceptionReason = null,
    subId = null
  ) {
    let retVal = this.getPubKeyValidity(exceptionReason);
    if (!retVal.keyValid) {
      return retVal;
    }

    if (
      !subId &&
      this.keyUseFor.search(/e/) >= 0 &&
      (!requireDecryptionKey || this.secretMaterial)
    ) {
      // We can stop and return the result we already found,
      // because we aren't looking at a specific subkey (!subId),
      // and the primary key is usable for encryption.
      // If we must own secret key material (requireDecryptionKey),
      // in this scenario it's sufficient to have secret material for
      // the primary key.
      return retVal;
    }

    retVal.keyValid = false;

    let expired = 0;
    let revoked = 0;
    let found = 0;
    let noSecret = 0;

    for (let sk of this.subKeys) {
      if (subId && subId != sk.keyId) {
        continue;
      }

      if (sk.keyUseFor.search(/e/) >= 0) {
        if (
          sk.keyTrust.search(/e/i) >= 0 &&
          exceptionReason != "ignoreExpired"
        ) {
          ++expired;
        } else if (sk.keyTrust.search(/r/i) >= 0) {
          ++revoked;
        } else if (requireDecryptionKey && !sk.secretMaterial) {
          ++noSecret;
        } else {
          // found subkey usable
          ++found;
        }
      }
    }

    if (!found) {
      let idToShow = subId ? subId : this.keyId;

      if (exceptionReason != "ignoreExpired" && expired) {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-enc-sub-keys-expired",
          {
            userId: this.userId,
            keyId: "0x" + idToShow,
          }
        );
      } else if (revoked) {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-enc-sub-keys-revoked",
          {
            userId: this.userId,
            keyId: "0x" + idToShow,
          }
        );
      } else if (noSecret) {
        retVal.reason = lazy.l10n.formatValueSync("key-ring-no-secret-key", {
          userId: this.userId,
          keyId: "0x" + idToShow,
        });
      } else {
        retVal.reason = lazy.l10n.formatValueSync(
          "key-ring-pub-key-not-for-encryption",
          {
            userId: this.userId,
            keyId: "0x" + idToShow,
          }
        );
      }
    } else {
      retVal.keyValid = true;
    }

    return retVal;
  }

  /**
   * Determine the next expiry date of the key. This is either the public key expiry date,
   * or the maximum expiry date of a signing or encryption subkey. I.e. this returns the next
   * date at which the key cannot be used for signing and/or encryption anymore
   *
   * @returns Number - The expiry date as seconds after 01/01/1970
   */
  getKeyExpiry() {
    let expiryDate = Number.MAX_VALUE;
    let encryption = -1;
    let signing = -1;

    // check public key expiry date
    if (this.expiryTime > 0) {
      expiryDate = this.expiryTime;
    }

    for (let sk in this.subKeys) {
      if (this.subKeys[sk].keyUseFor.search(/[eE]/) >= 0) {
        let expiry = this.subKeys[sk].expiryTime;
        if (expiry === 0) {
          expiry = Number.MAX_VALUE;
        }
        encryption = Math.max(encryption, expiry);
      } else if (this.subKeys[sk].keyUseFor.search(/[sS]/) >= 0) {
        let expiry = this.subKeys[sk].expiryTime;
        if (expiry === 0) {
          expiry = Number.MAX_VALUE;
        }
        signing = Math.max(signing, expiry);
      }
    }

    if (expiryDate > encryption) {
      if (this.keyUseFor.search(/[eE]/) < 0) {
        expiryDate = encryption;
      }
    }

    if (expiryDate > signing) {
      if (this.keyUseFor.search(/[Ss]/) < 0) {
        expiryDate = signing;
      }
    }

    return expiryDate;
  }

  /**
   * Export the minimum key for the public key object:
   * public key, desired UID, newest signing/encryption subkey
   *
   * @param {string} emailAddr: [optional] email address of UID to extract. Use primary UID if null .
   *
   * @returns Object:
   *    - exitCode (0 = success)
   *    - errorMsg (if exitCode != 0)
   *    - keyData: BASE64-encded string of key data
   */
  getMinimalPubKey(emailAddr) {
    lazy.EnigmailLog.DEBUG(
      "keyObj.jsm: EnigmailKeyObj.getMinimalPubKey: " + this.keyId + "\n"
    );

    if (emailAddr) {
      try {
        emailAddr = lazy.EnigmailFuncs.stripEmail(emailAddr.toLowerCase());
      } catch (x) {
        emailAddr = emailAddr.toLowerCase();
      }

      let foundUid = false,
        uid = "";
      for (let i in this.userIds) {
        try {
          uid = lazy.EnigmailFuncs.stripEmail(
            this.userIds[i].userId.toLowerCase()
          );
        } catch (x) {
          uid = this.userIds[i].userId.toLowerCase();
        }

        if (uid == emailAddr) {
          foundUid = true;
          break;
        }
      }
      if (!foundUid) {
        emailAddr = false;
      }
    }

    if (!emailAddr) {
      emailAddr = this.userId;
    }

    try {
      emailAddr = lazy.EnigmailFuncs.stripEmail(emailAddr.toLowerCase());
    } catch (x) {
      emailAddr = emailAddr.toLowerCase();
    }

    let newestSigningKey = 0,
      newestEncryptionKey = 0,
      subkeysArr = null;

    // search for valid subkeys
    for (let sk in this.subKeys) {
      if (!"indDre".includes(this.subKeys[sk].keyTrust)) {
        if (this.subKeys[sk].keyUseFor.search(/[sS]/) >= 0) {
          // found signing subkey
          if (this.subKeys[sk].keyCreated > newestSigningKey) {
            newestSigningKey = this.subKeys[sk].keyCreated;
          }
        }
        if (this.subKeys[sk].keyUseFor.search(/[eE]/) >= 0) {
          // found encryption subkey
          if (this.subKeys[sk].keyCreated > newestEncryptionKey) {
            newestEncryptionKey = this.subKeys[sk].keyCreated;
          }
        }
      }
    }

    if (newestSigningKey > 0 && newestEncryptionKey > 0) {
      subkeysArr = [newestEncryptionKey, newestSigningKey];
    }

    if (!(emailAddr in this.minimalKeyBlock)) {
      const cApi = lazy.EnigmailCryptoAPI();
      this.minimalKeyBlock[emailAddr] = cApi.sync(
        cApi.getMinimalPubKey(this.fpr, emailAddr, subkeysArr)
      );
    }
    return this.minimalKeyBlock[emailAddr];
  }

  /**
   * Obtain a "virtual" key size that allows to compare different algorithms with each other
   * e.g. elliptic curve keys have small key sizes with high cryptographic strength
   *
   *
   * @returns Number: a virtual size
   */
  getVirtualKeySize() {
    lazy.EnigmailLog.DEBUG(
      "keyObj.jsm: EnigmailKeyObj.getVirtualKeySize: " + this.keyId + "\n"
    );

    switch (this.algoSym) {
      case "DSA":
        return this.keySize / 2;
      case "ECDSA":
        return this.keySize * 8;
      case "EDDSA":
        return this.keySize * 32;
      default:
        return this.keySize;
    }
  }

  /**
   * @param {boolean} minimalKey - if true, reduce key to minimum required
   *
   * @returns {object}:
   *   - {Number} exitCode:  result code (0: OK)
   *   - {String} keyData:   ASCII armored key data material
   *   - {String} errorMsg:  error message in case exitCode !== 0
   */
  getSecretKey(minimalKey) {
    const cApi = lazy.EnigmailCryptoAPI();
    return cApi.sync(cApi.extractSecretKey(this.fpr, minimalKey));
  }

  iSimpleOneSubkeySameExpiry() {
    if (this.subKeys.length == 0) {
      return true;
    }

    if (this.subKeys.length > 1) {
      return false;
    }

    let subKey = this.subKeys[0];

    if (!this.expiryTime && !subKey.expiryTime) {
      return true;
    }

    let deltaSeconds = this.expiryTime - subKey.expiryTime;
    if (deltaSeconds < 0) {
      deltaSeconds *= -1;
    }

    // If expiry dates differ by less than a half day, then we
    // treat it as having roughly the same expiry date.
    return deltaSeconds < 12 * 60 * 60;
  }

  /**
   * Obtain the list of alternative email addresses, except the one
   * that is given as the parameter.
   *
   * @param {boolean} exceptThisEmail - an email address that will
   *   be excluded in the result array.
   * @returns {string[]} - an array of all email addresses found in all
   *   of the key's user IDs, excluding exceptThisEmail.
   */
  getAlternativeEmails(exceptThisEmail) {
    let result = [];

    for (let u of this.userIds) {
      let email;
      try {
        email = lazy.EnigmailFuncs.stripEmail(u.userId.toLowerCase());
      } catch (x) {
        email = u.userId.toLowerCase();
      }

      if (email == exceptThisEmail) {
        continue;
      }

      result.push(email);
    }

    return result;
  }

  getUserIdWithEmail(email) {
    for (let u of this.userIds) {
      let e;
      try {
        e = lazy.EnigmailFuncs.stripEmail(u.userId.toLowerCase());
      } catch (x) {
        e = u.userId.toLowerCase();
      }

      if (email == e) {
        return u;
      }
    }

    return null;
  }
}