2001-04-18 Simon Josefsson <simon@josefsson.org>
[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 and not encrypted."
124   :type '(repeat (list (string :tag "Mail address")
125                        (file :tag "File name")))
126   :group 'smime)
127
128 (defcustom smime-CA-directory nil
129   "Directory containing certificates for CAs you trust.
130 Directory should contain files (in PEM format) named to the X.509
131 hash of the certificate.  This can be done using OpenSSL such as:
132
133 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`
134
135 where `ca.pem' is the file containing a PEM encoded X.509 CA
136 certificate."
137   :type '(choice (const :tag "none" nil)
138                  directory)
139   :group 'smime)
140
141 (defcustom smime-CA-file nil
142   "Files containing certificates for CAs you trust.
143 File should contain certificates in PEM format."
144   :type '(choice (const :tag "none" nil)
145                  file)
146   :group 'smime)
147
148 (defcustom smime-certificate-directory "~/Mail/certs/"
149   "Directory containing other people's certificates.
150 It should contain files named to the X.509 hash of the certificate,
151 and the files themself should be in PEM format."
152 ;The S/MIME library provide simple functionality for fetching
153 ;certificates into this directory, so there is no need to populate it
154 ;manually.
155   :type 'directory
156   :group 'smime)
157
158 (defcustom smime-openssl-program
159   (and (condition-case ()
160            (eq 0 (call-process "openssl" nil nil nil "version"))
161          (error nil))
162        "openssl")
163   "Name of OpenSSL binary."
164   :type 'string
165   :group 'smime)
166
167 ;; OpenSSL option to select the encryption cipher
168
169 (defcustom smime-encrypt-cipher "-des3"
170   "Cipher algorithm used for encryption."
171   :type '(choice (const :tag "Triple DES" "-des3")
172                  (const :tag "DES"  "-des")
173                  (const :tag "RC2 40 bits" "-rc2-40")
174                  (const :tag "RC2 64 bits" "-rc2-64")
175                  (const :tag "RC2 128 bits" "-rc2-128"))
176   :group 'smime)
177   
178 (defcustom smime-dns-server nil
179   "DNS server to query certificates from.
180 If nil, use system defaults."
181   :type '(choice (const :tag "System defaults")
182                  string)
183   :group 'dig)
184
185 (defvar smime-details-buffer "*OpenSSL output*")
186
187 ;; Password dialog function
188
189 (defun smime-ask-passphrase ()
190   "Asks the passphrase to unlock the secret key."
191   (let ((passphrase
192          (comint-read-noecho
193           "Passphrase for secret key (RET for no passphrase): " t)))
194     (if (string= passphrase "")
195         nil
196       passphrase)))
197
198 ;; OpenSSL wrappers.
199
200 (defun smime-call-openssl-region (b e buf &rest args)
201   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
202     (0 t)
203     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
204     (2 (message "OpenSSL: One of the input files could not be read.") nil)
205     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
206     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
207     (t (error "Unknown OpenSSL exitcode") nil)))
208
209 ;; Sign+encrypt region
210
211 (defun smime-sign-region (b e keyfile)
212   "Sign region with certified key in KEYFILE.
213 If signing fails, the buffer is not modified.  Region is assumed to
214 have proper MIME tags.  KEYFILE is expected to contain a PEM encoded
215 private key and certificate."
216   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
217         (passphrase (smime-ask-passphrase)))
218     (if passphrase
219         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
220     (prog1
221         (when (apply 'smime-call-openssl-region b e buffer "smime" "-sign" 
222                      "-signer" (expand-file-name keyfile)
223                      (if passphrase
224                          (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
225           (delete-region b e)
226           (insert-buffer buffer)
227           (when (looking-at "^MIME-Version: 1.0$")
228             (delete-region (point) (progn (forward-line 1) (point))))
229           t)
230       (if passphrase
231           (setenv "GNUS_SMIME_PASSPHRASE" "" t))
232       (with-current-buffer (get-buffer-create smime-details-buffer)
233         (goto-char (point-max))
234         (insert-buffer buffer))
235       (kill-buffer buffer))))
236
237 (defun smime-encrypt-region (b e certfiles)
238   "Encrypt region for recipients specified in CERTFILES.
239 If encryption fails, the buffer is not modified.  Region is assumed to
240 have proper MIME tags.  CERTFILES is a list of filenames, each file
241 is expected to contain of a PEM encoded certificate."
242   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
243     (prog1
244         (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
245                      smime-encrypt-cipher (mapcar 'expand-file-name certfiles))
246           (delete-region b e)
247           (insert-buffer buffer)
248           (when (looking-at "^MIME-Version: 1.0$")
249             (delete-region (point) (progn (forward-line 1) (point))))
250           t)
251       (with-current-buffer (get-buffer-create smime-details-buffer)
252         (goto-char (point-max))
253         (insert-buffer buffer))
254       (kill-buffer buffer))))
255
256 ;; Sign+encrypt buffer
257
258 (defun smime-sign-buffer (&optional keyfile buffer)
259   "S/MIME sign BUFFER with key in KEYFILE.
260 KEYFILE should contain a PEM encoded key and certificate."
261   (interactive)
262   (with-current-buffer (or buffer (current-buffer))
263     (smime-sign-region
264      (point-min) (point-max)
265      (or keyfile
266          (smime-get-key-by-email
267           (completing-read "Sign using which signature? " smime-keys nil nil
268                            (and (listp (car-safe smime-keys))
269                                 (caar smime-keys))))))))
270
271 (defun smime-encrypt-buffer (&optional certfiles buffer)
272   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
273 CERTFILES is a list of filenames, each file is expected to consist of
274 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
275 nil."
276   (interactive)
277   (with-current-buffer (or buffer (current-buffer))
278     (smime-encrypt-region
279      (point-min) (point-max)
280      (or certfiles
281          (list (read-file-name "Recipient's S/MIME certificate: "
282                                smime-certificate-directory nil))))))
283
284 ;; Verify+decrypt region
285
286 (defun smime-verify-region (b e)
287   (let ((buffer (get-buffer-create smime-details-buffer))
288         (CAs (cond (smime-CA-file
289                     (list "-CAfile" (expand-file-name smime-CA-file)))
290                    (smime-CA-directory
291                     (list "-CApath" (expand-file-name smime-CA-directory)))
292                    (t
293                     (error "No CA configured.")))))
294     (with-current-buffer buffer
295       (erase-buffer))
296     (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
297                "-out" "/dev/null" CAs)
298         (message "S/MIME message verified succesfully.")
299       (message "S/MIME message NOT verified successfully.")
300       nil)))
301
302 (defun smime-noverify-region (b e)
303   (let ((buffer (get-buffer-create smime-details-buffer)))
304     (with-current-buffer buffer
305       (erase-buffer))
306     (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
307                "-noverify" "-out" '("/dev/null"))
308         (message "S/MIME message verified succesfully.")
309       (message "S/MIME message NOT verified successfully.")
310       nil)))
311
312 (defun smime-decrypt-region (b e keyfile)
313   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
314         CAs (passphrase (smime-ask-passphrase)))
315     (if passphrase
316         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
317     (when (apply 'smime-call-openssl-region
318                  b e buffer "smime" "-decrypt" 
319                  "-recip" (list keyfile)
320                  (if passphrase
321                      (list "-passin" "env:GNUS_SMIME_PASSPHRASE" )))
322       )
323     (if passphrase
324         (setenv "GNUS_SMIME_PASSPHRASE" "" t))
325     (with-current-buffer (get-buffer-create smime-details-buffer)
326       (goto-char (point-max))
327       (insert-buffer buffer))
328     (kill-buffer buffer)))
329
330 ;; Verify+Decrypt buffer
331
332 (defun smime-verify-buffer (&optional buffer)
333   "Verify integrity of S/MIME message in BUFFER.
334 Uses current buffer if BUFFER is nil."
335   (interactive)
336   (with-current-buffer (or buffer (current-buffer))
337     (smime-verify-region (point-min) (point-max))))
338
339 (defun smime-noverify-buffer (&optional buffer)
340   "Verify integrity of S/MIME message in BUFFER.
341 Uses current buffer if BUFFER is nil.
342 Does NOT verify validity of certificate."
343   (interactive)
344   (with-current-buffer (or buffer (current-buffer))
345     (smime-noverify-region (point-min) (point-max))))
346
347 (defun smime-decrypt-buffer (&optional buffer keyfile)
348   "Decrypt S/MIME message in BUFFER using KEYFILE.
349 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
350   (interactive)
351   (with-current-buffer (or buffer (current-buffer))
352     (smime-decrypt-region
353      (point-min) (point-max)
354      (expand-file-name
355       (or keyfile
356           (smime-get-key-by-email
357            (completing-read "Decrypt with which key? " smime-keys nil nil
358                             (and (listp (car-safe smime-keys))
359                                  (caar smime-keys)))))))))
360
361 ;; Various operations
362
363 (defun smime-pkcs7-region (b e)
364   "Convert S/MIME message between points B and E into a PKCS7 message."
365   (let ((buffer (get-buffer-create smime-details-buffer)))
366     (with-current-buffer buffer
367       (erase-buffer))
368     (when (smime-call-openssl-region b e buffer "smime" "-pk7out")
369       (delete-region b e)
370       (insert-buffer-substring buffer)
371       t)))
372
373 (defun smime-pkcs7-certificates-region (b e)
374   "Extract any certificates enclosed in PKCS7 message between points B and E."
375   (let ((buffer (get-buffer-create smime-details-buffer)))
376     (with-current-buffer buffer
377       (erase-buffer))
378     (when (smime-call-openssl-region b e buffer "pkcs7" "-print_certs" "-text")
379       (delete-region b e)
380       (insert-buffer-substring buffer)
381       t)))
382
383 (defun smime-pkcs7-email-region (b e)
384   "Get email addresses contained in certificate between points B and E.
385 A string or a list of strings is returned."
386   (let ((buffer (get-buffer-create smime-details-buffer)))
387     (with-current-buffer buffer
388       (erase-buffer))
389     (when (smime-call-openssl-region b e buffer "x509" "-email" "-noout")
390       (delete-region b e)
391       (insert-buffer-substring buffer)
392       t)))
393
394 (defalias 'smime-point-at-eol
395   (if (fboundp 'point-at-eol)
396       'point-at-eol
397     'line-end-position))
398
399 (defun smime-buffer-as-string-region (b e)
400   "Return each line in region between B and E as a list of strings."
401   (save-excursion
402     (goto-char b)
403     (let (res)
404       (while (< (point) e)
405         (let ((str (buffer-substring (point) (smime-point-at-eol))))
406           (unless (string= "" str)
407             (push str res)))
408         (forward-line))
409       res)))
410
411 ;; Find certificates
412
413 (defun smime-mail-to-domain (mailaddr)
414   (if (string-match "@" mailaddr)
415       (replace-match "." 'fixedcase 'literal mailaddr)
416     mailaddr))
417
418 (defun smime-cert-by-dns (mail)
419   (let* ((dig-dns-server smime-dns-server)
420          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
421          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
422          (certrr (with-current-buffer digbuf
423                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
424          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
425       (if cert
426           (with-current-buffer retbuf
427             (insert "-----BEGIN CERTIFICATE-----\n")
428             (let ((i 0) (len (length cert)))
429               (while (> (- len 64) i)
430                 (insert (substring cert i (+ i 64)) "\n")
431                 (setq i (+ i 64)))
432               (insert (substring cert i len) "\n"))
433             (insert "-----END CERTIFICATE-----\n"))
434         (kill-buffer retbuf)
435         (setq retbuf nil))
436       (kill-buffer digbuf)
437       retbuf))
438
439 ;; User interface.
440
441 (defvar smime-buffer "*SMIME*")
442
443 (defvar smime-mode-map nil)
444 (put 'smime-mode 'mode-class 'special)
445
446 (unless smime-mode-map
447   (setq smime-mode-map (make-sparse-keymap))
448   (suppress-keymap smime-mode-map)
449
450   (define-key smime-mode-map "q" 'smime-exit)
451   (define-key smime-mode-map "f" 'smime-certificate-info))
452
453 (defun smime-mode ()
454   "Major mode for browsing, viewing and fetching certificates.
455
456 All normal editing commands are switched off.
457 \\<smime-mode-map>
458
459 The following commands are available:
460
461 \\{smime-mode-map}"
462   (interactive)
463   (kill-all-local-variables)
464   (setq major-mode 'smime-mode)
465   (setq mode-name "SMIME")
466   (setq mode-line-process nil)
467   (use-local-map smime-mode-map)
468   (buffer-disable-undo)
469   (setq truncate-lines t)
470   (setq buffer-read-only t))
471
472 (defun smime-certificate-info (certfile)
473   (interactive "fCertificate file: ")
474   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
475     (switch-to-buffer buffer)
476     (erase-buffer)
477     (call-process smime-openssl-program nil buffer 'display
478                   "x509" "-in" (expand-file-name certfile) "-text")
479     (fundamental-mode)
480     (set-buffer-modified-p nil)
481     (toggle-read-only t)
482     (goto-char (point-min))))
483
484 (defun smime-draw-buffer ()
485   (with-current-buffer smime-buffer
486     (let (buffer-read-only)
487       (erase-buffer)
488       (insert "\nYour keys:\n")
489       (dolist (key smime-keys)
490         (insert
491          (format "\t\t%s: %s\n" (car key) (cadr key))))
492       (insert "\nTrusted Certificate Authoritys:\n")
493       (insert "\nKnown Certificates:\n"))))
494
495 (defun smime ()
496   "Go to the SMIME buffer."
497   (interactive)
498   (unless (get-buffer smime-buffer)
499     (save-excursion
500       (set-buffer (get-buffer-create smime-buffer))
501       (smime-mode)))
502   (smime-draw-buffer)
503   (switch-to-buffer smime-buffer))
504
505 (defun smime-exit ()
506   "Quit the S/MIME buffer."
507   (interactive)
508   (kill-buffer (current-buffer)))
509
510 ;; Other functions
511
512 (defun smime-get-key-by-email (email)
513   (cadr (assoc email smime-keys)))
514
515 (provide 'smime)
516
517 ;;; smime.el ends here