2001-08-17 14:00:00 ShengHuo ZHU <zsh@cs.rochester.edu>
[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 ;; Cache password for e.g. 1h
93 ;;
94 ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
95
96 ;; <rant>
97 ;;
98 ;; I would include pointers to introductory text on concepts used in
99 ;; this library here, but the material I've read are so horrible I
100 ;; don't want to recomend them.
101 ;;
102 ;; Why can't someone write a simple introduction to all this stuff?
103 ;; Until then, much of this resemble security by obscurity.
104 ;;
105 ;; Also, I'm not going to mention anything about the wonders of
106 ;; cryptopolitics.  Oops, I just did.
107 ;;
108 ;; </rant>
109
110 ;;; Revision history:
111
112 ;; version 0 not released
113
114 ;;; Code:
115
116 (require 'dig)
117 (require 'comint)
118 (eval-when-compile (require 'cl))
119
120 (defgroup smime nil
121   "S/MIME configuration.")
122
123 (defcustom smime-keys nil
124   "*Map mail addresses to a file containing Certificate (and private key).
125 The file is assumed to be in PEM format. You can also associate additional
126 certificates to be sent with every message to each address."
127   :type '(repeat (list (string :tag "Mail address")
128                        (file :tag "File name")
129                        (repeat :tag "Additional certificate files"
130                                (file :tag "File name"))))
131   :group 'smime)
132
133 (defcustom smime-CA-directory nil
134   "*Directory containing certificates for CAs you trust.
135 Directory should contain files (in PEM format) named to the X.509
136 hash of the certificate.  This can be done using OpenSSL such as:
137
138 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`
139
140 where `ca.pem' is the file containing a PEM encoded X.509 CA
141 certificate."
142   :type '(choice (const :tag "none" nil)
143                  directory)
144   :group 'smime)
145
146 (defcustom smime-CA-file nil
147   "*Files containing certificates for CAs you trust.
148 File should contain certificates in PEM format."
149   :type '(choice (const :tag "none" nil)
150                  file)
151   :group 'smime)
152
153 (defcustom smime-certificate-directory "~/Mail/certs/"
154   "*Directory containing other people's certificates.
155 It should contain files named to the X.509 hash of the certificate,
156 and the files themself should be in PEM format."
157 ;The S/MIME library provide simple functionality for fetching
158 ;certificates into this directory, so there is no need to populate it
159 ;manually.
160   :type 'directory
161   :group 'smime)
162
163 (defcustom smime-openssl-program
164   (and (condition-case ()
165            (eq 0 (call-process "openssl" nil nil nil "version"))
166          (error nil))
167        "openssl")
168   "*Name of OpenSSL binary."
169   :type 'string
170   :group 'smime)
171
172 ;; OpenSSL option to select the encryption cipher
173
174 (defcustom smime-encrypt-cipher "-des3"
175   "*Cipher algorithm used for encryption."
176   :type '(choice (const :tag "Triple DES" "-des3")
177                  (const :tag "DES"  "-des")
178                  (const :tag "RC2 40 bits" "-rc2-40")
179                  (const :tag "RC2 64 bits" "-rc2-64")
180                  (const :tag "RC2 128 bits" "-rc2-128"))
181   :group 'smime)
182
183 (defcustom smime-dns-server nil
184   "*DNS server to query certificates from.
185 If nil, use system defaults."
186   :type '(choice (const :tag "System defaults")
187                  string)
188   :group 'smime)
189
190 (defvar smime-details-buffer "*OpenSSL output*")
191
192 (eval-and-compile
193   (defalias 'smime-make-temp-file
194     (if (fboundp 'make-temp-file)
195         'make-temp-file
196       (lambda (prefix &optional dir-flag) ;; Simple implementation
197         (expand-file-name
198          (make-temp-name prefix)
199          temporary-file-directory)))))
200
201 ;; Password dialog function
202
203 (defun smime-ask-passphrase ()
204   "Asks the passphrase to unlock the secret key."
205   (let ((passphrase
206          (comint-read-noecho
207           "Passphrase for secret key (RET for no passphrase): " t)))
208     (if (string= passphrase "")
209         nil
210       passphrase)))
211
212 ;; OpenSSL wrappers.
213
214 (defun smime-call-openssl-region (b e buf &rest args)
215   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
216     (0 t)
217     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
218     (2 (message "OpenSSL: One of the input files could not be read.") nil)
219     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
220     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
221     (t (error "Unknown OpenSSL exitcode") nil)))
222
223 (defun smime-make-certfiles (certfiles)
224   (if certfiles
225       (append (list "-certfile" (expand-file-name (car certfiles)))
226               (smime-make-certfiles (cdr certfiles)))))
227
228 ;; Sign+encrypt region
229
230 (defun smime-sign-region (b e keyfiles)
231   "Sign region with certified key in KEYFILES.
232 If signing fails, the buffer is not modified.  Region is assumed to
233 have proper MIME tags.  KEYFILES is expected to contain a PEM encoded
234 private key and certificate as its car, and a list of additional certificates
235 to include in its caar."
236   (smime-new-details-buffer)
237   (let ((keyfile (car keyfiles))
238         (certfiles (and (cdr keyfiles) (cadr keyfiles)))
239         (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
240         (passphrase (smime-ask-passphrase))
241         (tmpfile (smime-make-temp-file "smime")))
242     (if passphrase
243         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
244     (prog1
245         (when (prog1
246                   (apply 'smime-call-openssl-region b e (list buffer tmpfile)
247                          "smime" "-sign" "-signer" (expand-file-name keyfile)
248                          (append
249                           (smime-make-certfiles certfiles)
250                           (if passphrase
251                               (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
252                 (if passphrase
253                     (setenv "GNUS_SMIME_PASSPHRASE" "" t))
254                 (with-current-buffer smime-details-buffer
255                   (insert-file-contents tmpfile)
256                   (delete-file tmpfile)))
257           (delete-region b e)
258           (insert-buffer-substring buffer)
259           (goto-char b)
260           (when (looking-at "^MIME-Version: 1.0$")
261             (delete-region (point) (progn (forward-line 1) (point))))
262           t)
263       (with-current-buffer smime-details-buffer
264         (goto-char (point-max))
265         (insert-buffer-substring buffer))
266       (kill-buffer buffer))))
267
268 (defun smime-encrypt-region (b e certfiles)
269   "Encrypt region for recipients specified in CERTFILES.
270 If encryption fails, the buffer is not modified.  Region is assumed to
271 have proper MIME tags.  CERTFILES is a list of filenames, each file
272 is expected to contain of a PEM encoded certificate."
273   (smime-new-details-buffer)
274   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
275         (tmpfile (smime-make-temp-file "smime")))
276     (prog1
277         (when (prog1
278                   (apply 'smime-call-openssl-region b e (list buffer tmpfile)
279                          "smime" "-encrypt" smime-encrypt-cipher
280                          (mapcar 'expand-file-name certfiles))
281                 (with-current-buffer smime-details-buffer
282                   (insert-file-contents tmpfile)
283                   (delete-file tmpfile)))
284           (delete-region b e)
285           (insert-buffer-substring buffer)
286           (goto-char b)
287           (when (looking-at "^MIME-Version: 1.0$")
288             (delete-region (point) (progn (forward-line 1) (point))))
289           t)
290       (with-current-buffer smime-details-buffer
291         (goto-char (point-max))
292         (insert-buffer-substring buffer))
293       (kill-buffer buffer))))
294
295 ;; Sign+encrypt buffer
296
297 (defun smime-sign-buffer (&optional keyfile buffer)
298   "S/MIME sign BUFFER with key in KEYFILE.
299 KEYFILE should contain a PEM encoded key and certificate."
300   (interactive)
301   (with-current-buffer (or buffer (current-buffer))
302     (smime-sign-region
303      (point-min) (point-max)
304      (if keyfile
305          (list keyfile (smime-get-certfiles keyfile smime-keys))
306        (smime-get-key-by-email
307         (completing-read "Sign using which signature? " smime-keys nil nil
308                          (and (listp (car-safe smime-keys))
309                               (cdr smime-keys))))))))
310
311 (defun smime-encrypt-buffer (&optional certfiles buffer)
312   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
313 CERTFILES is a list of filenames, each file is expected to consist of
314 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
315 nil."
316   (interactive)
317   (with-current-buffer (or buffer (current-buffer))
318     (smime-encrypt-region
319      (point-min) (point-max)
320      (or certfiles
321          (list (read-file-name "Recipient's S/MIME certificate: "
322                                smime-certificate-directory nil))))))
323
324 ;; Verify+decrypt region
325
326 (defun smime-verify-region (b e)
327   "Verify S/MIME message in region between B and E.
328 Returns non-nil on success.
329 Any details (stdout and stderr) are left in the buffer specified by
330 `smime-details-buffer'."
331   (smime-new-details-buffer)
332   (let ((CAs (append (if smime-CA-file
333                          (list "-CAfile"
334                                (expand-file-name smime-CA-file)))
335                      (if smime-CA-directory
336                          (list "-CApath"
337                                (expand-file-name smime-CA-directory))))))
338     (unless CAs
339       (error "No CA configured"))
340     (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
341                "smime" "-verify" "-out" "/dev/null" CAs)
342         t
343       (insert-buffer-substring smime-details-buffer)
344       nil)))
345
346 (defun smime-noverify-region (b e)
347   "Verify integrity of S/MIME message in region between B and E.
348 Returns non-nil on success.
349 Any details (stdout and stderr) are left in the buffer specified by
350 `smime-details-buffer'."
351   (smime-new-details-buffer)
352   (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
353              "smime" "-verify" "-noverify" "-out" '("/dev/null"))
354       t
355     (insert-buffer-substring smime-details-buffer)
356     nil))
357
358 (defun smime-decrypt-region (b e keyfile)
359   "Decrypt S/MIME message in region between B and E with key in KEYFILE.
360 On success, replaces region with decrypted data and return non-nil.
361 Any details (stderr on success, stdout and stderr on error) are left
362 in the buffer specified by `smime-details-buffer'."
363   (smime-new-details-buffer)
364   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
365         CAs (passphrase (smime-ask-passphrase))
366         (tmpfile (smime-make-temp-file "smime")))
367     (if passphrase
368         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
369     (if (prog1
370             (apply 'smime-call-openssl-region b e
371                    (list buffer tmpfile)
372                    "smime" "-decrypt" "-recip" (expand-file-name keyfile)
373                    (if passphrase
374                        (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
375           (if passphrase
376               (setenv "GNUS_SMIME_PASSPHRASE" "" t))
377           (with-current-buffer smime-details-buffer
378             (insert-file-contents tmpfile)
379             (delete-file tmpfile)))
380         (progn
381           (delete-region b e)
382           (insert-buffer-substring buffer)
383           (kill-buffer buffer)
384           t)
385       (with-current-buffer smime-details-buffer
386         (insert-buffer-substring buffer))
387       (kill-buffer buffer)
388       (delete-region b e)
389       (insert-buffer-substring smime-details-buffer)
390       nil)))
391
392 ;; Verify+Decrypt buffer
393
394 (defun smime-verify-buffer (&optional buffer)
395   "Verify integrity of S/MIME message in BUFFER.
396 Uses current buffer if BUFFER is nil. Returns non-nil on success.
397 Any details (stdout and stderr) are left in the buffer specified by
398 `smime-details-buffer'."
399   (interactive)
400   (with-current-buffer (or buffer (current-buffer))
401     (smime-verify-region (point-min) (point-max))))
402
403 (defun smime-noverify-buffer (&optional buffer)
404   "Verify integrity of S/MIME message in BUFFER.
405 Does NOT verify validity of certificate (only message integrity).
406 Uses current buffer if BUFFER is nil. Returns non-nil on success.
407 Any details (stdout and stderr) are left in the buffer specified by
408 `smime-details-buffer'."
409   (interactive)
410   (with-current-buffer (or buffer (current-buffer))
411     (smime-noverify-region (point-min) (point-max))))
412
413 (defun smime-decrypt-buffer (&optional buffer keyfile)
414   "Decrypt S/MIME message in BUFFER using KEYFILE.
415 Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
416 On success, replaces data in buffer and return non-nil.
417 Any details (stderr on success, stdout and stderr on error) are left
418 in the buffer specified by `smime-details-buffer'."
419   (interactive)
420   (with-current-buffer (or buffer (current-buffer))
421     (smime-decrypt-region
422      (point-min) (point-max)
423      (expand-file-name
424       (or keyfile
425           (smime-get-key-by-email
426            (completing-read "Decrypt with which key? " smime-keys nil nil
427                             (and (listp (car-safe smime-keys))
428                                  (caar smime-keys)))))))))
429
430 ;; Various operations
431
432 (defun smime-new-details-buffer ()
433   (with-current-buffer (get-buffer-create smime-details-buffer)
434     (erase-buffer)))
435
436 (defun smime-pkcs7-region (b e)
437   "Convert S/MIME message between points B and E into a PKCS7 message."
438   (smime-new-details-buffer)
439   (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
440     (delete-region b e)
441     (insert-buffer-substring smime-details-buffer)
442     t))
443
444 (defun smime-pkcs7-certificates-region (b e)
445   "Extract any certificates enclosed in PKCS7 message between points B and E."
446   (smime-new-details-buffer)
447   (when (smime-call-openssl-region
448          b e smime-details-buffer "pkcs7" "-print_certs" "-text")
449     (delete-region b e)
450     (insert-buffer-substring smime-details-buffer)
451     t))
452
453 (defun smime-pkcs7-email-region (b e)
454   "Get email addresses contained in certificate between points B and E.
455 A string or a list of strings is returned."
456   (smime-new-details-buffer)
457   (when (smime-call-openssl-region 
458          b e smime-details-buffer "x509" "-email" "-noout")
459     (delete-region b e)
460     (insert-buffer-substring smime-details-buffer)
461     t))
462
463 ;; Utility functions
464
465 (defun smime-get-certfiles (keyfile keys)
466   (if keys
467       (let ((curkey (car keys))
468             (otherkeys (cdr keys)))
469         (if (string= keyfile (cadr curkey))
470             (caddr curkey)
471           (smime-get-certfiles keyfile otherkeys)))))
472
473 (eval-and-compile
474   (defalias 'smime-point-at-eol
475     (if (fboundp 'point-at-eol)
476         'point-at-eol
477       'line-end-position)))
478
479 (defun smime-buffer-as-string-region (b e)
480   "Return each line in region between B and E as a list of strings."
481   (save-excursion
482     (goto-char b)
483     (let (res)
484       (while (< (point) e)
485         (let ((str (buffer-substring (point) (smime-point-at-eol))))
486           (unless (string= "" str)
487             (push str res)))
488         (forward-line))
489       res)))
490
491 ;; Find certificates
492
493 (defun smime-mail-to-domain (mailaddr)
494   (if (string-match "@" mailaddr)
495       (replace-match "." 'fixedcase 'literal mailaddr)
496     mailaddr))
497
498 (defun smime-cert-by-dns (mail)
499   (let* ((dig-dns-server smime-dns-server)
500          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
501          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
502          (certrr (with-current-buffer digbuf
503                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
504          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
505       (if cert
506           (with-current-buffer retbuf
507             (insert "-----BEGIN CERTIFICATE-----\n")
508             (let ((i 0) (len (length cert)))
509               (while (> (- len 64) i)
510                 (insert (substring cert i (+ i 64)) "\n")
511                 (setq i (+ i 64)))
512               (insert (substring cert i len) "\n"))
513             (insert "-----END CERTIFICATE-----\n"))
514         (kill-buffer retbuf)
515         (setq retbuf nil))
516       (kill-buffer digbuf)
517       retbuf))
518
519 ;; User interface.
520
521 (defvar smime-buffer "*SMIME*")
522
523 (defvar smime-mode-map nil)
524 (put 'smime-mode 'mode-class 'special)
525
526 (unless smime-mode-map
527   (setq smime-mode-map (make-sparse-keymap))
528   (suppress-keymap smime-mode-map)
529
530   (define-key smime-mode-map "q" 'smime-exit)
531   (define-key smime-mode-map "f" 'smime-certificate-info))
532
533 (defun smime-mode ()
534   "Major mode for browsing, viewing and fetching certificates.
535
536 All normal editing commands are switched off.
537 \\<smime-mode-map>
538
539 The following commands are available:
540
541 \\{smime-mode-map}"
542   (interactive)
543   (kill-all-local-variables)
544   (setq major-mode 'smime-mode)
545   (setq mode-name "SMIME")
546   (setq mode-line-process nil)
547   (use-local-map smime-mode-map)
548   (buffer-disable-undo)
549   (setq truncate-lines t)
550   (setq buffer-read-only t))
551
552 (defun smime-certificate-info (certfile)
553   (interactive "fCertificate file: ")
554   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
555     (switch-to-buffer buffer)
556     (erase-buffer)
557     (call-process smime-openssl-program nil buffer 'display
558                   "x509" "-in" (expand-file-name certfile) "-text")
559     (fundamental-mode)
560     (set-buffer-modified-p nil)
561     (toggle-read-only t)
562     (goto-char (point-min))))
563
564 (defun smime-draw-buffer ()
565   (with-current-buffer smime-buffer
566     (let (buffer-read-only)
567       (erase-buffer)
568       (insert "\nYour keys:\n")
569       (dolist (key smime-keys)
570         (insert
571          (format "\t\t%s: %s\n" (car key) (cadr key))))
572       (insert "\nTrusted Certificate Authoritys:\n")
573       (insert "\nKnown Certificates:\n"))))
574
575 (defun smime ()
576   "Go to the SMIME buffer."
577   (interactive)
578   (unless (get-buffer smime-buffer)
579     (save-excursion
580       (set-buffer (get-buffer-create smime-buffer))
581       (smime-mode)))
582   (smime-draw-buffer)
583   (switch-to-buffer smime-buffer))
584
585 (defun smime-exit ()
586   "Quit the S/MIME buffer."
587   (interactive)
588   (kill-buffer (current-buffer)))
589
590 ;; Other functions
591
592 (defun smime-get-key-by-email (email)
593   (cadr (assoc email smime-keys)))
594
595 (provide 'smime)
596
597 ;;; smime.el ends here