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