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