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