(smime-CA-directory): Rename from `smime-CAs'.
[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 ;; NOT provided (yet).
30 ;;
31 ;; It uses OpenSSL (tested with version 0.9.5a) 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 (defgroup smime nil
106   "S/MIME configuration.")
107
108 (defcustom smime-keys nil
109   "Map mail addresses to a file containing Certificate (and private key).
110 The file is assumed to be in PEM format and not encrypted."
111   :type '(repeat (list (string :tag "Mail address")
112                        (file :tag "File name")))
113   :group 'smime)
114
115 (defcustom smime-CA-directory ""
116   "Directory containing certificates for CAs you trust.
117 Directory should contain files (in PEM format) named to the X.509
118 hash of the certificate."
119   :type '(choice (const :tag "none" nil)
120                  directory)
121   :group 'smime)
122
123 (defcustom smime-CA-file ""
124   "Files containing certificates for CAs you trust.
125 File should be in PEM format."
126   :type '(choice (const :tag "none" nil)
127                  file)
128   :group 'smime)
129
130 (defcustom smime-certificate-directory "~/Mail/certs/"
131   "Directory containing other people's certificates.
132 It should contain files named to the X.509 hash of the certificate,
133 and the files themself should be in PEM format.
134 The S/MIME library provide simple functionality for fetching
135 certificates into this directory, so there is no need to populate it
136 manually."
137   :type 'directory
138   :group 'smime)
139
140 (defcustom smime-openssl-program "openssl"
141   "Name of OpenSSL binary."
142   :type 'string
143   :group 'smime)
144
145 ;; OpenSSL wrappers.
146
147 (defun smime-call-openssl-region (b e buf &rest args)
148   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
149     (0 t)
150     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
151     (2 (message "OpenSSL: One of the input files could not be read.") nil)
152     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
153     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
154     (t (error "Unknown OpenSSL exitcode") nil)))
155
156 ;; Sign+encrypt region
157
158 (defun smime-sign-region (b e keyfile)
159   "Sign region with certified key in KEYFILE.
160 If signing fails, the buffer is not modified.  Region is assumed to
161 have proper MIME tags.  KEYFILE is expected to contain a PEM encoded
162 private key and certificate."
163   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
164     (prog1
165         (when (smime-call-openssl-region b e buffer "smime" "-sign"
166                                          "-signer" (expand-file-name keyfile))
167           (delete-region b e)
168           (insert-buffer buffer)
169           (when (looking-at "^MIME-Version: 1.0$")
170             (delete-region (point) (progn (forward-line 1) (point))))
171           t)
172       (kill-buffer buffer))))
173
174 (defun smime-encrypt-region (b e certfiles)
175   "Encrypt region for recipients specified in CERTFILES.
176 If encryption fails, the buffer is not modified.  Region is assumed to
177 have proper MIME tags.  CERTFILES is a list of filenames, each file
178 is expected to contain of a PEM encoded certificate."
179   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
180     (prog1
181         (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
182                      (mapcar 'expand-file-name certfiles))
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       (kill-buffer buffer))))
189
190 ;; Sign+encrypt buffer
191
192 (defun smime-sign-buffer (&optional keyfile buffer)
193   "S/MIME sign BUFFER with key in KEYFILE.
194 KEYFILE should contain a PEM encoded key and certificate."
195   (interactive)
196   (with-current-buffer (or buffer (current-buffer))
197     (smime-sign-region
198      (point-min) (point-max) 
199      (or keyfile
200          (smime-get-key-by-email
201           (completing-read "Sign using which signature? " smime-keys nil nil
202                            (and (listp (car-safe smime-keys))
203                                 (caar smime-keys))))))))
204
205 (defun smime-encrypt-buffer (&optional certfiles buffer)
206   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
207 CERTFILES is a list of filenames, each file is expected to consist of
208 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
209 nil."
210   (interactive)
211   (with-current-buffer (or buffer (current-buffer))
212     (smime-encrypt-region 
213      (point-min) (point-max)
214      (or certfiles
215          (list (read-file-name "Recipient's S/MIME certificate: "
216                                smime-certificate-directory nil))))))
217
218 ;; Verify+decrypt region
219
220 (defun smime-verify-region (b e)
221   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
222         (CAs (cond (smime-CA-file
223                     (list "-CAfile" (expand-file-name smime-CA-file)))
224                    (smime-CA-directory
225                     (list "-CApath" (expand-file-name smime-CA-directory)))
226                    (t
227                     (error "No CA configured.")))))
228     (prog1
229         (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify" CAs)
230             (message "S/MIME message verified succesfully.")
231           (message "S/MIME message NOT verified successfully.")
232           nil)
233       (kill-buffer buffer))))
234   
235 (defun smime-decrypt-region (b e keyfile)
236   (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
237         CAs)
238     (when (apply 'smime-call-openssl-region b e buffer "smime" "-decrypt" 
239                  "-recip" keyfile)
240       
241       )
242     (kill-buffer buffer)))
243   
244 ;; Verify+Decrypt buffer
245
246 (defun smime-verify-buffer (&optional buffer)
247   "Verify integrity of S/MIME message in BUFFER.
248 Uses current buffer if BUFFER is nil."
249   (interactive)
250   (with-current-buffer (or buffer (current-buffer))
251     (smime-verify-region (point-min) (point-max))))
252
253 (defun smime-decrypt-buffer (&optional buffer keyfile)
254   "Decrypt S/MIME message in BUFFER using KEYFILE.
255 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
256   (interactive)
257   (with-current-buffer (or buffer (current-buffer))
258     (smime-decrypt-region 
259      (point-min) (point-max)
260      (or keyfile
261          (smime-get-key-by-email
262           (completing-read "Decrypt with which key? " smime-keys nil nil
263                            (and (listp (car-safe smime-keys)) 
264                                 (caar smime-keys))))))))
265
266 ;; User interface.
267
268 (defvar smime-buffer "*SMIME*")
269
270 (defvar smime-mode-map nil)
271 (put 'smime-mode 'mode-class 'special)
272
273 (unless smime-mode-map
274   (setq smime-mode-map (make-sparse-keymap))
275   (suppress-keymap smime-mode-map)
276
277   (define-key smime-mode-map "q" 'smime-exit)
278   (define-key smime-mode-map "f" 'smime-certificate-info))
279
280 (defun smime-mode ()
281   "Major mode for browsing, viewing and fetching certificates.
282
283 All normal editing commands are switched off.
284 \\<smime-mode-map>
285
286 The following commands are available:
287
288 \\{smime-mode-map}"
289   (interactive)
290   (kill-all-local-variables)
291   (setq major-mode 'smime-mode)
292   (setq mode-name "SMIME")
293   (setq mode-line-process nil)
294   (use-local-map smime-mode-map)
295   (buffer-disable-undo)
296   (setq truncate-lines t)
297   (setq buffer-read-only t))
298
299 (defun smime-certificate-info (certfile)
300   (interactive "fCertificate file: ")
301   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
302     (switch-to-buffer buffer)
303     (erase-buffer)
304     (call-process smime-openssl-program nil buffer 'display
305                   "x509" "-in" (expand-file-name certfile) "-text")
306     (fundamental-mode)
307     (set-buffer-modified-p nil)
308     (toggle-read-only t)
309     (goto-char (point-min))))
310
311 (defun smime-draw-buffer ()
312   (with-current-buffer smime-buffer
313     (let (buffer-read-only)
314       (erase-buffer)
315       (insert "\nYour keys:\n")
316       (dolist (key smime-keys)
317         (insert 
318          (format "\t\t%s: %s\n" (car key) (cadr key))))
319       (insert "\nTrusted Certificate Authoritys:\n")
320       (insert "\nKnown Certificates:\n"))))
321
322 (defun smime ()
323   "Go to the SMIME buffer."
324   (interactive)
325   (unless (get-buffer smime-buffer)
326     (save-excursion
327       (set-buffer (get-buffer-create smime-buffer))
328       (smime-mode)))
329   (smime-draw-buffer)
330   (switch-to-buffer smime-buffer))
331
332 (defun smime-exit ()
333   "Quit the S/MIME buffer."
334   (interactive)
335   (kill-buffer (current-buffer)))
336
337 ;; Other functions
338
339 (defun smime-get-key-by-email (email)
340   (cadr (assoc email smime-keys)))
341
342 (provide 'smime)
343
344 ;;; smime.el ends here