summaryrefslogtreecommitdiffstats
path: root/comm/mail/extensions/openpgp/content/modules/encryption.jsm
blob: b02336bb91847682dda0577953a7328e485e5b37 (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
/*
 * 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 https://mozilla.org/MPL/2.0/.
 */

"use strict";

const EXPORTED_SYMBOLS = ["EnigmailEncryption"];

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

const lazy = {};

XPCOMUtils.defineLazyModuleGetters(lazy, {
  EnigmailConstants: "chrome://openpgp/content/modules/constants.jsm",
  EnigmailCryptoAPI: "chrome://openpgp/content/modules/cryptoAPI.jsm",
  EnigmailCore: "chrome://openpgp/content/modules/core.jsm",
  EnigmailData: "chrome://openpgp/content/modules/data.jsm",
  EnigmailDialog: "chrome://openpgp/content/modules/dialog.jsm",
  EnigmailFuncs: "chrome://openpgp/content/modules/funcs.jsm",
  EnigmailKeyRing: "chrome://openpgp/content/modules/keyRing.jsm",
  EnigmailLog: "chrome://openpgp/content/modules/log.jsm",
  PgpSqliteDb2: "chrome://openpgp/content/modules/sqliteDb.jsm",
});

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

const gMimeHashAlgorithms = [
  null,
  "sha1",
  "ripemd160",
  "sha256",
  "sha384",
  "sha512",
  "sha224",
  "md5",
];

const ENC_TYPE_MSG = 0;
const ENC_TYPE_ATTACH_BINARY = 1;

var EnigmailEncryption = {
  // return object on success, null on failure
  getCryptParams(
    fromMailAddr,
    toMailAddr,
    bccMailAddr,
    hashAlgorithm,
    sendFlags,
    isAscii,
    errorMsgObj,
    logFileObj
  ) {
    let result = {};
    result.sender = "";
    result.sign = false;
    result.signatureHash = "";
    result.sigTypeClear = false;
    result.sigTypeDetached = false;
    result.encrypt = false;
    result.encryptToSender = false;
    result.armor = false;
    result.senderKeyIsExternal = false;

    lazy.EnigmailLog.DEBUG(
      "encryption.jsm: getCryptParams: hashAlgorithm=" + hashAlgorithm + "\n"
    );

    try {
      fromMailAddr = lazy.EnigmailFuncs.stripEmail(fromMailAddr);
      toMailAddr = lazy.EnigmailFuncs.stripEmail(toMailAddr);
      bccMailAddr = lazy.EnigmailFuncs.stripEmail(bccMailAddr);
    } catch (ex) {
      errorMsgObj.value = lazy.l10n.formatValueSync("invalid-email");
      return null;
    }

    var signMsg = sendFlags & lazy.EnigmailConstants.SEND_SIGNED;
    var encryptMsg = sendFlags & lazy.EnigmailConstants.SEND_ENCRYPTED;
    var usePgpMime = sendFlags & lazy.EnigmailConstants.SEND_PGP_MIME;

    if (sendFlags & lazy.EnigmailConstants.SEND_SENDER_KEY_EXTERNAL) {
      result.senderKeyIsExternal = true;
    }

    // Some day we might need to look at flag SEND_TWO_MIME_LAYERS here,
    // to decide which detached signature flag needs to be passed on
    // to the RNP or GPGME layers. However, today those layers can
    // derive their necessary behavior from being asked to do combined
    // or single encryption/signing. This is because today we always
    // create signed messages using the detached signature, and we never
    // need the OpenPGP signature encoding that includes the message
    // except when combining GPG signing with RNP encryption.

    var detachedSig =
      (usePgpMime || sendFlags & lazy.EnigmailConstants.SEND_ATTACHMENT) &&
      signMsg &&
      !encryptMsg;

    result.to = toMailAddr.split(/\s*,\s*/);
    result.bcc = bccMailAddr.split(/\s*,\s*/);
    result.aliasKeys = new Map();

    if (result.to.length == 1 && result.to[0].length == 0) {
      result.to.splice(0, 1); // remove the single empty entry
    }

    if (result.bcc.length == 1 && result.bcc[0].length == 0) {
      result.bcc.splice(0, 1); // remove the single empty entry
    }

    if (/^0x[0-9a-f]+$/i.test(fromMailAddr)) {
      result.sender = fromMailAddr;
    } else {
      result.sender = "<" + fromMailAddr + ">";
    }
    result.sender = result.sender.replace(/(["'`])/g, "\\$1");

    if (signMsg && hashAlgorithm) {
      result.signatureHash = hashAlgorithm;
    }

    if (encryptMsg) {
      if (isAscii != ENC_TYPE_ATTACH_BINARY) {
        result.armor = true;
      }
      result.encrypt = true;

      if (signMsg) {
        result.sign = true;
      }

      if (
        sendFlags & lazy.EnigmailConstants.SEND_ENCRYPT_TO_SELF &&
        fromMailAddr
      ) {
        result.encryptToSender = true;
      }

      let recipArrays = ["to", "bcc"];
      for (let recipArray of recipArrays) {
        let kMax = recipArray == "to" ? result.to.length : result.bcc.length;
        for (let k = 0; k < kMax; k++) {
          let email = recipArray == "to" ? result.to[k] : result.bcc[k];
          if (!email) {
            continue;
          }
          email = email.toLowerCase();
          if (/^0x[0-9a-f]+$/i.test(email)) {
            throw new Error(`Recipient should not be a key ID: ${email}`);
          }
          if (recipArray == "to") {
            result.to[k] = "<" + email + ">";
          } else {
            result.bcc[k] = "<" + email + ">";
          }

          let aliasKeyList = lazy.EnigmailKeyRing.getAliasKeyList(email);
          if (aliasKeyList) {
            // We have an alias definition.

            let aliasKeys = lazy.EnigmailKeyRing.getAliasKeys(aliasKeyList);
            if (!aliasKeys.length) {
              // An empty result means there was a failure obtaining the
              // defined keys, this happens if at least one key is missing
              // or unusable.
              // We don't allow composing an email that involves a
              // bad alias definition, return null to signal that
              // sending should be aborted.
              errorMsgObj.value = "bad alias definition for " + email;
              return null;
            }

            result.aliasKeys.set(email, aliasKeys);
          }
        }
      }
    } else if (detachedSig) {
      result.sigTypeDetached = true;
      result.sign = true;

      if (isAscii != ENC_TYPE_ATTACH_BINARY) {
        result.armor = true;
      }
    } else if (signMsg) {
      result.sigTypeClear = true;
      result.sign = true;
    }

    return result;
  },

  /**
   * Determine why a given key cannot be used for signing.
   *
   * @param {string} keyId - key ID
   *
   * @returns {string} The reason(s) as message to display to the user, or
   *   an empty string in case the key is valid.
   */
  determineInvSignReason(keyId) {
    lazy.EnigmailLog.DEBUG(
      "errorHandling.jsm: determineInvSignReason: keyId: " + keyId + "\n"
    );

    let key = lazy.EnigmailKeyRing.getKeyById(keyId);
    if (!key) {
      return lazy.l10n.formatValueSync("key-error-key-id-not-found", {
        keySpec: keyId,
      });
    }
    let r = key.getSigningValidity();
    if (!r.keyValid) {
      return r.reason;
    }

    return "";
  },

  /**
   * Determine why a given key cannot be used for encryption.
   *
   * @param {string} keyId - key ID
   *
   * @returns {string} The reason(s) as message to display to the user, or
   *   an empty string in case the key is valid.
   */
  determineInvRcptReason(keyId) {
    lazy.EnigmailLog.DEBUG(
      "errorHandling.jsm: determineInvRcptReason: keyId: " + keyId + "\n"
    );

    let key = lazy.EnigmailKeyRing.getKeyById(keyId);
    if (!key) {
      return lazy.l10n.formatValueSync("key-error-key-id-not-found", {
        keySpec: keyId,
      });
    }
    let r = key.getEncryptionValidity(false);
    if (!r.keyValid) {
      return r.reason;
    }

    return "";
  },

  /**
   * Determine if the sender key ID or user ID can be used for signing and/or
   * encryption
   *
   * @param {integer} sendFlags - The send Flags; need to contain SEND_SIGNED and/or SEND_ENCRYPTED
   * @param {string} fromKeyId - The sender key ID
   *
   * @returns {object} object
   *         - keyId:    String - the found key ID, or null if fromMailAddr is not valid
   *         - errorMsg: String - the error message if key not valid, or null if key is valid
   */
  async determineOwnKeyUsability(sendFlags, fromKeyId, isExternalGnuPG) {
    lazy.EnigmailLog.DEBUG(
      "encryption.jsm: determineOwnKeyUsability: sendFlags=" +
        sendFlags +
        ", sender=" +
        fromKeyId +
        "\n"
    );

    let foundKey = null;
    let ret = {
      errorMsg: null,
    };

    if (!fromKeyId) {
      return ret;
    }

    let sign = !!(sendFlags & lazy.EnigmailConstants.SEND_SIGNED);
    let encrypt = !!(sendFlags & lazy.EnigmailConstants.SEND_ENCRYPTED);

    if (/^(0x)?[0-9a-f]+$/i.test(fromKeyId)) {
      // key ID specified
      foundKey = lazy.EnigmailKeyRing.getKeyById(fromKeyId);
    }

    // even for isExternalGnuPG we require that the public key is available
    if (!foundKey) {
      ret.errorMsg = this.determineInvSignReason(fromKeyId);
      return ret;
    }

    if (!isExternalGnuPG && foundKey.secretAvailable) {
      let isPersonal = await lazy.PgpSqliteDb2.isAcceptedAsPersonalKey(
        foundKey.fpr
      );
      if (!isPersonal) {
        ret.errorMsg = lazy.l10n.formatValueSync(
          "key-error-not-accepted-as-personal",
          {
            keySpec: fromKeyId,
          }
        );
        return ret;
      }
    }

    let canSign = false;
    let canEncrypt = false;

    if (isExternalGnuPG) {
      canSign = true;
    } else if (sign && foundKey) {
      let v = foundKey.getSigningValidity();
      if (v.keyValid) {
        canSign = true;
      } else {
        // If we already have a reason for the key not being valid,
        // use that as error message.
        ret.errorMsg = v.reason;
      }
    }

    if (encrypt && foundKey) {
      let v;
      if (lazy.EnigmailKeyRing.isSubkeyId(fromKeyId)) {
        // If the configured own key ID points to a subkey, check
        // specifically that this subkey is a valid encryption key.

        let id = fromKeyId.replace(/^0x/, "");
        v = foundKey.getEncryptionValidity(false, null, id);
      } else {
        // Use parameter "false", because for isExternalGnuPG we cannot
        // confirm that the user has the secret key.
        // And for users of internal encryption code, we don't need to
        // check that here either, public key is sufficient for encryption.
        v = foundKey.getEncryptionValidity(false);
      }

      if (v.keyValid) {
        canEncrypt = true;
      } else {
        // If we already have a reason for the key not being valid,
        // use that as error message.
        ret.errorMsg = v.reason;
      }
    }

    if (sign && !canSign) {
      if (!ret.errorMsg) {
        // Only if we don't have an error message yet.
        ret.errorMsg = this.determineInvSignReason(fromKeyId);
      }
    } else if (encrypt && !canEncrypt) {
      if (!ret.errorMsg) {
        // Only if we don't have an error message yet.
        ret.errorMsg = this.determineInvRcptReason(fromKeyId);
      }
    }

    return ret;
  },

  // return 0 on success, non-zero on failure
  encryptMessageStart(
    win,
    uiFlags,
    fromMailAddr,
    toMailAddr,
    bccMailAddr,
    hashAlgorithm,
    sendFlags,
    listener,
    statusFlagsObj,
    errorMsgObj
  ) {
    lazy.EnigmailLog.DEBUG(
      "encryption.jsm: encryptMessageStart: uiFlags=" +
        uiFlags +
        ", from " +
        fromMailAddr +
        " to " +
        toMailAddr +
        ", hashAlgorithm=" +
        hashAlgorithm +
        " (" +
        lazy.EnigmailData.bytesToHex(lazy.EnigmailData.pack(sendFlags, 4)) +
        ")\n"
    );

    // This code used to call determineOwnKeyUsability, and return on
    // failure. But now determineOwnKeyUsability is an async function,
    // and calling it from here with await results in a deadlock.
    // Instead we perform this check in Enigmail.msg.prepareSendMsg.

    var hashAlgo =
      gMimeHashAlgorithms[
        Services.prefs.getIntPref("temp.openpgp.mimeHashAlgorithm")
      ];

    if (hashAlgorithm) {
      hashAlgo = hashAlgorithm;
    }

    errorMsgObj.value = "";

    if (!sendFlags) {
      lazy.EnigmailLog.DEBUG(
        "encryption.jsm: encryptMessageStart: NO ENCRYPTION!\n"
      );
      errorMsgObj.value = lazy.l10n.formatValueSync("not-required");
      return 0;
    }

    if (!lazy.EnigmailCore.getService(win)) {
      throw new Error(
        "encryption.jsm: encryptMessageStart: not yet initialized"
      );
    }

    let logFileObj = {};

    let encryptArgs = EnigmailEncryption.getCryptParams(
      fromMailAddr,
      toMailAddr,
      bccMailAddr,
      hashAlgo,
      sendFlags,
      ENC_TYPE_MSG,
      errorMsgObj,
      logFileObj
    );

    if (!encryptArgs) {
      return -1;
    }

    if (!listener) {
      throw new Error("unexpected no listener");
    }

    let resultStatus = {};
    const cApi = lazy.EnigmailCryptoAPI();
    let encrypted = cApi.sync(
      cApi.encryptAndOrSign(
        listener.getInputForCrypto(),
        encryptArgs,
        resultStatus
      )
    );

    if (resultStatus.exitCode) {
      if (resultStatus.errorMsg.length) {
        lazy.EnigmailDialog.alert(win, resultStatus.errorMsg);
      }
    } else if (encrypted) {
      listener.addCryptoOutput(encrypted);
    }

    if (resultStatus.exitCode === 0 && !listener.getCryptoOutputLength()) {
      resultStatus.exitCode = -1;
    }
    return resultStatus.exitCode;
  },

  encryptMessage(
    parent,
    uiFlags,
    plainText,
    fromMailAddr,
    toMailAddr,
    bccMailAddr,
    sendFlags,
    exitCodeObj,
    statusFlagsObj,
    errorMsgObj
  ) {
    lazy.EnigmailLog.DEBUG(
      "enigmail.js: Enigmail.encryptMessage: " +
        plainText.length +
        " bytes from " +
        fromMailAddr +
        " to " +
        toMailAddr +
        " (" +
        sendFlags +
        ")\n"
    );
    throw new Error("Not implemented");

    /*
    exitCodeObj.value = -1;
    statusFlagsObj.value = 0;
    errorMsgObj.value = "";

    if (!plainText) {
      EnigmailLog.DEBUG("enigmail.js: Enigmail.encryptMessage: NO ENCRYPTION!\n");
      exitCodeObj.value = 0;
      EnigmailLog.DEBUG("  <=== encryptMessage()\n");
      return plainText;
    }

    var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
    var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
    var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;

    if (encryptMsg) {
      // First convert all linebreaks to newlines
      plainText = plainText.replace(/\r\n/g, "\n");
      plainText = plainText.replace(/\r/g, "\n");

      // we need all data in CRLF according to RFC 4880
      plainText = plainText.replace(/\n/g, "\r\n");
    }

    var listener = EnigmailExecution.newSimpleListener(
      function _stdin(pipe) {
        pipe.write(plainText);
        pipe.close();
      },
      function _done(exitCode) {});


    var proc = EnigmailEncryption.encryptMessageStart(parent, uiFlags,
      fromMailAddr, toMailAddr, bccMailAddr,
      null, sendFlags,
      listener, statusFlagsObj, errorMsgObj);
    if (!proc) {
      exitCodeObj.value = -1;
      EnigmailLog.DEBUG("  <=== encryptMessage()\n");
      return "";
    }

    // Wait for child pipes to close
    proc.wait();

    var retStatusObj = {};
    exitCodeObj.value = EnigmailEncryption.encryptMessageEnd(fromMailAddr, EnigmailData.getUnicodeData(listener.stderrData), listener.exitCode,
      uiFlags, sendFlags,
      listener.stdoutData.length,
      retStatusObj);

    statusFlagsObj.value = retStatusObj.statusFlags;
    statusFlagsObj.statusMsg = retStatusObj.statusMsg;
    errorMsgObj.value = retStatusObj.errorMsg;


    if ((exitCodeObj.value === 0) && listener.stdoutData.length === 0)
      exitCodeObj.value = -1;

    if (exitCodeObj.value === 0) {
      // Normal return
      EnigmailLog.DEBUG("  <=== encryptMessage()\n");
      return EnigmailData.getUnicodeData(listener.stdoutData);
    }

    // Error processing
    EnigmailLog.DEBUG("enigmail.js: Enigmail.encryptMessage: command execution exit code: " + exitCodeObj.value + "\n");
    return "";
  */
  },
};