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