Make `mml-smime-use' a defcustom and default to 'epg if EPG is loaded.
[gnus] / lisp / mml-smime.el
1 ;;; mml-smime.el --- S/MIME support for MML
2
3 ;; Copyright (C) 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Author: Simon Josefsson <simon@josefsson.org>
7 ;; Keywords: Gnus, MIME, S/MIME, MML
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 ;; For Emacs <22.2 and XEmacs.
29 (eval-and-compile
30   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
31
32 (eval-when-compile (require 'cl))
33
34 (require 'smime)
35 (require 'mm-decode)
36 (require 'mml-sec)
37 (autoload 'message-narrow-to-headers "message")
38 (autoload 'message-fetch-field "message")
39
40 (defcustom mml-smime-use (if (featurep 'epg) 'epg 'openssl)
41   "Whether to use OpenSSL or EPG to decrypt S/MIME messages.
42 Defaults to EPG if it's loaded."
43   :group 'mime-security
44   :type '(choice (const :tag "EPG" epg)
45                  (const :tag "OpenSSL" openssl)))
46
47 (defvar mml-smime-function-alist
48   '((openssl mml-smime-openssl-sign
49              mml-smime-openssl-encrypt
50              mml-smime-openssl-sign-query
51              mml-smime-openssl-encrypt-query
52              mml-smime-openssl-verify
53              mml-smime-openssl-verify-test)
54     (epg mml-smime-epg-sign
55          mml-smime-epg-encrypt
56          nil
57          nil
58          mml-smime-epg-verify
59          mml-smime-epg-verify-test)))
60
61 (defcustom mml-smime-cache-passphrase mml-secure-cache-passphrase
62   "If t, cache passphrase."
63   :group 'mime-security
64   :type 'boolean)
65
66 (defcustom mml-smime-passphrase-cache-expiry mml-secure-passphrase-cache-expiry
67   "How many seconds the passphrase is cached.
68 Whether the passphrase is cached at all is controlled by
69 `mml-smime-cache-passphrase'."
70   :group 'mime-security
71   :type 'integer)
72
73 (defcustom mml-smime-signers nil
74   "A list of your own key ID which will be used to sign a message."
75   :group 'mime-security
76   :type '(repeat (string :tag "Key ID")))
77
78 (defun mml-smime-sign (cont)
79   (let ((func (nth 1 (assq mml-smime-use mml-smime-function-alist))))
80     (if func
81         (funcall func cont)
82       (error "Cannot find sign function"))))
83
84 (defun mml-smime-encrypt (cont)
85   (let ((func (nth 2 (assq mml-smime-use mml-smime-function-alist))))
86     (if func
87         (funcall func cont)
88       (error "Cannot find encrypt function"))))
89
90 (defun mml-smime-sign-query ()
91   (let ((func (nth 3 (assq mml-smime-use mml-smime-function-alist))))
92     (if func
93         (funcall func))))
94
95 (defun mml-smime-encrypt-query ()
96   (let ((func (nth 4 (assq mml-smime-use mml-smime-function-alist))))
97     (if func
98         (funcall func))))
99
100 (defun mml-smime-verify (handle ctl)
101   (let ((func (nth 5 (assq mml-smime-use mml-smime-function-alist))))
102     (if func
103         (funcall func handle ctl)
104       handle)))
105
106 (defun mml-smime-verify-test (handle ctl)
107   (let ((func (nth 6 (assq mml-smime-use mml-smime-function-alist))))
108     (if func
109         (funcall func handle ctl))))
110
111 (defun mml-smime-openssl-sign (cont)
112   (when (null smime-keys)
113     (customize-variable 'smime-keys)
114     (error "No S/MIME keys configured, use customize to add your key"))
115   (smime-sign-buffer (cdr (assq 'keyfile cont)))
116   (goto-char (point-min))
117   (while (search-forward "\r\n" nil t)
118     (replace-match "\n" t t))
119   (goto-char (point-max)))
120
121 (defun mml-smime-openssl-encrypt (cont)
122   (let (certnames certfiles tmp file tmpfiles)
123     ;; xxx tmp files are always an security issue
124     (while (setq tmp (pop cont))
125       (if (and (consp tmp) (eq (car tmp) 'certfile))
126           (push (cdr tmp) certnames)))
127     (while (setq tmp (pop certnames))
128       (if (not (and (not (file-exists-p tmp))
129                     (get-buffer tmp)))
130           (push tmp certfiles)
131         (setq file (mm-make-temp-file (expand-file-name "mml."
132                                                         mm-tmp-directory)))
133         (with-current-buffer tmp
134           (write-region (point-min) (point-max) file))
135         (push file certfiles)
136         (push file tmpfiles)))
137     (if (smime-encrypt-buffer certfiles)
138         (progn
139           (while (setq tmp (pop tmpfiles))
140             (delete-file tmp))
141           t)
142       (while (setq tmp (pop tmpfiles))
143         (delete-file tmp))
144       nil))
145   (goto-char (point-max)))
146
147 (defvar gnus-extract-address-components)
148
149 (defun mml-smime-openssl-sign-query ()
150   ;; query information (what certificate) from user when MML tag is
151   ;; added, for use later by the signing process
152   (when (null smime-keys)
153     (customize-variable 'smime-keys)
154     (error "No S/MIME keys configured, use customize to add your key"))
155   (list 'keyfile
156         (if (= (length smime-keys) 1)
157             (cadar smime-keys)
158           (or (let ((from (cadr (funcall (if (boundp
159                                               'gnus-extract-address-components)
160                                              gnus-extract-address-components
161                                            'mail-extract-address-components)
162                                          (or (save-excursion
163                                                (save-restriction
164                                                  (message-narrow-to-headers)
165                                                  (message-fetch-field "from")))
166                                              "")))))
167                 (and from (smime-get-key-by-email from)))
168               (smime-get-key-by-email
169                (gnus-completing-read "Sign this part with what signature"
170                                      (mapcar 'car smime-keys) nil nil nil
171                                      (and (listp (car-safe smime-keys))
172                                           (caar smime-keys))))))))
173
174 (defun mml-smime-get-file-cert ()
175   (ignore-errors
176     (list 'certfile (read-file-name
177                      "File with recipient's S/MIME certificate: "
178                      smime-certificate-directory nil t ""))))
179
180 (defun mml-smime-get-dns-cert ()
181   ;; todo: deal with comma separated multiple recipients
182   (let (result who bad cert)
183     (condition-case ()
184         (while (not result)
185           (setq who (read-from-minibuffer
186                      (format "%sLookup certificate for: " (or bad ""))
187                      (cadr (funcall (if (boundp
188                                          'gnus-extract-address-components)
189                                         gnus-extract-address-components
190                                       'mail-extract-address-components)
191                                     (or (save-excursion
192                                           (save-restriction
193                                             (message-narrow-to-headers)
194                                             (message-fetch-field "to")))
195                                         "")))))
196           (if (setq cert (smime-cert-by-dns who))
197               (setq result (list 'certfile (buffer-name cert)))
198             (setq bad (format "`%s' not found. " who))))
199       (quit))
200     result))
201
202 (defun mml-smime-get-ldap-cert ()
203   ;; todo: deal with comma separated multiple recipients
204   (let (result who bad cert)
205     (condition-case ()
206         (while (not result)
207           (setq who (read-from-minibuffer
208                      (format "%sLookup certificate for: " (or bad ""))
209                      (cadr (funcall gnus-extract-address-components
210                                     (or (save-excursion
211                                           (save-restriction
212                                             (message-narrow-to-headers)
213                                             (message-fetch-field "to")))
214                                         "")))))
215           (if (setq cert (smime-cert-by-ldap who))
216               (setq result (list 'certfile (buffer-name cert)))
217             (setq bad (format "`%s' not found. " who))))
218       (quit))
219     result))
220
221 (autoload 'gnus-completing-read "gnus-util")
222
223 (defun mml-smime-openssl-encrypt-query ()
224   ;; todo: try dns/ldap automatically first, before prompting user
225   (let (certs done)
226     (while (not done)
227       (ecase (read (gnus-completing-read
228                     "Fetch certificate from"
229                     '("dns" "ldap" "file") t nil nil
230                     "ldap"))
231         (dns (setq certs (append certs
232                                  (mml-smime-get-dns-cert))))
233         (ldap (setq certs (append certs
234                                   (mml-smime-get-ldap-cert))))
235         (file (setq certs (append certs
236                                   (mml-smime-get-file-cert)))))
237       (setq done (not (y-or-n-p "Add more recipients? "))))
238     certs))
239
240 (defun mml-smime-openssl-verify (handle ctl)
241   (with-temp-buffer
242     (insert-buffer-substring (mm-handle-multipart-original-buffer ctl))
243     (goto-char (point-min))
244     (insert (format "Content-Type: %s; " (mm-handle-media-type ctl)))
245     (insert (format "protocol=\"%s\"; "
246                     (mm-handle-multipart-ctl-parameter ctl 'protocol)))
247     (insert (format "micalg=\"%s\"; "
248                     (mm-handle-multipart-ctl-parameter ctl 'micalg)))
249     (insert (format "boundary=\"%s\"\n\n"
250                     (mm-handle-multipart-ctl-parameter ctl 'boundary)))
251     (when (get-buffer smime-details-buffer)
252       (kill-buffer smime-details-buffer))
253     (let ((buf (current-buffer))
254           (good-signature (smime-noverify-buffer))
255           (good-certificate (and (or smime-CA-file smime-CA-directory)
256                                  (smime-verify-buffer)))
257           addresses openssl-output)
258       (setq openssl-output (with-current-buffer smime-details-buffer
259                              (buffer-string)))
260       (if (not good-signature)
261           (progn
262             ;; we couldn't verify message, fail with openssl output as message
263             (mm-set-handle-multipart-parameter
264              mm-security-handle 'gnus-info "Failed")
265             (mm-set-handle-multipart-parameter
266              mm-security-handle 'gnus-details
267              (concat "OpenSSL failed to verify message integrity:\n"
268                      "-------------------------------------------\n"
269                      openssl-output)))
270         ;; verify mail addresses in mail against those in certificate
271         (when (and (smime-pkcs7-region (point-min) (point-max))
272                    (smime-pkcs7-certificates-region (point-min) (point-max)))
273           (with-temp-buffer
274             (insert-buffer-substring buf)
275             (goto-char (point-min))
276             (while (re-search-forward "-----END CERTIFICATE-----" nil t)
277               (when (smime-pkcs7-email-region (point-min) (point))
278                 (setq addresses (append (smime-buffer-as-string-region
279                                          (point-min) (point)) addresses)))
280               (delete-region (point-min) (point)))
281             (setq addresses (mapcar 'downcase addresses))))
282         (if (not (member (downcase (or (mm-handle-multipart-from ctl) "")) addresses))
283             (mm-set-handle-multipart-parameter
284              mm-security-handle 'gnus-info "Sender address forged")
285           (if good-certificate
286               (mm-set-handle-multipart-parameter
287                mm-security-handle 'gnus-info "Ok (sender authenticated)")
288             (mm-set-handle-multipart-parameter
289              mm-security-handle 'gnus-info "Ok (sender not trusted)")))
290         (mm-set-handle-multipart-parameter
291          mm-security-handle 'gnus-details
292          (concat "Sender claimed to be: " (mm-handle-multipart-from ctl) "\n"
293                  (if addresses
294                      (concat "Addresses in certificate: "
295                              (mapconcat 'identity addresses ", "))
296                    "No addresses found in certificate. (Requires OpenSSL 0.9.6 or later.)")
297                  "\n" "\n"
298                  "OpenSSL output:\n"
299                  "---------------\n" openssl-output "\n"
300                  "Certificate(s) inside S/MIME signature:\n"
301                  "---------------------------------------\n"
302                  (buffer-string) "\n")))))
303   handle)
304
305 (defun mml-smime-openssl-verify-test (handle ctl)
306   smime-openssl-program)
307
308 (defvar epg-user-id-alist)
309 (defvar epg-digest-algorithm-alist)
310 (defvar inhibit-redisplay)
311 (defvar password-cache-expiry)
312
313 (eval-when-compile
314   (autoload 'epg-make-context "epg")
315   (autoload 'epg-context-set-armor "epg")
316   (autoload 'epg-context-set-signers "epg")
317   (autoload 'epg-context-result-for "epg")
318   (autoload 'epg-new-signature-digest-algorithm "epg")
319   (autoload 'epg-verify-result-to-string "epg")
320   (autoload 'epg-list-keys "epg")
321   (autoload 'epg-decrypt-string "epg")
322   (autoload 'epg-verify-string "epg")
323   (autoload 'epg-sign-string "epg")
324   (autoload 'epg-encrypt-string "epg")
325   (autoload 'epg-passphrase-callback-function "epg")
326   (autoload 'epg-context-set-passphrase-callback "epg")
327   (autoload 'epg-configuration "epg-config")
328   (autoload 'epg-expand-group "epg-config")
329   (autoload 'epa-select-keys "epa"))
330
331 (defvar mml-smime-epg-secret-key-id-list nil)
332
333 (defun mml-smime-epg-passphrase-callback (context key-id ignore)
334   (if (eq key-id 'SYM)
335       (epg-passphrase-callback-function context key-id nil)
336     (let* (entry
337            (passphrase
338             (password-read
339              (if (eq key-id 'PIN)
340                  "Passphrase for PIN: "
341                (if (setq entry (assoc key-id epg-user-id-alist))
342                    (format "Passphrase for %s %s: " key-id (cdr entry))
343                  (format "Passphrase for %s: " key-id)))
344              (if (eq key-id 'PIN)
345                  "PIN"
346                key-id))))
347       (when passphrase
348         (let ((password-cache-expiry mml-smime-passphrase-cache-expiry))
349           (password-cache-add key-id passphrase))
350         (setq mml-smime-epg-secret-key-id-list
351               (cons key-id mml-smime-epg-secret-key-id-list))
352         (copy-sequence passphrase)))))
353
354 (declare-function epg-key-sub-key-list   "ext:epg" (key))
355 (declare-function epg-sub-key-capability "ext:epg" (sub-key))
356 (declare-function epg-sub-key-validity   "ext:epg" (sub-key))
357
358 (defun mml-smime-epg-find-usable-key (keys usage)
359   (catch 'found
360     (while keys
361       (let ((pointer (epg-key-sub-key-list (car keys))))
362         (while pointer
363           (if (and (memq usage (epg-sub-key-capability (car pointer)))
364                    (not (memq (epg-sub-key-validity (car pointer))
365                               '(revoked expired))))
366               (throw 'found (car keys)))
367           (setq pointer (cdr pointer))))
368       (setq keys (cdr keys)))))
369
370 (autoload 'mml-compute-boundary "mml")
371
372 ;; We require mm-decode, which requires mm-bodies, which autoloads
373 ;; message-options-get (!).
374 (declare-function message-options-set "message" (symbol value))
375
376 (defun mml-smime-epg-sign (cont)
377   (let* ((inhibit-redisplay t)
378          (context (epg-make-context 'CMS))
379          (boundary (mml-compute-boundary cont))
380          signer-key
381          (signers
382           (or (message-options-get 'mml-smime-epg-signers)
383               (message-options-set
384               'mml-smime-epg-signers
385               (if (eq mm-sign-option 'guided)
386                   (epa-select-keys context "\
387 Select keys for signing.
388 If no one is selected, default secret key is used.  "
389                                    mml-smime-signers t)
390                 (if mml-smime-signers
391                     (mapcar
392                      (lambda (signer)
393                        (setq signer-key (mml-smime-epg-find-usable-key
394                                          (epg-list-keys context signer t)
395                                          'sign))
396                        (unless (or signer-key
397                                    (y-or-n-p
398                                     (format "No secret key for %s; skip it? "
399                                             signer)))
400                          (error "No secret key for %s" signer))
401                        signer-key)
402                      mml-smime-signers))))))
403          signature micalg)
404     (epg-context-set-signers context signers)
405     (if mml-smime-cache-passphrase
406         (epg-context-set-passphrase-callback
407          context
408          #'mml-smime-epg-passphrase-callback))
409     (condition-case error
410         (setq signature (epg-sign-string context
411                                          (mm-replace-in-string (buffer-string)
412                                                                "\n" "\r\n")
413                                          t)
414               mml-smime-epg-secret-key-id-list nil)
415       (error
416        (while mml-smime-epg-secret-key-id-list
417          (password-cache-remove (car mml-smime-epg-secret-key-id-list))
418          (setq mml-smime-epg-secret-key-id-list
419                (cdr mml-smime-epg-secret-key-id-list)))
420        (signal (car error) (cdr error))))
421     (if (epg-context-result-for context 'sign)
422         (setq micalg (epg-new-signature-digest-algorithm
423                       (car (epg-context-result-for context 'sign)))))
424     (goto-char (point-min))
425     (insert (format "Content-Type: multipart/signed; boundary=\"%s\";\n"
426                     boundary))
427     (if micalg
428         (insert (format "\tmicalg=%s; "
429                         (downcase
430                          (cdr (assq micalg
431                                     epg-digest-algorithm-alist))))))
432     (insert "protocol=\"application/pkcs7-signature\"\n")
433     (insert (format "\n--%s\n" boundary))
434     (goto-char (point-max))
435     (insert (format "\n--%s\n" boundary))
436     (insert "Content-Type: application/pkcs7-signature; name=smime.p7s
437 Content-Transfer-Encoding: base64
438 Content-Disposition: attachment; filename=smime.p7s
439
440 ")
441     (insert (base64-encode-string signature) "\n")
442     (goto-char (point-max))
443     (insert (format "--%s--\n" boundary))
444     (goto-char (point-max))))
445
446 (defun mml-smime-epg-encrypt (cont)
447   (let ((inhibit-redisplay t)
448         (context (epg-make-context 'CMS))
449         (config (epg-configuration))
450         (recipients (message-options-get 'mml-smime-epg-recipients))
451         cipher signers
452         (boundary (mml-compute-boundary cont))
453         recipient-key)
454     (unless recipients
455       (setq recipients
456             (apply #'nconc
457                    (mapcar
458                     (lambda (recipient)
459                       (or (epg-expand-group config recipient)
460                           (list recipient)))
461                     (split-string
462                      (or (message-options-get 'message-recipients)
463                          (message-options-set 'message-recipients
464                                               (read-string "Recipients: ")))
465                      "[ \f\t\n\r\v,]+"))))
466       (if (eq mm-encrypt-option 'guided)
467           (setq recipients
468                 (epa-select-keys context "\
469 Select recipients for encryption.
470 If no one is selected, symmetric encryption will be performed.  "
471                                  recipients))
472         (setq recipients
473               (mapcar
474                (lambda (recipient)
475                  (setq recipient-key (mml-smime-epg-find-usable-key
476                                       (epg-list-keys context recipient)
477                                       'encrypt))
478                  (unless (or recipient-key
479                              (y-or-n-p
480                               (format "No public key for %s; skip it? "
481                                       recipient)))
482                    (error "No public key for %s" recipient))
483                  recipient-key)
484                recipients))
485         (unless recipients
486           (error "No recipient specified")))
487       (message-options-set 'mml-smime-epg-recipients recipients))
488     (if mml-smime-cache-passphrase
489         (epg-context-set-passphrase-callback
490          context
491          #'mml-smime-epg-passphrase-callback))
492     (condition-case error
493         (setq cipher
494               (epg-encrypt-string context (buffer-string) recipients)
495               mml-smime-epg-secret-key-id-list nil)
496       (error
497        (while mml-smime-epg-secret-key-id-list
498          (password-cache-remove (car mml-smime-epg-secret-key-id-list))
499          (setq mml-smime-epg-secret-key-id-list
500                (cdr mml-smime-epg-secret-key-id-list)))
501        (signal (car error) (cdr error))))
502     (delete-region (point-min) (point-max))
503     (goto-char (point-min))
504     (insert "\
505 Content-Type: application/pkcs7-mime;
506  smime-type=enveloped-data;
507  name=smime.p7m
508 Content-Transfer-Encoding: base64
509 Content-Disposition: attachment; filename=smime.p7m
510
511 ")
512     (insert (base64-encode-string cipher))
513     (goto-char (point-max))))
514
515 (defun mml-smime-epg-verify (handle ctl)
516   (catch 'error
517     (let ((inhibit-redisplay t)
518           context plain signature-file part signature)
519       (when (or (null (setq part (mm-find-raw-part-by-type
520                                   ctl (or (mm-handle-multipart-ctl-parameter
521                                            ctl 'protocol)
522                                           "application/pkcs7-signature")
523                                   t)))
524                 (null (setq signature (or (mm-find-part-by-type
525                                            (cdr handle)
526                                            "application/pkcs7-signature"
527                                            nil t)
528                                           (mm-find-part-by-type
529                                            (cdr handle)
530                                            "application/x-pkcs7-signature"
531                                            nil t)))))
532         (mm-set-handle-multipart-parameter
533          mm-security-handle 'gnus-info "Corrupted")
534         (throw 'error handle))
535       (setq part (mm-replace-in-string part "\n" "\r\n" t)
536             context (epg-make-context 'CMS))
537       (condition-case error
538           (setq plain (epg-verify-string context (mm-get-part signature) part))
539         (error
540          (mm-set-handle-multipart-parameter
541           mm-security-handle 'gnus-info "Failed")
542          (if (eq (car error) 'quit)
543              (mm-set-handle-multipart-parameter
544               mm-security-handle 'gnus-details "Quit.")
545            (mm-set-handle-multipart-parameter
546             mm-security-handle 'gnus-details (format "%S" error)))
547          (throw 'error handle)))
548       (mm-set-handle-multipart-parameter
549        mm-security-handle 'gnus-info
550        (epg-verify-result-to-string (epg-context-result-for context 'verify)))
551       handle)))
552
553 (defun mml-smime-epg-verify-test (handle ctl)
554   t)
555
556 (provide 'mml-smime)
557
558 ;;; mml-smime.el ends here