2000-11-13 15:29:58 ShengHuo ZHU <zsh@cs.rochester.edu>
[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 
144   (and (condition-case () 
145            (eq 0 (call-process "openssl" nil nil nil "version"))
146          (error nil))
147        "openssl")
148   "Name of OpenSSL binary."
149   :type 'string
150   :group 'smime)
151
152 (defcustom smime-dns-server nil
153   "DNS server to query certificates from.
154 If nil, use system defaults."
155   :type '(choice (const :tag "System defaults")
156                  string)
157   :group 'dig)
158
159 (defvar smime-details-buffer "*S/MIME OpenSSL output*")
160
161 ;; OpenSSL wrappers.
162
163 (defun smime-call-openssl-region (b e buf &rest args)
164   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
165     (0 t)
166     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
167     (2 (message "OpenSSL: One of the input files could not be read.") nil)
168     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
169     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
170     (t (error "Unknown OpenSSL exitcode") nil)))
171
172 ;; Sign+encrypt region
173
174 (defun smime-sign-region (b e keyfile)
175   "Sign region with certified key in KEYFILE.
176 If signing fails, the buffer is not modified.  Region is assumed to
177 have proper MIME tags.  KEYFILE is expected to contain a PEM encoded
178 private key and certificate."
179   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
180     (prog1
181         (when (smime-call-openssl-region b e buffer "smime" "-sign"
182                                          "-signer" (expand-file-name keyfile))
183           (delete-region b e)
184           (insert-buffer buffer)
185           (when (looking-at "^MIME-Version: 1.0$")
186             (delete-region (point) (progn (forward-line 1) (point))))
187           t)
188       (with-current-buffer (get-buffer-create smime-details-buffer)
189         (goto-char (point-max))
190         (insert-buffer buffer))
191       (kill-buffer buffer))))
192
193 (defun smime-encrypt-region (b e certfiles)
194   "Encrypt region for recipients specified in CERTFILES.
195 If encryption fails, the buffer is not modified.  Region is assumed to
196 have proper MIME tags.  CERTFILES is a list of filenames, each file
197 is expected to contain of a PEM encoded certificate."
198   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
199     (prog1
200         (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
201                      (mapcar 'expand-file-name certfiles))
202           (delete-region b e)
203           (insert-buffer buffer)
204           (when (looking-at "^MIME-Version: 1.0$")
205             (delete-region (point) (progn (forward-line 1) (point))))
206           t)
207       (with-current-buffer (get-buffer-create smime-details-buffer)
208         (goto-char (point-max))
209         (insert-buffer buffer))
210       (kill-buffer buffer))))
211
212 ;; Sign+encrypt buffer
213
214 (defun smime-sign-buffer (&optional keyfile buffer)
215   "S/MIME sign BUFFER with key in KEYFILE.
216 KEYFILE should contain a PEM encoded key and certificate."
217   (interactive)
218   (with-current-buffer (or buffer (current-buffer))
219     (smime-sign-region
220      (point-min) (point-max) 
221      (or keyfile
222          (smime-get-key-by-email
223           (completing-read "Sign using which signature? " smime-keys nil nil
224                            (and (listp (car-safe smime-keys))
225                                 (caar smime-keys))))))))
226
227 (defun smime-encrypt-buffer (&optional certfiles buffer)
228   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
229 CERTFILES is a list of filenames, each file is expected to consist of
230 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
231 nil."
232   (interactive)
233   (with-current-buffer (or buffer (current-buffer))
234     (smime-encrypt-region 
235      (point-min) (point-max)
236      (or certfiles
237          (list (read-file-name "Recipient's S/MIME certificate: "
238                                smime-certificate-directory nil))))))
239
240 ;; Verify+decrypt region
241
242 (defun smime-verify-region (b e)
243   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
244         (CAs (cond (smime-CA-file
245                     (list "-CAfile" (expand-file-name smime-CA-file)))
246                    (smime-CA-directory
247                     (list "-CApath" (expand-file-name smime-CA-directory)))
248                    (t
249                     (error "No CA configured.")))))
250     (prog1
251         (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify" CAs)
252             (message "S/MIME message verified succesfully.")
253           (message "S/MIME message NOT verified successfully.")
254           nil)
255       (with-current-buffer (get-buffer-create smime-details-buffer)
256         (goto-char (point-max))
257         (insert-buffer buffer))
258       (kill-buffer buffer))))
259   
260 (defun smime-decrypt-region (b e keyfile)
261   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
262         CAs)
263     (when (apply 'smime-call-openssl-region b e buffer "smime" "-decrypt" 
264                  "-recip" keyfile)
265       
266       )
267     (with-current-buffer (get-buffer-create smime-details-buffer)
268       (goto-char (point-max))
269       (insert-buffer buffer))
270     (kill-buffer buffer)))
271   
272 ;; Verify+Decrypt buffer
273
274 (defun smime-verify-buffer (&optional buffer)
275   "Verify integrity of S/MIME message in BUFFER.
276 Uses current buffer if BUFFER is nil."
277   (interactive)
278   (with-current-buffer (or buffer (current-buffer))
279     (smime-verify-region (point-min) (point-max))))
280
281 (defun smime-decrypt-buffer (&optional buffer keyfile)
282   "Decrypt S/MIME message in BUFFER using KEYFILE.
283 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
284   (interactive)
285   (with-current-buffer (or buffer (current-buffer))
286     (smime-decrypt-region 
287      (point-min) (point-max)
288      (or keyfile
289          (smime-get-key-by-email
290           (completing-read "Decrypt with which key? " smime-keys nil nil
291                            (and (listp (car-safe smime-keys)) 
292                                 (caar smime-keys))))))))
293
294 ;; Find certificates
295
296 (defun smime-mail-to-domain (mailaddr)
297   (if (string-match "@" mailaddr)
298       (replace-match "." 'fixedcase 'literal mailaddr)
299     mailaddr))
300
301 (defun smime-cert-by-dns (mail)
302   (let* ((dig-dns-server smime-dns-server)
303          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
304          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
305          (certrr (with-current-buffer digbuf
306                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
307          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
308       (if cert
309           (with-current-buffer retbuf
310             (insert "-----BEGIN CERTIFICATE-----\n")
311             (let ((i 0) (len (length cert)))
312               (while (> (- len 64) i)
313                 (insert (substring cert i (+ i 64)) "\n")
314                 (setq i (+ i 64)))
315               (insert (substring cert i len) "\n"))
316             (insert "-----END CERTIFICATE-----\n"))
317         (kill-buffer retbuf)
318         (setq retbuf nil))
319       (kill-buffer digbuf)
320       retbuf))
321
322 ;; User interface.
323
324 (defvar smime-buffer "*SMIME*")
325
326 (defvar smime-mode-map nil)
327 (put 'smime-mode 'mode-class 'special)
328
329 (unless smime-mode-map
330   (setq smime-mode-map (make-sparse-keymap))
331   (suppress-keymap smime-mode-map)
332
333   (define-key smime-mode-map "q" 'smime-exit)
334   (define-key smime-mode-map "f" 'smime-certificate-info))
335
336 (defun smime-mode ()
337   "Major mode for browsing, viewing and fetching certificates.
338
339 All normal editing commands are switched off.
340 \\<smime-mode-map>
341
342 The following commands are available:
343
344 \\{smime-mode-map}"
345   (interactive)
346   (kill-all-local-variables)
347   (setq major-mode 'smime-mode)
348   (setq mode-name "SMIME")
349   (setq mode-line-process nil)
350   (use-local-map smime-mode-map)
351   (buffer-disable-undo)
352   (setq truncate-lines t)
353   (setq buffer-read-only t))
354
355 (defun smime-certificate-info (certfile)
356   (interactive "fCertificate file: ")
357   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
358     (switch-to-buffer buffer)
359     (erase-buffer)
360     (call-process smime-openssl-program nil buffer 'display
361                   "x509" "-in" (expand-file-name certfile) "-text")
362     (fundamental-mode)
363     (set-buffer-modified-p nil)
364     (toggle-read-only t)
365     (goto-char (point-min))))
366
367 (defun smime-draw-buffer ()
368   (with-current-buffer smime-buffer
369     (let (buffer-read-only)
370       (erase-buffer)
371       (insert "\nYour keys:\n")
372       (dolist (key smime-keys)
373         (insert 
374          (format "\t\t%s: %s\n" (car key) (cadr key))))
375       (insert "\nTrusted Certificate Authoritys:\n")
376       (insert "\nKnown Certificates:\n"))))
377
378 (defun smime ()
379   "Go to the SMIME buffer."
380   (interactive)
381   (unless (get-buffer smime-buffer)
382     (save-excursion
383       (set-buffer (get-buffer-create smime-buffer))
384       (smime-mode)))
385   (smime-draw-buffer)
386   (switch-to-buffer smime-buffer))
387
388 (defun smime-exit ()
389   "Quit the S/MIME buffer."
390   (interactive)
391   (kill-buffer (current-buffer)))
392
393 ;; Other functions
394
395 (defun smime-get-key-by-email (email)
396   (cadr (assoc email smime-keys)))
397
398 (provide 'smime)
399
400 ;;; smime.el ends here