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