]> code.delx.au - gnu-emacs/blob - lisp/gnus/mml-sec.el
* test/automated/viper-tests.el (viper-test-undo-kmacro):
[gnu-emacs] / lisp / gnus / mml-sec.el
1 ;;; mml-sec.el --- A package with security functions for MML documents
2
3 ;; Copyright (C) 2000-2016 Free Software Foundation, Inc.
4
5 ;; Author: Simon Josefsson <simon@josefsson.org>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 (eval-when-compile (require 'cl))
27
28 (require 'gnus-util)
29 (require 'epg)
30 (require 'password-cache)
31 (require 'mm-encode)
32
33 (autoload 'mail-strip-quoted-names "mail-utils")
34 (autoload 'mml2015-sign "mml2015")
35 (autoload 'mml2015-encrypt "mml2015")
36 (autoload 'mml1991-sign "mml1991")
37 (autoload 'mml1991-encrypt "mml1991")
38 (autoload 'message-fetch-field "message")
39 (autoload 'message-goto-body "message")
40 (autoload 'message-options-get "message")
41 (autoload 'mml-insert-tag "mml")
42 (autoload 'mml-smime-sign "mml-smime")
43 (autoload 'mml-smime-encrypt "mml-smime")
44 (autoload 'mml-smime-sign-query "mml-smime")
45 (autoload 'mml-smime-encrypt-query "mml-smime")
46 (autoload 'mml-smime-verify "mml-smime")
47 (autoload 'mml-smime-verify-test "mml-smime")
48 (autoload 'epa--select-keys "epa")
49
50 (declare-function message-options-set "message" (symbol value))
51
52 (defvar mml-sign-alist
53 '(("smime" mml-smime-sign-buffer mml-smime-sign-query)
54 ("pgp" mml-pgp-sign-buffer list)
55 ("pgpauto" mml-pgpauto-sign-buffer list)
56 ("pgpmime" mml-pgpmime-sign-buffer list))
57 "Alist of MIME signer functions.")
58
59 (defcustom mml-default-sign-method "pgpmime"
60 "Default sign method.
61 The string must have an entry in `mml-sign-alist'."
62 :version "22.1"
63 :type '(choice (const "smime")
64 (const "pgp")
65 (const "pgpauto")
66 (const "pgpmime")
67 string)
68 :group 'message)
69
70 (defvar mml-encrypt-alist
71 '(("smime" mml-smime-encrypt-buffer mml-smime-encrypt-query)
72 ("pgp" mml-pgp-encrypt-buffer list)
73 ("pgpauto" mml-pgpauto-sign-buffer list)
74 ("pgpmime" mml-pgpmime-encrypt-buffer list))
75 "Alist of MIME encryption functions.")
76
77 (defcustom mml-default-encrypt-method "pgpmime"
78 "Default encryption method.
79 The string must have an entry in `mml-encrypt-alist'."
80 :version "22.1"
81 :type '(choice (const "smime")
82 (const "pgp")
83 (const "pgpauto")
84 (const "pgpmime")
85 string)
86 :group 'message)
87
88 (defcustom mml-signencrypt-style-alist
89 '(("smime" separate)
90 ("pgp" combined)
91 ("pgpauto" combined)
92 ("pgpmime" combined))
93 "Alist specifying if `signencrypt' results in two separate operations or not.
94 The first entry indicates the MML security type, valid entries include
95 the strings \"smime\", \"pgp\", and \"pgpmime\". The second entry is
96 a symbol `separate' or `combined' where `separate' means that MML signs
97 and encrypt messages in a two step process, and `combined' means that MML
98 signs and encrypt the message in one step.
99
100 Note that the output generated by using a `combined' mode is NOT
101 understood by all PGP implementations, in particular PGP version
102 2 does not support it! See Info node `(message) Security' for
103 details."
104 :version "22.1"
105 :group 'message
106 :type '(repeat (list (choice (const :tag "S/MIME" "smime")
107 (const :tag "PGP" "pgp")
108 (const :tag "PGP/MIME" "pgpmime")
109 (string :tag "User defined"))
110 (choice (const :tag "Separate" separate)
111 (const :tag "Combined" combined)))))
112
113 (defcustom mml-secure-verbose nil
114 "If non-nil, ask the user about the current operation more verbosely."
115 :group 'message
116 :type 'boolean)
117
118 ;; FIXME If it's "NOT recommended", why is it the default?
119 (defcustom mml-secure-cache-passphrase password-cache
120 "If t, cache OpenPGP or S/MIME passphrases inside Emacs.
121 Passphrase caching in Emacs is NOT recommended. Use gpg-agent instead.
122 See Info node `(message) Security'."
123 :group 'message
124 :type 'boolean)
125
126 (defcustom mml-secure-passphrase-cache-expiry password-cache-expiry
127 "How many seconds the passphrase is cached.
128 Whether the passphrase is cached at all is controlled by
129 `mml-secure-cache-passphrase'."
130 :group 'message
131 :type 'integer)
132
133 (defcustom mml-secure-safe-bcc-list nil
134 "List of e-mail addresses that are safe to use in Bcc headers.
135 EasyPG encrypts e-mails to Bcc addresses, and the encrypted e-mail
136 by default identifies the used encryption keys, giving away the
137 Bcc'ed identities. Clearly, this contradicts the original goal of
138 *blind* copies.
139 For an academic paper explaining the problem, see URL
140 `http://crypto.stanford.edu/portia/papers/bb-bcc.pdf'.
141 Use this variable to specify e-mail addresses whose owners do not
142 mind if they are identifiable as recipients. This may be useful if
143 you use Bcc headers to encrypt e-mails to yourself."
144 :version "25.1"
145 :group 'message
146 :type '(repeat string))
147
148 ;;; Configuration/helper functions
149
150 (defun mml-signencrypt-style (method &optional style)
151 "Function for setting/getting the signencrypt-style used. Takes two
152 arguments, the method (e.g. \"pgp\") and optionally the mode
153 \(e.g. combined). If the mode is omitted, the current value is returned.
154
155 For example, if you prefer to use combined sign & encrypt with
156 smime, putting the following in your Gnus startup file will
157 enable that behavior:
158
159 \(mml-set-signencrypt-style \"smime\" combined)
160
161 You can also customize or set `mml-signencrypt-style-alist' instead."
162 (let ((style-item (assoc method mml-signencrypt-style-alist)))
163 (if style-item
164 (if (or (eq style 'separate)
165 (eq style 'combined))
166 ;; valid style setting?
167 (setf (second style-item) style)
168 ;; otherwise, just return the current value
169 (second style-item))
170 (message "Warning, attempt to set invalid signencrypt style"))))
171
172 ;;; Security functions
173
174 (defun mml-smime-sign-buffer (cont)
175 (or (mml-smime-sign cont)
176 (error "Signing failed... inspect message logs for errors")))
177
178 (defun mml-smime-encrypt-buffer (cont &optional sign)
179 (when sign
180 (message "Combined sign and encrypt S/MIME not support yet")
181 (sit-for 1))
182 (or (mml-smime-encrypt cont)
183 (error "Encryption failed... inspect message logs for errors")))
184
185 (defun mml-pgp-sign-buffer (cont)
186 (or (mml1991-sign cont)
187 (error "Signing failed... inspect message logs for errors")))
188
189 (defun mml-pgp-encrypt-buffer (cont &optional sign)
190 (or (mml1991-encrypt cont sign)
191 (error "Encryption failed... inspect message logs for errors")))
192
193 (defun mml-pgpmime-sign-buffer (cont)
194 (or (mml2015-sign cont)
195 (error "Signing failed... inspect message logs for errors")))
196
197 (defun mml-pgpmime-encrypt-buffer (cont &optional sign)
198 (or (mml2015-encrypt cont sign)
199 (error "Encryption failed... inspect message logs for errors")))
200
201 (defun mml-pgpauto-sign-buffer (cont)
202 (message-goto-body)
203 (or (if (re-search-backward "Content-Type: *multipart/.*" nil t) ; there must be a better way...
204 (mml2015-sign cont)
205 (mml1991-sign cont))
206 (error "Encryption failed... inspect message logs for errors")))
207
208 (defun mml-pgpauto-encrypt-buffer (cont &optional sign)
209 (message-goto-body)
210 (or (if (re-search-backward "Content-Type: *multipart/.*" nil t) ; there must be a better way...
211 (mml2015-encrypt cont sign)
212 (mml1991-encrypt cont sign))
213 (error "Encryption failed... inspect message logs for errors")))
214
215 (defun mml-secure-part (method &optional sign)
216 (save-excursion
217 (let ((tags (funcall (nth 2 (assoc method (if sign mml-sign-alist
218 mml-encrypt-alist))))))
219 (cond ((re-search-backward
220 "<#\\(multipart\\|part\\|external\\|mml\\)" nil t)
221 (goto-char (match-end 0))
222 (insert (if sign " sign=" " encrypt=") method)
223 (while tags
224 (let ((key (pop tags))
225 (value (pop tags)))
226 (when value
227 ;; Quote VALUE if it contains suspicious characters.
228 (when (string-match "[\"'\\~/*;() \t\n]" value)
229 (setq value (prin1-to-string value)))
230 (insert (format " %s=%s" key value))))))
231 ((or (re-search-backward
232 (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
233 (re-search-forward
234 (concat "^" (regexp-quote mail-header-separator) "\n") nil t))
235 (goto-char (match-end 0))
236 (apply 'mml-insert-tag 'part (cons (if sign 'sign 'encrypt)
237 (cons method tags))))
238 (t (error "The message is corrupted. No mail header separator"))))))
239
240 (defvar mml-secure-method
241 (if (equal mml-default-encrypt-method mml-default-sign-method)
242 mml-default-sign-method
243 "pgpmime")
244 "Current security method. Internal variable.")
245
246 (defun mml-secure-sign (&optional method)
247 "Add MML tags to sign this MML part.
248 Use METHOD if given. Else use `mml-secure-method' or
249 `mml-default-sign-method'."
250 (interactive)
251 (mml-secure-part
252 (or method mml-secure-method mml-default-sign-method)
253 'sign))
254
255 (defun mml-secure-encrypt (&optional method)
256 "Add MML tags to encrypt this MML part.
257 Use METHOD if given. Else use `mml-secure-method' or
258 `mml-default-sign-method'."
259 (interactive)
260 (mml-secure-part
261 (or method mml-secure-method mml-default-sign-method)))
262
263 (defun mml-secure-sign-pgp ()
264 "Add MML tags to PGP sign this MML part."
265 (interactive)
266 (mml-secure-part "pgp" 'sign))
267
268 (defun mml-secure-sign-pgpauto ()
269 "Add MML tags to PGP-auto sign this MML part."
270 (interactive)
271 (mml-secure-part "pgpauto" 'sign))
272
273 (defun mml-secure-sign-pgpmime ()
274 "Add MML tags to PGP/MIME sign this MML part."
275 (interactive)
276 (mml-secure-part "pgpmime" 'sign))
277
278 (defun mml-secure-sign-smime ()
279 "Add MML tags to S/MIME sign this MML part."
280 (interactive)
281 (mml-secure-part "smime" 'sign))
282
283 (defun mml-secure-encrypt-pgp ()
284 "Add MML tags to PGP encrypt this MML part."
285 (interactive)
286 (mml-secure-part "pgp"))
287
288 (defun mml-secure-encrypt-pgpmime ()
289 "Add MML tags to PGP/MIME encrypt this MML part."
290 (interactive)
291 (mml-secure-part "pgpmime"))
292
293 (defun mml-secure-encrypt-smime ()
294 "Add MML tags to S/MIME encrypt this MML part."
295 (interactive)
296 (mml-secure-part "smime"))
297
298 (defun mml-secure-is-encrypted-p ()
299 "Check whether secure encrypt tag is present."
300 (save-excursion
301 (goto-char (point-min))
302 (re-search-forward
303 (concat "^" (regexp-quote mail-header-separator) "\n"
304 "<#secure[^>]+encrypt")
305 nil t)))
306
307 (defun mml-secure-bcc-is-safe ()
308 "Check whether usage of Bcc is safe (or absent).
309 Bcc usage is safe in two cases: first, if the current message does
310 not contain an MML secure encrypt tag;
311 second, if the Bcc addresses are a subset of `mml-secure-safe-bcc-list'.
312 In all other cases, ask the user whether Bcc usage is safe.
313 Raise error if user answers no.
314 Note that this function does not produce a meaningful return value:
315 either an error is raised or not."
316 (when (mml-secure-is-encrypted-p)
317 (let ((bcc (mail-strip-quoted-names (message-fetch-field "bcc"))))
318 (when bcc
319 (let ((bcc-list (mapcar #'cadr
320 (mail-extract-address-components bcc t))))
321 (unless (gnus-subsetp bcc-list mml-secure-safe-bcc-list)
322 (unless (yes-or-no-p "Message for encryption contains Bcc header.\
323 This may give away all Bcc'ed identities to all recipients.\
324 Are you sure that this is safe?\
325 (Customize `mml-secure-safe-bcc-list' to avoid this warning.) ")
326 (error "Aborted"))))))))
327
328 ;; defuns that add the proper <#secure ...> tag to the top of the message body
329 (defun mml-secure-message (method &optional modesym)
330 (let ((mode (prin1-to-string modesym))
331 (tags (append
332 (if (or (eq modesym 'sign)
333 (eq modesym 'signencrypt))
334 (funcall (nth 2 (assoc method mml-sign-alist))))
335 (if (or (eq modesym 'encrypt)
336 (eq modesym 'signencrypt))
337 (funcall (nth 2 (assoc method mml-encrypt-alist))))))
338 insert-loc)
339 (mml-unsecure-message)
340 (save-excursion
341 (goto-char (point-min))
342 (cond ((re-search-forward
343 (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
344 (goto-char (setq insert-loc (match-end 0)))
345 (unless (looking-at "<#secure")
346 (apply 'mml-insert-tag
347 'secure 'method method 'mode mode tags)))
348 (t (error
349 "The message is corrupted. No mail header separator"))))
350 (when (eql insert-loc (point))
351 (forward-line 1))))
352
353 (defun mml-unsecure-message ()
354 "Remove security related MML tags from message."
355 (interactive)
356 (save-excursion
357 (goto-char (point-max))
358 (when (re-search-backward "^<#secure.*>\n" nil t)
359 (delete-region (match-beginning 0) (match-end 0)))))
360
361
362 (defun mml-secure-message-sign (&optional method)
363 "Add MML tags to sign the entire message.
364 Use METHOD if given. Else use `mml-secure-method' or
365 `mml-default-sign-method'."
366 (interactive)
367 (mml-secure-message
368 (or method mml-secure-method mml-default-sign-method)
369 'sign))
370
371 (defun mml-secure-message-sign-encrypt (&optional method)
372 "Add MML tag to sign and encrypt the entire message.
373 Use METHOD if given. Else use `mml-secure-method' or
374 `mml-default-sign-method'."
375 (interactive)
376 (mml-secure-message
377 (or method mml-secure-method mml-default-sign-method)
378 'signencrypt))
379
380 (defun mml-secure-message-encrypt (&optional method)
381 "Add MML tag to encrypt the entire message.
382 Use METHOD if given. Else use `mml-secure-method' or
383 `mml-default-sign-method'."
384 (interactive)
385 (mml-secure-message
386 (or method mml-secure-method mml-default-sign-method)
387 'encrypt))
388
389 (defun mml-secure-message-sign-smime ()
390 "Add MML tag to encrypt/sign the entire message."
391 (interactive)
392 (mml-secure-message "smime" 'sign))
393
394 (defun mml-secure-message-sign-pgp ()
395 "Add MML tag to encrypt/sign the entire message."
396 (interactive)
397 (mml-secure-message "pgp" 'sign))
398
399 (defun mml-secure-message-sign-pgpmime ()
400 "Add MML tag to encrypt/sign the entire message."
401 (interactive)
402 (mml-secure-message "pgpmime" 'sign))
403
404 (defun mml-secure-message-sign-pgpauto ()
405 "Add MML tag to encrypt/sign the entire message."
406 (interactive)
407 (mml-secure-message "pgpauto" 'sign))
408
409 (defun mml-secure-message-encrypt-smime (&optional dontsign)
410 "Add MML tag to encrypt and sign the entire message.
411 If called with a prefix argument, only encrypt (do NOT sign)."
412 (interactive "P")
413 (mml-secure-message "smime" (if dontsign 'encrypt 'signencrypt)))
414
415 (defun mml-secure-message-encrypt-pgp (&optional dontsign)
416 "Add MML tag to encrypt and sign the entire message.
417 If called with a prefix argument, only encrypt (do NOT sign)."
418 (interactive "P")
419 (mml-secure-message "pgp" (if dontsign 'encrypt 'signencrypt)))
420
421 (defun mml-secure-message-encrypt-pgpmime (&optional dontsign)
422 "Add MML tag to encrypt and sign the entire message.
423 If called with a prefix argument, only encrypt (do NOT sign)."
424 (interactive "P")
425 (mml-secure-message "pgpmime" (if dontsign 'encrypt 'signencrypt)))
426
427 (defun mml-secure-message-encrypt-pgpauto (&optional dontsign)
428 "Add MML tag to encrypt and sign the entire message.
429 If called with a prefix argument, only encrypt (do NOT sign)."
430 (interactive "P")
431 (mml-secure-message "pgpauto" (if dontsign 'encrypt 'signencrypt)))
432
433 ;;; Common functionality for mml1991.el, mml2015.el, mml-smime.el
434
435 (define-obsolete-variable-alias 'mml1991-signers 'mml-secure-openpgp-signers
436 "25.1")
437 (define-obsolete-variable-alias 'mml2015-signers 'mml-secure-openpgp-signers
438 "25.1")
439 (defcustom mml-secure-openpgp-signers nil
440 "A list of your own key ID(s) which will be used to sign OpenPGP messages.
441 If set, it is added to the setting of `mml-secure-openpgp-sign-with-sender'."
442 :group 'mime-security
443 :type '(repeat (string :tag "Key ID")))
444
445 (define-obsolete-variable-alias 'mml-smime-signers 'mml-secure-smime-signers
446 "25.1")
447 (defcustom mml-secure-smime-signers nil
448 "A list of your own key ID(s) which will be used to sign S/MIME messages.
449 If set, it is added to the setting of `mml-secure-smime-sign-with-sender'."
450 :group 'mime-security
451 :type '(repeat (string :tag "Key ID")))
452
453 (define-obsolete-variable-alias
454 'mml1991-encrypt-to-self 'mml-secure-openpgp-encrypt-to-self "25.1")
455 (define-obsolete-variable-alias
456 'mml2015-encrypt-to-self 'mml-secure-openpgp-encrypt-to-self "25.1")
457 (defcustom mml-secure-openpgp-encrypt-to-self nil
458 "List of own key ID(s) or t; determines additional recipients with OpenPGP.
459 If t, also encrypt to key for message sender; if list, encrypt to those keys.
460 With this variable, you can ensure that you can decrypt your own messages.
461 Alternatives to this variable include Bcc'ing the message to yourself or
462 using the encrypt-to or hidden-encrypt-to option in gpg.conf (see man gpg(1)).
463 Note that this variable and the encrypt-to option give away your identity
464 for *every* encryption without warning, which is not what you want if you are
465 using, e.g., remailers.
466 Also, use of Bcc gives away your identity for *every* encryption without
467 warning, which is a bug, see:
468 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=18718"
469 :group 'mime-security
470 :type '(choice (const :tag "None" nil)
471 (const :tag "From address" t)
472 (repeat (string :tag "Key ID"))))
473
474 (define-obsolete-variable-alias
475 'mml-smime-encrypt-to-self 'mml-secure-smime-encrypt-to-self "25.1")
476 (defcustom mml-secure-smime-encrypt-to-self nil
477 "List of own key ID(s) or t; determines additional recipients with S/MIME.
478 If t, also encrypt to key for message sender; if list, encrypt to those keys.
479 With this variable, you can ensure that you can decrypt your own messages.
480 Alternatives to this variable include Bcc'ing the message to yourself or
481 using the encrypt-to option in gpgsm.conf (see man gpgsm(1)).
482 Note that this variable and the encrypt-to option give away your identity
483 for *every* encryption without warning, which is not what you want if you are
484 using, e.g., remailers.
485 Also, use of Bcc gives away your identity for *every* encryption without
486 warning, which is a bug, see:
487 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=18718"
488 :group 'mime-security
489 :type '(choice (const :tag "None" nil)
490 (const :tag "From address" t)
491 (repeat (string :tag "Key ID"))))
492
493 (define-obsolete-variable-alias
494 'mml2015-sign-with-sender 'mml-secure-openpgp-sign-with-sender "25.1")
495 ;mml1991-sign-with-sender did never exist.
496 (defcustom mml-secure-openpgp-sign-with-sender nil
497 "If t, use message sender to find an OpenPGP key to sign with."
498 :group 'mime-security
499 :type 'boolean)
500
501 (define-obsolete-variable-alias
502 'mml-smime-sign-with-sender 'mml-secure-smime-sign-with-sender "25.1")
503 (defcustom mml-secure-smime-sign-with-sender nil
504 "If t, use message sender to find an S/MIME key to sign with."
505 :group 'mime-security
506 :type 'boolean)
507
508 (define-obsolete-variable-alias
509 'mml2015-always-trust 'mml-secure-openpgp-always-trust "25.1")
510 ;mml1991-always-trust did never exist.
511 (defcustom mml-secure-openpgp-always-trust t
512 "If t, skip key validation of GnuPG on encryption."
513 :group 'mime-security
514 :type 'boolean)
515
516 (defcustom mml-secure-fail-when-key-problem nil
517 "If t, raise an error if some key is missing or several keys exist.
518 Otherwise, ask the user."
519 :version "25.1"
520 :group 'mime-security
521 :type 'boolean)
522
523 (defcustom mml-secure-key-preferences
524 '((OpenPGP (sign) (encrypt)) (CMS (sign) (encrypt)))
525 "Protocol- and usage-specific fingerprints of preferred keys.
526 This variable is only relevant if a recipient owns multiple key pairs (for
527 encryption) or you own multiple key pairs (for signing). In such cases,
528 you will be asked which key(s) should be used, and your choice can be
529 customized in this variable."
530 :version "25.1"
531 :group 'mime-security
532 :type '(alist :key-type (symbol :tag "Protocol") :value-type
533 (alist :key-type (symbol :tag "Usage") :value-type
534 (alist :key-type (string :tag "Name") :value-type
535 (repeat (string :tag "Fingerprint"))))))
536
537 (defun mml-secure-cust-usage-lookup (context usage)
538 "Return preferences for CONTEXT and USAGE."
539 (let* ((protocol (epg-context-protocol context))
540 (protocol-prefs (cdr (assoc protocol mml-secure-key-preferences))))
541 (assoc usage protocol-prefs)))
542
543 (defun mml-secure-cust-fpr-lookup (context usage name)
544 "Return fingerprints of preferred keys for CONTEXT, USAGE, and NAME."
545 (let* ((usage-prefs (mml-secure-cust-usage-lookup context usage))
546 (fprs (assoc name (cdr usage-prefs))))
547 (when fprs
548 (cdr fprs))))
549
550 (defun mml-secure-cust-record-keys (context usage name keys &optional save)
551 "For CONTEXT, USAGE, and NAME record fingerprint(s) of KEYS.
552 If optional SAVE is not nil, save customized fingerprints.
553 Return keys."
554 (assert keys)
555 (let* ((usage-prefs (mml-secure-cust-usage-lookup context usage))
556 (curr-fprs (cdr (assoc name (cdr usage-prefs))))
557 (key-fprs (mapcar 'mml-secure-fingerprint keys))
558 (new-fprs (gnus-union curr-fprs key-fprs :test 'equal)))
559 (if curr-fprs
560 (setcdr (assoc name (cdr usage-prefs)) new-fprs)
561 (setcdr usage-prefs (cons (cons name new-fprs) (cdr usage-prefs))))
562 (when save
563 (customize-save-variable
564 'mml-secure-key-preferences mml-secure-key-preferences))
565 keys))
566
567 (defun mml-secure-cust-remove-keys (context usage name)
568 "Remove keys for CONTEXT, USAGE, and NAME.
569 Return t if a customization for NAME was present (and has been removed)."
570 (let* ((usage-prefs (mml-secure-cust-usage-lookup context usage))
571 (current (assoc name usage-prefs)))
572 (when current
573 (setcdr usage-prefs (remove current (cdr usage-prefs)))
574 t)))
575
576 (defvar mml-secure-secret-key-id-list nil)
577
578 (defun mml-secure-add-secret-key-id (key-id)
579 "Record KEY-ID in list of secret keys."
580 (add-to-list 'mml-secure-secret-key-id-list key-id))
581
582 (defun mml-secure-clear-secret-key-id-list ()
583 "Remove passwords from cache and clear list of secret keys."
584 ;; Loosely based on code inside mml2015-epg-encrypt,
585 ;; mml2015-epg-clear-decrypt, and mml2015-epg-decrypt
586 (dolist (key-id mml-secure-secret-key-id-list nil)
587 (password-cache-remove key-id))
588 (setq mml-secure-secret-key-id-list nil))
589
590 (defvar mml1991-cache-passphrase)
591 (defvar mml1991-passphrase-cache-expiry)
592
593 (defun mml-secure-cache-passphrase-p (protocol)
594 "Return t if OpenPGP or S/MIME passphrases should be cached for PROTOCOL.
595 Passphrase caching in Emacs is NOT recommended. Use gpg-agent instead."
596 (or (and (eq 'OpenPGP protocol)
597 (or mml-secure-cache-passphrase
598 (and (boundp 'mml2015-cache-passphrase)
599 mml2015-cache-passphrase)
600 (and (boundp 'mml1991-cache-passphrase)
601 mml1991-cache-passphrase)))
602 (and (eq 'CMS protocol)
603 (or mml-secure-cache-passphrase
604 (and (boundp 'mml-smime-cache-passphrase)
605 mml-smime-cache-passphrase)))))
606
607 (defun mml-secure-cache-expiry-interval (protocol)
608 "Return time in seconds to cache passphrases for PROTOCOL.
609 Passphrase caching in Emacs is NOT recommended. Use gpg-agent instead."
610 (or (and (eq 'OpenPGP protocol)
611 (or (and (boundp 'mml2015-passphrase-cache-expiry)
612 mml2015-passphrase-cache-expiry)
613 (and (boundp 'mml1991-passphrase-cache-expiry)
614 mml1991-passphrase-cache-expiry)
615 mml-secure-passphrase-cache-expiry))
616 (and (eq 'CMS protocol)
617 (or (and (boundp 'mml-smime-passphrase-cache-expiry)
618 mml-smime-passphrase-cache-expiry)
619 mml-secure-passphrase-cache-expiry))))
620
621 (defun mml-secure-passphrase-callback (context key-id standard)
622 "Ask for passphrase in CONTEXT for KEY-ID for STANDARD.
623 The passphrase is read and cached."
624 ;; Based on mml2015-epg-passphrase-callback.
625 (if (eq key-id 'SYM)
626 (epg-passphrase-callback-function context key-id nil)
627 (let* ((password-cache-key-id
628 (if (eq key-id 'PIN)
629 "PIN"
630 key-id))
631 (entry (assoc key-id epg-user-id-alist))
632 (passphrase
633 (password-read
634 (if (eq key-id 'PIN)
635 "Passphrase for PIN: "
636 (if entry
637 (format "Passphrase for %s %s: " key-id (cdr entry))
638 (format "Passphrase for %s: " key-id)))
639 ;; TODO: With mml-smime.el, password-cache-key-id is not passed
640 ;; as argument to password-read.
641 ;; Is that on purpose? If so, the following needs to be placed
642 ;; inside an if statement.
643 password-cache-key-id)))
644 (when passphrase
645 (let ((password-cache-expiry (mml-secure-cache-expiry-interval
646 (epg-context-protocol context))))
647 (password-cache-add password-cache-key-id passphrase))
648 (mml-secure-add-secret-key-id password-cache-key-id)
649 (copy-sequence passphrase)))))
650
651 (defun mml-secure-check-user-id (key recipient)
652 "Check whether KEY has a non-revoked, non-expired UID for RECIPIENT."
653 ;; Based on mml2015-epg-check-user-id.
654 (let ((uids (epg-key-user-id-list key)))
655 (catch 'break
656 (dolist (uid uids nil)
657 (if (and (stringp (epg-user-id-string uid))
658 (equal (downcase (car (mail-header-parse-address
659 (epg-user-id-string uid))))
660 (downcase (car (mail-header-parse-address
661 recipient))))
662 (not (memq (epg-user-id-validity uid)
663 '(revoked expired))))
664 (throw 'break t))))))
665
666 (defun mml-secure-secret-key-exists-p (context subkey)
667 "Return t if keyring for CONTEXT contains secret key for public SUBKEY."
668 (let* ((fpr (epg-sub-key-fingerprint subkey))
669 (candidates (epg-list-keys context fpr 'secret))
670 (candno (length candidates)))
671 ;; If two or more subkeys with the same fingerprint exist, something is
672 ;; terribly wrong.
673 (when (>= candno 2)
674 (error "Found %d secret keys with same fingerprint %s" candno fpr))
675 (= 1 candno)))
676
677 (defun mml-secure-check-sub-key (context key usage &optional fingerprint)
678 "Check whether in CONTEXT the public KEY has a usable subkey for USAGE.
679 This is the case if KEY is not disabled, and there is a subkey for
680 USAGE that is neither revoked nor expired. Additionally, if optional
681 FINGERPRINT is present and if it is not the primary key's fingerprint, then
682 the returned subkey must have that FINGERPRINT. FINGERPRINT must consist of
683 hexadecimal digits only (no leading \"0x\" allowed).
684 If USAGE is not `encrypt', then additionally an appropriate secret key must
685 be present in the keyring."
686 ;; Based on mml2015-epg-check-sub-key, extended by
687 ;; - check for secret keys if usage is not 'encrypt and
688 ;; - check for new argument FINGERPRINT.
689 (let* ((subkeys (epg-key-sub-key-list key))
690 (primary (car subkeys))
691 (fpr (epg-sub-key-fingerprint primary)))
692 ;; The primary key will be marked as disabled, when the entire
693 ;; key is disabled (see 12 Field, Format of colon listings, in
694 ;; gnupg/doc/DETAILS)
695 (unless (memq 'disabled (epg-sub-key-capability primary))
696 (catch 'break
697 (dolist (subkey subkeys nil)
698 (if (and (memq usage (epg-sub-key-capability subkey))
699 (not (memq (epg-sub-key-validity subkey)
700 '(revoked expired)))
701 (or (eq 'encrypt usage) ; Encryption works with public key.
702 ;; In contrast, signing requires secret key.
703 (mml-secure-secret-key-exists-p context subkey))
704 (or (not fingerprint)
705 (gnus-string-match-p (concat fingerprint "$") fpr)
706 (gnus-string-match-p (concat fingerprint "$")
707 (epg-sub-key-fingerprint subkey))))
708 (throw 'break t)))))))
709
710 (defun mml-secure-find-usable-keys (context name usage &optional justone)
711 "In CONTEXT return a list of keys for NAME and USAGE.
712 If USAGE is `encrypt' public keys are returned, otherwise secret ones.
713 Only non-revoked and non-expired keys are returned whose primary key is
714 not disabled.
715 NAME can be an e-mail address or a key ID.
716 If NAME just consists of hexadecimal digits (possibly prefixed by \"0x\"), it
717 is treated as key ID for which at most one key must exist in the keyring.
718 Otherwise, NAME is treated as user ID, for which no keys are returned if it
719 is expired or revoked.
720 If optional JUSTONE is not nil, return the first key instead of a list."
721 (let* ((keys (epg-list-keys context name))
722 (iskeyid (string-match "\\(0x\\)?\\([0-9a-fA-F]\\{8,\\}\\)" name))
723 (fingerprint (match-string 2 name))
724 result)
725 (when (and iskeyid (>= (length keys) 2))
726 (error
727 "Name %s (for %s) looks like a key ID but multiple keys found"
728 name usage))
729 (catch 'break
730 (dolist (key keys result)
731 (if (and (or iskeyid
732 (mml-secure-check-user-id key name))
733 (mml-secure-check-sub-key context key usage fingerprint))
734 (if justone
735 (throw 'break key)
736 (push key result)))))))
737
738 (defun mml-secure-select-preferred-keys (context names usage)
739 "Return list of preferred keys in CONTEXT for NAMES and USAGE.
740 This inspects the keyrings to find keys for each name in NAMES. If several
741 keys are found for a name, `mml-secure-select-keys' is used to look for
742 customized preferences or have the user select preferable ones.
743 When `mml-secure-fail-when-key-problem' is t, fail with an error in
744 case of missing, outdated, or multiple keys."
745 ;; Loosely based on code appearing inside mml2015-epg-sign and
746 ;; mml2015-epg-encrypt.
747 (apply
748 #'nconc
749 (mapcar
750 (lambda (name)
751 (let* ((keys (mml-secure-find-usable-keys context name usage))
752 (keyno (length keys)))
753 (cond ((= 0 keyno)
754 (when (or mml-secure-fail-when-key-problem
755 (not (y-or-n-p
756 (format "No %s key for %s; skip it? "
757 usage name))))
758 (error "No %s key for %s" usage name)))
759 ((= 1 keyno) keys)
760 (t (mml-secure-select-keys context name keys usage)))))
761 names)))
762
763 (defun mml-secure-fingerprint (key)
764 "Return fingerprint for public KEY."
765 (epg-sub-key-fingerprint (car (epg-key-sub-key-list key))))
766
767 (defun mml-secure-filter-keys (keys fprs)
768 "Filter KEYS to subset with fingerprints in FPRS."
769 (when keys
770 (if (member (mml-secure-fingerprint (car keys)) fprs)
771 (cons (car keys) (mml-secure-filter-keys (cdr keys) fprs))
772 (mml-secure-filter-keys (cdr keys) fprs))))
773
774 (defun mml-secure-normalize-cust-name (name)
775 "Normalize NAME to be used for customization.
776 Currently, remove ankle brackets."
777 (if (string-match "^<\\(.*\\)>$" name)
778 (match-string 1 name)
779 name))
780
781 (defun mml-secure-select-keys (context name keys usage)
782 "In CONTEXT for NAME select among KEYS for USAGE.
783 KEYS should be a list with multiple entries.
784 NAME is normalized first as customized keys are inspected.
785 When `mml-secure-fail-when-key-problem' is t, fail with an error in case of
786 outdated or multiple keys."
787 (let* ((nname (mml-secure-normalize-cust-name name))
788 (fprs (mml-secure-cust-fpr-lookup context usage nname))
789 (usable-fprs (mapcar 'mml-secure-fingerprint keys)))
790 (if fprs
791 (if (gnus-subsetp fprs usable-fprs)
792 (mml-secure-filter-keys keys fprs)
793 (mml-secure-cust-remove-keys context usage nname)
794 (let ((diff (gnus-setdiff fprs usable-fprs)))
795 (if mml-secure-fail-when-key-problem
796 (error "Customization of %s keys for %s outdated" usage nname)
797 (mml-secure-select-keys-1
798 context nname keys usage (format "\
799 Customized keys
800 (%s)
801 for %s not available any more.
802 Select anew. "
803 diff nname)))))
804 (if mml-secure-fail-when-key-problem
805 (error "Multiple %s keys for %s" usage nname)
806 (mml-secure-select-keys-1
807 context nname keys usage (format "\
808 Multiple %s keys for:
809 %s
810 Select preferred one(s). "
811 usage nname))))))
812
813 (defun mml-secure-select-keys-1 (context name keys usage message)
814 "In CONTEXT for NAME let user select among KEYS for USAGE, showing MESSAGE.
815 Return selected keys."
816 (let* ((selected (epa--select-keys message keys))
817 (selno (length selected))
818 ;; TODO: y-or-n-p does not always resize the echo area but may
819 ;; truncate the message. Why? The following does not help.
820 ;; yes-or-no-p shows full message, though.
821 (message-truncate-lines nil))
822 (if selected
823 (if (y-or-n-p
824 (format "%d %s key(s) selected. Store for %s? "
825 selno usage name))
826 (mml-secure-cust-record-keys context usage name selected 'save)
827 selected)
828 (unless (y-or-n-p
829 (format "No %s key for %s; skip it? " usage name))
830 (error "No %s key for %s" usage name)))))
831
832 (defun mml-secure-signer-names (protocol sender)
833 "Determine signer names for PROTOCOL and message from SENDER.
834 Returned names may be e-mail addresses or key IDs and are determined based
835 on `mml-secure-openpgp-signers' and `mml-secure-openpgp-sign-with-sender' with
836 OpenPGP or `mml-secure-smime-signers' and `mml-secure-smime-sign-with-sender'
837 with S/MIME."
838 (if (eq 'OpenPGP protocol)
839 (append mml-secure-openpgp-signers
840 (if (and mml-secure-openpgp-sign-with-sender sender)
841 (list (concat "<" sender ">"))))
842 (append mml-secure-smime-signers
843 (if (and mml-secure-smime-sign-with-sender sender)
844 (list (concat "<" sender ">"))))))
845
846 (defun mml-secure-signers (context signer-names)
847 "Determine signing keys in CONTEXT from SIGNER-NAMES.
848 If `mm-sign-option' is `guided', the user is asked to choose.
849 Otherwise, `mml-secure-select-preferred-keys' is used."
850 ;; Based on code appearing inside mml2015-epg-sign and
851 ;; mml2015-epg-encrypt.
852 (if (eq mm-sign-option 'guided)
853 (epa-select-keys context "\
854 Select keys for signing.
855 If no one is selected, default secret key is used. "
856 signer-names t)
857 (mml-secure-select-preferred-keys context signer-names 'sign)))
858
859 (defun mml-secure-self-recipients (protocol sender)
860 "Determine additional recipients based on encrypt-to-self variables.
861 PROTOCOL specifies OpenPGP or S/MIME for a message from SENDER."
862 (let ((encrypt-to-self
863 (if (eq 'OpenPGP protocol)
864 mml-secure-openpgp-encrypt-to-self
865 mml-secure-smime-encrypt-to-self)))
866 (when encrypt-to-self
867 (if (listp encrypt-to-self)
868 encrypt-to-self
869 (list sender)))))
870
871 (defun mml-secure-recipients (protocol context config sender)
872 "Determine encryption recipients.
873 PROTOCOL specifies OpenPGP or S/MIME with matching CONTEXT and CONFIG
874 for a message from SENDER."
875 ;; Based on code appearing inside mml2015-epg-encrypt.
876 (let ((recipients
877 (apply #'nconc
878 (mapcar
879 (lambda (recipient)
880 (or (epg-expand-group config recipient)
881 (list (concat "<" recipient ">"))))
882 (split-string
883 (or (message-options-get 'message-recipients)
884 (message-options-set 'message-recipients
885 (read-string "Recipients: ")))
886 "[ \f\t\n\r\v,]+")))))
887 (nconc recipients (mml-secure-self-recipients protocol sender))
888 (if (eq mm-encrypt-option 'guided)
889 (setq recipients
890 (epa-select-keys context "\
891 Select recipients for encryption.
892 If no one is selected, symmetric encryption will be performed. "
893 recipients))
894 (setq recipients
895 (mml-secure-select-preferred-keys context recipients 'encrypt))
896 (unless recipients
897 (error "No recipient specified")))
898 recipients))
899
900 (defun mml-secure-epg-encrypt (protocol cont &optional sign)
901 ;; Based on code appearing inside mml2015-epg-encrypt.
902 (let* ((context (epg-make-context protocol))
903 (config (epg-configuration))
904 (sender (message-options-get 'message-sender))
905 (recipients (mml-secure-recipients protocol context config sender))
906 (signer-names (mml-secure-signer-names protocol sender))
907 cipher signers)
908 (when sign
909 (setq signers (mml-secure-signers context signer-names))
910 (epg-context-set-signers context signers))
911 (when (eq 'OpenPGP protocol)
912 (epg-context-set-armor context t)
913 (epg-context-set-textmode context t))
914 (when (mml-secure-cache-passphrase-p protocol)
915 (epg-context-set-passphrase-callback
916 context
917 (cons 'mml-secure-passphrase-callback protocol)))
918 (condition-case error
919 (setq cipher
920 (if (eq 'OpenPGP protocol)
921 (epg-encrypt-string context (buffer-string) recipients sign
922 mml-secure-openpgp-always-trust)
923 (epg-encrypt-string context (buffer-string) recipients))
924 mml-secure-secret-key-id-list nil)
925 (error
926 (mml-secure-clear-secret-key-id-list)
927 (signal (car error) (cdr error))))
928 cipher))
929
930 (defun mml-secure-epg-sign (protocol mode)
931 ;; Based on code appearing inside mml2015-epg-sign.
932 (let* ((context (epg-make-context protocol))
933 (sender (message-options-get 'message-sender))
934 (signer-names (mml-secure-signer-names protocol sender))
935 (signers (mml-secure-signers context signer-names))
936 signature micalg)
937 (when (eq 'OpenPGP protocol)
938 (epg-context-set-armor context t)
939 (epg-context-set-textmode context t))
940 (epg-context-set-signers context signers)
941 (when (mml-secure-cache-passphrase-p protocol)
942 (epg-context-set-passphrase-callback
943 context
944 (cons 'mml-secure-passphrase-callback protocol)))
945 (condition-case error
946 (setq signature
947 (if (eq 'OpenPGP protocol)
948 (epg-sign-string context (buffer-string) mode)
949 (epg-sign-string context
950 (mm-replace-in-string (buffer-string)
951 "\n" "\r\n") t))
952 mml-secure-secret-key-id-list nil)
953 (error
954 (mml-secure-clear-secret-key-id-list)
955 (signal (car error) (cdr error))))
956 (if (epg-context-result-for context 'sign)
957 (setq micalg (epg-new-signature-digest-algorithm
958 (car (epg-context-result-for context 'sign)))))
959 (cons signature micalg)))
960
961 (provide 'mml-sec)
962
963 ;;; mml-sec.el ends here