2001-07-30 Simon Josefsson <jas@extundo.com>
[gnus] / lisp / smime.el
1 ;;; smime.el --- S/MIME support library
2 ;; Copyright (c) 2000, 2001 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <simon@josefsson.org>
5 ;; Keywords: SMIME X.509 PEM OpenSSL
6
7 ;; This file is not a part of GNU Emacs, but the same permissions apply.
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
11 ;; by the Free Software Foundation; either version 2, or (at your
12 ;; option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful, but
15 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 ;; 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; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This library perform S/MIME operations from within Emacs.
27 ;;
28 ;; Functions for fetching certificates from public repositories are
29 ;; provided, currently only from DNS.  LDAP support (via EUDC) is planned.
30 ;;
31 ;; It uses OpenSSL (tested with version 0.9.5a and 0.9.6) for signing,
32 ;; encryption and decryption.
33 ;;
34 ;; Some general knowledge of S/MIME, X.509, PKCS#12, PEM etc is
35 ;; probably required to use this library in any useful way.
36 ;; Especially, don't expect this library to buy security for you.  If
37 ;; you don't understand what you are doing, you're as likely to lose
38 ;; security than gain any by using this library.
39 ;;
40 ;; This library is not intended to provide a "raw" API for S/MIME,
41 ;; PKCSx or similar, it's intended to perform common operations
42 ;; done on messages encoded in these formats.  The terminology chosen
43 ;; reflect this.
44
45 ;;; Quick introduction:
46
47 ;; Get your S/MIME certificate from VeriSign or someplace.  I used
48 ;; Netscape to generate the key and certificate request and stuff, and
49 ;; Netscape can export the key into PKCS#12 format.
50 ;;
51 ;; Enter OpenSSL.  To be able to use this library, it need to have the
52 ;; SMIME key readable in PEM format.  OpenSSL is used to convert the
53 ;; key:
54 ;;
55 ;; $ openssl pkcs12 -in mykey.p12 -clcerts -nodes > mykey.pem
56 ;; ...
57 ;;
58 ;; Now, use M-x customize-variable smime-keys and add mykey.pem as
59 ;; a key.
60 ;;
61 ;; Now you should be able to sign messages!  Create a buffer and write
62 ;; something and run M-x smime-sign-buffer RET RET and you should see
63 ;; your message MIME armoured and a signature.  Encryption, M-x
64 ;; smime-encrypt-buffer, should also work.
65 ;;
66 ;; To be able to verify messages you need to build up trust with
67 ;; someone.  Perhaps you trust the CA that issued your certificate, at
68 ;; least I did, so I export it's certificates from my PKCS#12
69 ;; certificate with:
70 ;;
71 ;; $ openssl pkcs12 -in mykey.p12 -cacerts -nodes > cacert.pem
72 ;; ...
73 ;;
74 ;; Now, use M-x customize-variable smime-CAs and add cacert.pem as a
75 ;; CA certificate.
76 ;;
77 ;; You should now be able to sign messages, and even verify messages
78 ;; sent by others that use the same CA as you.
79
80 ;; Bugs:
81 ;;
82 ;; Don't complain that this package doesn't do encrypted PEM files,
83 ;; submit a patch instead.  I store my keys in a safe place, so I
84 ;; didn't need the encryption.  Also, programming was made easier by
85 ;; that decision.  One might think that this even influenced were I
86 ;; store my keys, and one would probably be right. :-)
87 ;;
88 ;; Update: Mathias Herberts sent the patch.  However, it uses
89 ;; environment variables to pass the password to OpenSSL, which is
90 ;; slightly insecure. Hence a new todo: use a better -passin method.
91 ;;
92 ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
93
94 ;; <rant>
95 ;;
96 ;; I would include pointers to introductory text on concepts used in
97 ;; this library here, but the material I've read are so horrible I
98 ;; don't want to recomend them.
99 ;;
100 ;; Why can't someone write a simple introduction to all this stuff?
101 ;; Until then, much of this resemble security by obscurity.
102 ;;
103 ;; Also, I'm not going to mention anything about the wonders of
104 ;; cryptopolitics.  Oops, I just did.
105 ;;
106 ;; </rant>
107
108 ;;; Revision history:
109
110 ;; version 0 not released
111
112 ;;; Code:
113
114 (require 'dig)
115 (require 'comint)
116 (eval-when-compile (require 'cl))
117
118 (defgroup smime nil
119   "S/MIME configuration.")
120
121 (defcustom smime-keys nil
122   "*Map mail addresses to a file containing Certificate (and private key).
123 The file is assumed to be in PEM format. You can also associate additional
124 certificates to be sent with every message to each address."
125   :type '(repeat (list (string :tag "Mail address")
126                        (file :tag "File name")
127                        (repeat :tag "Additional certificate files"
128                                (file :tag "File name"))))
129   :group 'smime)
130
131 (defcustom smime-CA-directory nil
132   "*Directory containing certificates for CAs you trust.
133 Directory should contain files (in PEM format) named to the X.509
134 hash of the certificate.  This can be done using OpenSSL such as:
135
136 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`
137
138 where `ca.pem' is the file containing a PEM encoded X.509 CA
139 certificate."
140   :type '(choice (const :tag "none" nil)
141                  directory)
142   :group 'smime)
143
144 (defcustom smime-CA-file nil
145   "*Files containing certificates for CAs you trust.
146 File should contain certificates in PEM format."
147   :type '(choice (const :tag "none" nil)
148                  file)
149   :group 'smime)
150
151 (defcustom smime-certificate-directory "~/Mail/certs/"
152   "*Directory containing other people's certificates.
153 It should contain files named to the X.509 hash of the certificate,
154 and the files themself should be in PEM format."
155 ;The S/MIME library provide simple functionality for fetching
156 ;certificates into this directory, so there is no need to populate it
157 ;manually.
158   :type 'directory
159   :group 'smime)
160
161 (defcustom smime-openssl-program
162   (and (condition-case ()
163            (eq 0 (call-process "openssl" nil nil nil "version"))
164          (error nil))
165        "openssl")
166   "*Name of OpenSSL binary."
167   :type 'string
168   :group 'smime)
169
170 ;; OpenSSL option to select the encryption cipher
171
172 (defcustom smime-encrypt-cipher "-des3"
173   "*Cipher algorithm used for encryption."
174   :type '(choice (const :tag "Triple DES" "-des3")
175                  (const :tag "DES"  "-des")
176                  (const :tag "RC2 40 bits" "-rc2-40")
177                  (const :tag "RC2 64 bits" "-rc2-64")
178                  (const :tag "RC2 128 bits" "-rc2-128"))
179   :group 'smime)
180
181 (defcustom smime-dns-server nil
182   "*DNS server to query certificates from.
183 If nil, use system defaults."
184   :type '(choice (const :tag "System defaults")
185                  string)
186   :group 'smime)
187
188 (defcustom smime-extra-arguments nil
189   "*List of additional arguments passed to OpenSSL.
190 For instance, if you don't have a /dev/random you might be forced
191 to set this to e.g. `(\"-rand\" \"/etc/entropy\")'."
192   :type '(repeat string)
193   :group 'smime)
194
195 (defvar smime-details-buffer "*OpenSSL output*")
196
197 ;; Password dialog function
198
199 (defun smime-ask-passphrase ()
200   "Asks the passphrase to unlock the secret key."
201   (let ((passphrase
202          (comint-read-noecho
203           "Passphrase for secret key (RET for no passphrase): " t)))
204     (if (string= passphrase "")
205         nil
206       passphrase)))
207
208 ;; OpenSSL wrappers.
209
210 (defun smime-call-openssl-region (b e buf &rest args)
211   (case (apply 'call-process-region b e smime-openssl-program nil
212                buf nil (append smime-extra-arguments args))
213     (0 t)
214     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
215     (2 (message "OpenSSL: One of the input files could not be read.") nil)
216     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
217     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
218     (t (error "Unknown OpenSSL exitcode") nil)))
219
220 (defun smime-make-certfiles (certfiles)
221   (if certfiles
222       (append (list "-certfile" (expand-file-name (car certfiles)))
223               (smime-make-certfiles (cdr certfiles)))))
224
225 ;; Sign+encrypt region
226
227 (defun smime-sign-region (b e keyfiles)
228   "Sign region with certified key in KEYFILES.
229 If signing fails, the buffer is not modified.  Region is assumed to
230 have proper MIME tags.  KEYFILES is expected to contain a PEM encoded
231 private key and certificate as its car, and a list of additional certificates
232 to include in its caar."
233   (let ((keyfile (car keyfiles))
234         (certfiles (and (cdr keyfiles) (cadr keyfiles)))
235         (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
236         (passphrase (smime-ask-passphrase)))
237     (if passphrase
238         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
239     (prog1
240         (when (apply 'smime-call-openssl-region b e buffer "smime" "-sign"
241                      "-signer" (expand-file-name keyfile)
242                      (append
243                       (smime-make-certfiles certfiles)
244                       (if passphrase
245                           (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
246           (delete-region b e)
247           (insert-buffer-substring buffer)
248           (when (looking-at "^MIME-Version: 1.0$")
249             (delete-region (point) (progn (forward-line 1) (point))))
250           t)
251       (if passphrase
252           (setenv "GNUS_SMIME_PASSPHRASE" "" t))
253       (with-current-buffer (get-buffer-create smime-details-buffer)
254         (goto-char (point-max))
255         (insert-buffer-substring buffer))
256       (kill-buffer buffer))))
257
258 (defun smime-encrypt-region (b e certfiles)
259   "Encrypt region for recipients specified in CERTFILES.
260 If encryption fails, the buffer is not modified.  Region is assumed to
261 have proper MIME tags.  CERTFILES is a list of filenames, each file
262 is expected to contain of a PEM encoded certificate."
263   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
264     (prog1
265         (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
266                      smime-encrypt-cipher (mapcar 'expand-file-name certfiles))
267           (delete-region b e)
268           (insert-buffer-substring buffer)
269           (when (looking-at "^MIME-Version: 1.0$")
270             (delete-region (point) (progn (forward-line 1) (point))))
271           t)
272       (with-current-buffer (get-buffer-create smime-details-buffer)
273         (goto-char (point-max))
274         (insert-buffer-substring buffer))
275       (kill-buffer buffer))))
276
277 ;; Sign+encrypt buffer
278
279 (defun smime-sign-buffer (&optional keyfile buffer)
280   "S/MIME sign BUFFER with key in KEYFILE.
281 KEYFILE should contain a PEM encoded key and certificate."
282   (interactive)
283   (with-current-buffer (or buffer (current-buffer))
284     (smime-sign-region
285      (point-min) (point-max)
286      (if keyfile
287          (list keyfile (smime-get-certfiles keyfile smime-keys))
288        (smime-get-key-by-email
289         (completing-read "Sign using which signature? " smime-keys nil nil
290                          (and (listp (car-safe smime-keys))
291                               (cdr smime-keys))))))))
292
293 (defun smime-encrypt-buffer (&optional certfiles buffer)
294   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
295 CERTFILES is a list of filenames, each file is expected to consist of
296 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
297 nil."
298   (interactive)
299   (with-current-buffer (or buffer (current-buffer))
300     (smime-encrypt-region
301      (point-min) (point-max)
302      (or certfiles
303          (list (read-file-name "Recipient's S/MIME certificate: "
304                                smime-certificate-directory nil))))))
305
306 ;; Verify+decrypt region
307
308 (defun smime-verify-region (b e)
309   "Verify S/MIME message in region between B and E.
310 Returns non-nil on success.
311 Any details (stdout and stderr) are left in the buffer specified by
312 `smime-details-buffer'."
313   (smime-new-details-buffer)
314   (let ((CAs (append (if smime-CA-file
315                          (list "-CAfile"
316                                (expand-file-name smime-CA-file)))
317                      (if smime-CA-directory
318                          (list "-CApath"
319                                (expand-file-name smime-CA-directory))))))
320     (unless CAs
321       (error "No CA configured"))
322     (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
323                "smime" "-verify" "-out" "/dev/null" CAs)
324         t
325       (insert-buffer-substring smime-details-buffer)
326       nil)))
327
328 (defun smime-noverify-region (b e)
329   "Verify integrity of S/MIME message in region between B and E.
330 Returns non-nil on success.
331 Any details (stdout and stderr) are left in the buffer specified by
332 `smime-details-buffer'."
333   (smime-new-details-buffer)
334   (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
335              "smime" "-verify" "-noverify" "-out" '("/dev/null"))
336       t
337     (insert-buffer-substring smime-details-buffer)
338     nil))
339
340 (defun smime-decrypt-region (b e keyfile)
341   "Decrypt S/MIME message in region between B and E with key in KEYFILE.
342 On success, replaces region with decrypted data and return non-nil.
343 Any details (stderr on success, stdout and stderr on error) are left
344 in the buffer specified by `smime-details-buffer'."
345   (smime-new-details-buffer)
346   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
347         CAs (passphrase (smime-ask-passphrase))
348         (tmpfile (make-temp-file "smime")))
349     (if passphrase
350         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
351     (if (prog1
352             (apply 'smime-call-openssl-region b e
353                    (list buffer tmpfile)
354                    "smime" "-decrypt" "-recip" (expand-file-name keyfile)
355                    (if passphrase
356                        (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
357           (if passphrase
358               (setenv "GNUS_SMIME_PASSPHRASE" "" t))
359           (with-current-buffer smime-details-buffer
360             (insert-file-contents tmpfile)
361             (delete-file tmpfile)))
362         (progn
363           (delete-region b e)
364           (insert-buffer-substring buffer)
365           (kill-buffer buffer)
366           t)
367       (with-current-buffer smime-details-buffer
368         (insert-buffer-substring buffer))
369       (kill-buffer buffer)
370       (delete-region b e)
371       (insert-buffer-substring smime-details-buffer)
372       nil)))
373
374 ;; Verify+Decrypt buffer
375
376 (defun smime-verify-buffer (&optional buffer)
377   "Verify integrity of S/MIME message in BUFFER.
378 Uses current buffer if BUFFER is nil. Returns non-nil on success.
379 Any details (stdout and stderr) are left in the buffer specified by
380 `smime-details-buffer'."
381   (interactive)
382   (with-current-buffer (or buffer (current-buffer))
383     (smime-verify-region (point-min) (point-max))))
384
385 (defun smime-noverify-buffer (&optional buffer)
386   "Verify integrity of S/MIME message in BUFFER.
387 Does NOT verify validity of certificate (only message integrity).
388 Uses current buffer if BUFFER is nil. Returns non-nil on success.
389 Any details (stdout and stderr) are left in the buffer specified by
390 `smime-details-buffer'."
391   (interactive)
392   (with-current-buffer (or buffer (current-buffer))
393     (smime-noverify-region (point-min) (point-max))))
394
395 (defun smime-decrypt-buffer (&optional buffer keyfile)
396   "Decrypt S/MIME message in BUFFER using KEYFILE.
397 Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
398 On success, replaces data in buffer and return non-nil.
399 Any details (stderr on success, stdout and stderr on error) are left
400 in the buffer specified by `smime-details-buffer'."
401   (interactive)
402   (with-current-buffer (or buffer (current-buffer))
403     (smime-decrypt-region
404      (point-min) (point-max)
405      (expand-file-name
406       (or keyfile
407           (smime-get-key-by-email
408            (completing-read "Decrypt with which key? " smime-keys nil nil
409                             (and (listp (car-safe smime-keys))
410                                  (caar smime-keys)))))))))
411
412 ;; Various operations
413
414 (defun smime-new-details-buffer ()
415   (with-current-buffer (get-buffer-create smime-details-buffer)
416     (erase-buffer)))
417
418 (defun smime-pkcs7-region (b e)
419   "Convert S/MIME message between points B and E into a PKCS7 message."
420   (smime-new-details-buffer)
421   (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
422     (delete-region b e)
423     (insert-buffer-substring smime-details-buffer)
424     t))
425
426 (defun smime-pkcs7-certificates-region (b e)
427   "Extract any certificates enclosed in PKCS7 message between points B and E."
428   (smime-new-details-buffer)
429   (when (smime-call-openssl-region
430          b e smime-details-buffer "pkcs7" "-print_certs" "-text")
431     (delete-region b e)
432     (insert-buffer-substring smime-details-buffer)
433     t))
434
435 (defun smime-pkcs7-email-region (b e)
436   "Get email addresses contained in certificate between points B and E.
437 A string or a list of strings is returned."
438   (smime-new-details-buffer)
439   (when (smime-call-openssl-region 
440          b e smime-details-buffer "x509" "-email" "-noout")
441     (delete-region b e)
442     (insert-buffer-substring smime-details-buffer)
443     t))
444
445 ;; Utility functions
446
447 (defun smime-get-certfiles (keyfile keys)
448   (if keys
449       (let ((curkey (car keys))
450             (otherkeys (cdr keys)))
451         (if (string= keyfile (cadr curkey))
452             (caddr curkey)
453           (smime-get-certfiles keyfile otherkeys)))))
454
455 (defalias 'smime-point-at-eol
456   (if (fboundp 'point-at-eol)
457       'point-at-eol
458     'line-end-position))
459
460 (defun smime-buffer-as-string-region (b e)
461   "Return each line in region between B and E as a list of strings."
462   (save-excursion
463     (goto-char b)
464     (let (res)
465       (while (< (point) e)
466         (let ((str (buffer-substring (point) (smime-point-at-eol))))
467           (unless (string= "" str)
468             (push str res)))
469         (forward-line))
470       res)))
471
472 ;; Find certificates
473
474 (defun smime-mail-to-domain (mailaddr)
475   (if (string-match "@" mailaddr)
476       (replace-match "." 'fixedcase 'literal mailaddr)
477     mailaddr))
478
479 (defun smime-cert-by-dns (mail)
480   (let* ((dig-dns-server smime-dns-server)
481          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
482          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
483          (certrr (with-current-buffer digbuf
484                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
485          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
486       (if cert
487           (with-current-buffer retbuf
488             (insert "-----BEGIN CERTIFICATE-----\n")
489             (let ((i 0) (len (length cert)))
490               (while (> (- len 64) i)
491                 (insert (substring cert i (+ i 64)) "\n")
492                 (setq i (+ i 64)))
493               (insert (substring cert i len) "\n"))
494             (insert "-----END CERTIFICATE-----\n"))
495         (kill-buffer retbuf)
496         (setq retbuf nil))
497       (kill-buffer digbuf)
498       retbuf))
499
500 ;; User interface.
501
502 (defvar smime-buffer "*SMIME*")
503
504 (defvar smime-mode-map nil)
505 (put 'smime-mode 'mode-class 'special)
506
507 (unless smime-mode-map
508   (setq smime-mode-map (make-sparse-keymap))
509   (suppress-keymap smime-mode-map)
510
511   (define-key smime-mode-map "q" 'smime-exit)
512   (define-key smime-mode-map "f" 'smime-certificate-info))
513
514 (defun smime-mode ()
515   "Major mode for browsing, viewing and fetching certificates.
516
517 All normal editing commands are switched off.
518 \\<smime-mode-map>
519
520 The following commands are available:
521
522 \\{smime-mode-map}"
523   (interactive)
524   (kill-all-local-variables)
525   (setq major-mode 'smime-mode)
526   (setq mode-name "SMIME")
527   (setq mode-line-process nil)
528   (use-local-map smime-mode-map)
529   (buffer-disable-undo)
530   (setq truncate-lines t)
531   (setq buffer-read-only t))
532
533 (defun smime-certificate-info (certfile)
534   (interactive "fCertificate file: ")
535   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
536     (switch-to-buffer buffer)
537     (erase-buffer)
538     (call-process smime-openssl-program nil buffer 'display
539                   "x509" "-in" (expand-file-name certfile) "-text")
540     (fundamental-mode)
541     (set-buffer-modified-p nil)
542     (toggle-read-only t)
543     (goto-char (point-min))))
544
545 (defun smime-draw-buffer ()
546   (with-current-buffer smime-buffer
547     (let (buffer-read-only)
548       (erase-buffer)
549       (insert "\nYour keys:\n")
550       (dolist (key smime-keys)
551         (insert
552          (format "\t\t%s: %s\n" (car key) (cadr key))))
553       (insert "\nTrusted Certificate Authoritys:\n")
554       (insert "\nKnown Certificates:\n"))))
555
556 (defun smime ()
557   "Go to the SMIME buffer."
558   (interactive)
559   (unless (get-buffer smime-buffer)
560     (save-excursion
561       (set-buffer (get-buffer-create smime-buffer))
562       (smime-mode)))
563   (smime-draw-buffer)
564   (switch-to-buffer smime-buffer))
565
566 (defun smime-exit ()
567   "Quit the S/MIME buffer."
568   (interactive)
569   (kill-buffer (current-buffer)))
570
571 ;; Other functions
572
573 (defun smime-get-key-by-email (email)
574   (cadr (assoc email smime-keys)))
575
576 (provide 'smime)
577
578 ;;; smime.el ends here