2000-11-11 Simon Josefsson <sj@extundo.com>
[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 ;;; Quick introduction:
41
42 ;; Get your S/MIME certificate from VeriSign or someplace.  I used
43 ;; Netscape to generate the key and certificate request and stuff, and
44 ;; Netscape can export the key into PKCS#12 format.
45 ;;
46 ;; Enter OpenSSL.  To be able to use this library, it need to have the
47 ;; SMIME key readable in PEM format.  OpenSSL is used to convert the
48 ;; key:
49 ;;
50 ;; $ openssl pkcs12 -in mykey.p12 -clcerts -nodes > mykey.pem
51 ;; ...
52 ;;
53 ;; Now, use M-x customize-variable smime-keys and add mykey.pem as
54 ;; a key.
55 ;;
56 ;; Now you should be able to sign messages!  Create a buffer and write
57 ;; something and run M-x smime-sign-buffer RET RET and you should see
58 ;; your message MIME armoured and a signature.  Encryption, M-x
59 ;; smime-encrypt-buffer, should also work.
60 ;;
61 ;; To be able to verify messages you need to build up trust with
62 ;; someone.  Perhaps you trust the CA that issued your certificate, at
63 ;; least I did, so I export it's certificates from my PKCS#12
64 ;; certificate with:
65 ;;
66 ;; $ openssl pkcs12 -in mykey.p12 -cacerts -nodes > cacert.pem
67 ;; ...
68 ;;
69 ;; Now, use M-x customize-variable smime-CAs and add cacert.pem as a
70 ;; CA certificate.
71 ;;
72 ;; You should now be able to sign messages, and even verify messages
73 ;; sent by others that use the same CA as you.
74
75 ;; Bugs:
76 ;;
77 ;; Don't complain that this package doesn't do encrypted PEM files,
78 ;; submit a patch instead.  I store my keys in a safe place, so I
79 ;; didn't need the encryption.  Also, programming was made easier by
80 ;; that decision.  One might think that this even influenced were I
81 ;; store my keys, and one would probably be right. :-)
82 ;;
83 ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
84
85 ;; <rant>
86 ;;
87 ;; I would include pointers to introductory text on concepts used in
88 ;; this library here, but the material I've read are so horrible I
89 ;; don't want to recomend them.
90 ;;
91 ;; Why can't someone write a simple introduction to all this stuff?
92 ;; Until then, much of this resemble security by obscurity.
93 ;;
94 ;; Also, I'm not going to mention anything about the wonders of
95 ;; cryptopolitics.  Oops, I just did.
96 ;;
97 ;; </rant>
98
99 ;;; Revision history:
100
101 ;; version 0 not released
102
103 ;;; Code:
104
105 (require 'dig)
106 (eval-when-compile (require 'cl))
107
108 (defgroup smime nil
109   "S/MIME configuration.")
110
111 (defcustom smime-keys nil
112   "Map mail addresses to a file containing Certificate (and private key).
113 The file is assumed to be in PEM format and not encrypted."
114   :type '(repeat (list (string :tag "Mail address")
115                        (file :tag "File name")))
116   :group 'smime)
117
118 (defcustom smime-CA-directory ""
119   "Directory containing certificates for CAs you trust.
120 Directory should contain files (in PEM format) named to the X.509
121 hash of the certificate."
122   :type '(choice (const :tag "none" nil)
123                  directory)
124   :group 'smime)
125
126 (defcustom smime-CA-file ""
127   "Files containing certificates for CAs you trust.
128 File should be in PEM format."
129   :type '(choice (const :tag "none" nil)
130                  file)
131   :group 'smime)
132
133 (defcustom smime-certificate-directory "~/Mail/certs/"
134   "Directory containing other people's certificates.
135 It should contain files named to the X.509 hash of the certificate,
136 and the files themself should be in PEM format.
137 The S/MIME library provide simple functionality for fetching
138 certificates into this directory, so there is no need to populate it
139 manually."
140   :type 'directory
141   :group 'smime)
142
143 (defcustom smime-openssl-program "openssl"
144   "Name of OpenSSL binary."
145   :type 'string
146   :group 'smime)
147
148 (defcustom smime-dns-server nil
149   "DNS server to query certificates from.
150 If nil, use system defaults."
151   :type '(choice (const :tag "System defaults")
152                  string)
153   :group 'dig)
154
155 (defvar smime-details-buffer "*S/MIME OpenSSL output*")
156
157 ;; OpenSSL wrappers.
158
159 (defun smime-call-openssl-region (b e buf &rest args)
160   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
161     (0 t)
162     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
163     (2 (message "OpenSSL: One of the input files could not be read.") nil)
164     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
165     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
166     (t (error "Unknown OpenSSL exitcode") nil)))
167
168 ;; Sign+encrypt region
169
170 (defun smime-sign-region (b e keyfile)
171   "Sign region with certified key in KEYFILE.
172 If signing fails, the buffer is not modified.  Region is assumed to
173 have proper MIME tags.  KEYFILE is expected to contain a PEM encoded
174 private key and certificate."
175   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
176     (prog1
177         (when (smime-call-openssl-region b e buffer "smime" "-sign"
178                                          "-signer" (expand-file-name keyfile))
179           (delete-region b e)
180           (insert-buffer buffer)
181           (when (looking-at "^MIME-Version: 1.0$")
182             (delete-region (point) (progn (forward-line 1) (point))))
183           t)
184       (with-current-buffer (get-buffer-create smime-details-buffer)
185         (goto-char (point-max))
186         (insert-buffer buffer))
187       (kill-buffer buffer))))
188
189 (defun smime-encrypt-region (b e certfiles)
190   "Encrypt region for recipients specified in CERTFILES.
191 If encryption fails, the buffer is not modified.  Region is assumed to
192 have proper MIME tags.  CERTFILES is a list of filenames, each file
193 is expected to contain of a PEM encoded certificate."
194   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
195     (prog1
196         (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
197                      (mapcar 'expand-file-name certfiles))
198           (delete-region b e)
199           (insert-buffer buffer)
200           (when (looking-at "^MIME-Version: 1.0$")
201             (delete-region (point) (progn (forward-line 1) (point))))
202           t)
203       (with-current-buffer (get-buffer-create smime-details-buffer)
204         (goto-char (point-max))
205         (insert-buffer buffer))
206       (kill-buffer buffer))))
207
208 ;; Sign+encrypt buffer
209
210 (defun smime-sign-buffer (&optional keyfile buffer)
211   "S/MIME sign BUFFER with key in KEYFILE.
212 KEYFILE should contain a PEM encoded key and certificate."
213   (interactive)
214   (with-current-buffer (or buffer (current-buffer))
215     (smime-sign-region
216      (point-min) (point-max) 
217      (or keyfile
218          (smime-get-key-by-email
219           (completing-read "Sign using which signature? " smime-keys nil nil
220                            (and (listp (car-safe smime-keys))
221                                 (caar smime-keys))))))))
222
223 (defun smime-encrypt-buffer (&optional certfiles buffer)
224   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
225 CERTFILES is a list of filenames, each file is expected to consist of
226 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
227 nil."
228   (interactive)
229   (with-current-buffer (or buffer (current-buffer))
230     (smime-encrypt-region 
231      (point-min) (point-max)
232      (or certfiles
233          (list (read-file-name "Recipient's S/MIME certificate: "
234                                smime-certificate-directory nil))))))
235
236 ;; Verify+decrypt region
237
238 (defun smime-verify-region (b e)
239   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
240         (CAs (cond (smime-CA-file
241                     (list "-CAfile" (expand-file-name smime-CA-file)))
242                    (smime-CA-directory
243                     (list "-CApath" (expand-file-name smime-CA-directory)))
244                    (t
245                     (error "No CA configured.")))))
246     (prog1
247         (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify" CAs)
248             (message "S/MIME message verified succesfully.")
249           (message "S/MIME message NOT verified successfully.")
250           nil)
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 (defun smime-decrypt-region (b e keyfile)
257   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
258         CAs)
259     (when (apply 'smime-call-openssl-region b e buffer "smime" "-decrypt" 
260                  "-recip" keyfile)
261       
262       )
263     (with-current-buffer (get-buffer-create smime-details-buffer)
264       (goto-char (point-max))
265       (insert-buffer buffer))
266     (kill-buffer buffer)))
267   
268 ;; Verify+Decrypt buffer
269
270 (defun smime-verify-buffer (&optional buffer)
271   "Verify integrity of S/MIME message in BUFFER.
272 Uses current buffer if BUFFER is nil."
273   (interactive)
274   (with-current-buffer (or buffer (current-buffer))
275     (smime-verify-region (point-min) (point-max))))
276
277 (defun smime-decrypt-buffer (&optional buffer keyfile)
278   "Decrypt S/MIME message in BUFFER using KEYFILE.
279 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
280   (interactive)
281   (with-current-buffer (or buffer (current-buffer))
282     (smime-decrypt-region 
283      (point-min) (point-max)
284      (or keyfile
285          (smime-get-key-by-email
286           (completing-read "Decrypt with which key? " smime-keys nil nil
287                            (and (listp (car-safe smime-keys)) 
288                                 (caar smime-keys))))))))
289
290 ;; Find certificates
291
292 (defun smime-mail-to-domain (mailaddr)
293   (if (string-match "@" mailaddr)
294       (replace-match "." 'fixedcase 'literal mailaddr)
295     mailaddr))
296
297 (defun smime-cert-by-dns (mail)
298   (let* ((dig-dns-server smime-dns-server)
299          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
300          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
301          (certrr (with-current-buffer digbuf
302                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
303          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
304       (if cert
305           (with-current-buffer retbuf
306             (insert "-----BEGIN CERTIFICATE-----\n")
307             (let ((i 0) (len (length cert)))
308               (while (> (- len 64) i)
309                 (insert (substring cert i (+ i 64)) "\n")
310                 (setq i (+ i 64)))
311               (insert (substring cert i len) "\n"))
312             (insert "-----END CERTIFICATE-----\n"))
313         (kill-buffer retbuf)
314         (setq retbuf nil))
315       (kill-buffer digbuf)
316       retbuf))
317
318 ;; User interface.
319
320 (defvar smime-buffer "*SMIME*")
321
322 (defvar smime-mode-map nil)
323 (put 'smime-mode 'mode-class 'special)
324
325 (unless smime-mode-map
326   (setq smime-mode-map (make-sparse-keymap))
327   (suppress-keymap smime-mode-map)
328
329   (define-key smime-mode-map "q" 'smime-exit)
330   (define-key smime-mode-map "f" 'smime-certificate-info))
331
332 (defun smime-mode ()
333   "Major mode for browsing, viewing and fetching certificates.
334
335 All normal editing commands are switched off.
336 \\<smime-mode-map>
337
338 The following commands are available:
339
340 \\{smime-mode-map}"
341   (interactive)
342   (kill-all-local-variables)
343   (setq major-mode 'smime-mode)
344   (setq mode-name "SMIME")
345   (setq mode-line-process nil)
346   (use-local-map smime-mode-map)
347   (buffer-disable-undo)
348   (setq truncate-lines t)
349   (setq buffer-read-only t))
350
351 (defun smime-certificate-info (certfile)
352   (interactive "fCertificate file: ")
353   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
354     (switch-to-buffer buffer)
355     (erase-buffer)
356     (call-process smime-openssl-program nil buffer 'display
357                   "x509" "-in" (expand-file-name certfile) "-text")
358     (fundamental-mode)
359     (set-buffer-modified-p nil)
360     (toggle-read-only t)
361     (goto-char (point-min))))
362
363 (defun smime-draw-buffer ()
364   (with-current-buffer smime-buffer
365     (let (buffer-read-only)
366       (erase-buffer)
367       (insert "\nYour keys:\n")
368       (dolist (key smime-keys)
369         (insert 
370          (format "\t\t%s: %s\n" (car key) (cadr key))))
371       (insert "\nTrusted Certificate Authoritys:\n")
372       (insert "\nKnown Certificates:\n"))))
373
374 (defun smime ()
375   "Go to the SMIME buffer."
376   (interactive)
377   (unless (get-buffer smime-buffer)
378     (save-excursion
379       (set-buffer (get-buffer-create smime-buffer))
380       (smime-mode)))
381   (smime-draw-buffer)
382   (switch-to-buffer smime-buffer))
383
384 (defun smime-exit ()
385   "Quit the S/MIME buffer."
386   (interactive)
387   (kill-buffer (current-buffer)))
388
389 ;; Other functions
390
391 (defun smime-get-key-by-email (email)
392   (cadr (assoc email smime-keys)))
393
394 (provide 'smime)
395
396 ;;; smime.el ends here