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