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