Revision: miles@gnu.org--gnu-2005/gnus--devo--0--patch-151
[gnus] / lisp / smime.el
1 ;;; smime.el --- S/MIME support library
2 ;; Copyright (c) 2000, 2001, 2003, 2005 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <simon@josefsson.org>
5 ;; Keywords: SMIME X.509 PEM OpenSSL
6
7 ;; This file is part of GNU Emacs.
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., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, 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 from DNS and LDAP.
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 ;; 2005-02-13  retrieve certificates via LDAP
119
120 ;;; Code:
121
122 (require 'dig)
123 (require 'smime-ldap)
124 (require 'password)
125 (eval-when-compile (require 'cl))
126
127 (eval-and-compile
128   (cond
129    ((fboundp 'replace-in-string)
130     (defalias 'smime-replace-in-string 'replace-in-string))
131    ((fboundp 'replace-regexp-in-string)
132     (defun smime-replace-in-string  (string regexp newtext &optional literal)
133       "Replace all matches for REGEXP with NEWTEXT in STRING.
134 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
135 string containing the replacements.
136
137 This is a compatibility function for different Emacsen."
138       (replace-regexp-in-string regexp newtext string nil literal)))))
139
140 (defgroup smime nil
141   "S/MIME configuration."
142   :group 'mime)
143
144 (defcustom smime-keys nil
145   "*Map mail addresses to a file containing Certificate (and private key).
146 The file is assumed to be in PEM format. You can also associate additional
147 certificates to be sent with every message to each address."
148   :type '(repeat (list (string :tag "Mail address")
149                        (file :tag "File name")
150                        (repeat :tag "Additional certificate files"
151                                (file :tag "File name"))))
152   :group 'smime)
153
154 (defcustom smime-CA-directory nil
155   "*Directory containing certificates for CAs you trust.
156 Directory should contain files (in PEM format) named to the X.509
157 hash of the certificate.  This can be done using OpenSSL such as:
158
159 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`.0
160
161 where `ca.pem' is the file containing a PEM encoded X.509 CA
162 certificate."
163   :type '(choice (const :tag "none" nil)
164                  directory)
165   :group 'smime)
166
167 (defcustom smime-CA-file nil
168   "*Files containing certificates for CAs you trust.
169 File should contain certificates in PEM format."
170   :version "22.1"
171   :type '(choice (const :tag "none" nil)
172                  file)
173   :group 'smime)
174
175 (defcustom smime-certificate-directory "~/Mail/certs/"
176   "*Directory containing other people's certificates.
177 It should contain files named to the X.509 hash of the certificate,
178 and the files themself should be in PEM format."
179 ;The S/MIME library provide simple functionality for fetching
180 ;certificates into this directory, so there is no need to populate it
181 ;manually.
182   :type 'directory
183   :group 'smime)
184
185 (defcustom smime-openssl-program
186   (and (condition-case ()
187            (eq 0 (call-process "openssl" nil nil nil "version"))
188          (error nil))
189        "openssl")
190   "*Name of OpenSSL binary."
191   :type 'string
192   :group 'smime)
193
194 ;; OpenSSL option to select the encryption cipher
195
196 (defcustom smime-encrypt-cipher "-des3"
197   "*Cipher algorithm used for encryption."
198   :version "22.1"
199   :type '(choice (const :tag "Triple DES" "-des3")
200                  (const :tag "DES"  "-des")
201                  (const :tag "RC2 40 bits" "-rc2-40")
202                  (const :tag "RC2 64 bits" "-rc2-64")
203                  (const :tag "RC2 128 bits" "-rc2-128"))
204   :group 'smime)
205
206 (defcustom smime-crl-check nil
207   "*Check revocation status of signers certificate using CRLs.
208 Enabling this will have OpenSSL check the signers certificate
209 against a certificate revocation list (CRL).
210
211 For this to work the CRL must be up-to-date and since they are
212 normally updated quite often (ie. several times a day) you
213 probably need some tool to keep them up-to-date. Unfortunately
214 Gnus cannot do this for you.
215
216 The CRL should either be appended (in PEM format) to your
217 `smime-CA-file' or be located in a file (also in PEM format) in
218 your `smime-certificate-directory' named to the X.509 hash of the
219 certificate with .r0 as file name extension.
220
221 At least OpenSSL version 0.9.7 is required for this to work."
222   :type '(choice (const :tag "No check" nil)
223                  (const :tag "Check certificate" "-crl_check")
224                  (const :tag "Check certificate chain" "-crl_check_all"))
225   :group 'smime)
226
227 (defcustom smime-dns-server nil
228   "*DNS server to query certificates from.
229 If nil, use system defaults."
230   :version "22.1"
231   :type '(choice (const :tag "System defaults")
232                  string)
233   :group 'smime)
234
235 (defcustom smime-ldap-host-list nil
236   "A list of LDAP hosts with S/MIME user certificates.
237 If needed search base, binddn, passwd, etc. for the LDAP host
238 must be set in `ldap-host-parameters-alist'."
239   :type '(repeat (string :tag "Host name"))
240   :version "23.0" ;; No Gnus
241   :group 'smime)
242
243 (defvar smime-details-buffer "*OpenSSL output*")
244
245 ;; Use mm-util?
246 (eval-and-compile
247   (defalias 'smime-make-temp-file
248     (if (fboundp 'make-temp-file)
249         'make-temp-file
250       (lambda (prefix &optional dir-flag) ;; Simple implementation
251         (expand-file-name
252          (make-temp-name prefix)
253          (if (fboundp 'temp-directory)
254              (temp-directory)
255            temporary-file-directory))))))
256
257 ;; Password dialog function
258
259 (defun smime-ask-passphrase (&optional cache-key)
260   "Asks the passphrase to unlock the secret key.
261 If `cache-key' and `password-cache' is non-nil then cache the
262 password under `cache-key'."
263   (let ((passphrase
264          (password-read-and-add
265           "Passphrase for secret key (RET for no passphrase): " cache-key)))
266     (if (string= passphrase "")
267         nil
268       passphrase)))
269
270 ;; OpenSSL wrappers.
271
272 (defun smime-call-openssl-region (b e buf &rest args)
273   (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
274     (0 t)
275     (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
276     (2 (message "OpenSSL: One of the input files could not be read.") nil)
277     (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
278     (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
279     (t (error "Unknown OpenSSL exitcode") nil)))
280
281 (defun smime-make-certfiles (certfiles)
282   (if certfiles
283       (append (list "-certfile" (expand-file-name (car certfiles)))
284               (smime-make-certfiles (cdr certfiles)))))
285
286 ;; Sign+encrypt region
287
288 (defun smime-sign-region (b e keyfile)
289   "Sign region with certified key in KEYFILE.
290 If signing fails, the buffer is not modified.  Region is assumed to
291 have proper MIME tags.  KEYFILE is expected to contain a PEM encoded
292 private key and certificate as its car, and a list of additional
293 certificates to include in its caar.  If no additional certificates is
294 included, KEYFILE may be the file containing the PEM encoded private
295 key and certificate itself."
296   (smime-new-details-buffer)
297   (let* ((certfiles (and (cdr-safe keyfile) (cadr keyfile)))
298          (keyfile (or (car-safe keyfile) keyfile))
299          (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
300          (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
301          (tmpfile (smime-make-temp-file "smime")))
302     (if passphrase
303         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
304     (prog1
305         (when (prog1
306                   (apply 'smime-call-openssl-region b e (list buffer tmpfile)
307                          "smime" "-sign" "-signer" (expand-file-name keyfile)
308                          (append
309                           (smime-make-certfiles certfiles)
310                           (if passphrase
311                               (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
312                 (if passphrase
313                     (setenv "GNUS_SMIME_PASSPHRASE" "" t))
314                 (with-current-buffer smime-details-buffer
315                   (insert-file-contents tmpfile)
316                   (delete-file tmpfile)))
317           (delete-region b e)
318           (insert-buffer-substring buffer)
319           (goto-char b)
320           (when (looking-at "^MIME-Version: 1.0$")
321             (delete-region (point) (progn (forward-line 1) (point))))
322           t)
323       (with-current-buffer smime-details-buffer
324         (goto-char (point-max))
325         (insert-buffer-substring buffer))
326       (kill-buffer buffer))))
327
328 (defun smime-encrypt-region (b e certfiles)
329   "Encrypt region for recipients specified in CERTFILES.
330 If encryption fails, the buffer is not modified.  Region is assumed to
331 have proper MIME tags.  CERTFILES is a list of filenames, each file
332 is expected to contain of a PEM encoded certificate."
333   (smime-new-details-buffer)
334   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
335         (tmpfile (smime-make-temp-file "smime")))
336     (prog1
337         (when (prog1
338                   (apply 'smime-call-openssl-region b e (list buffer tmpfile)
339                          "smime" "-encrypt" smime-encrypt-cipher
340                          (mapcar 'expand-file-name certfiles))
341                 (with-current-buffer smime-details-buffer
342                   (insert-file-contents tmpfile)
343                   (delete-file tmpfile)))
344           (delete-region b e)
345           (insert-buffer-substring buffer)
346           (goto-char b)
347           (when (looking-at "^MIME-Version: 1.0$")
348             (delete-region (point) (progn (forward-line 1) (point))))
349           t)
350       (with-current-buffer smime-details-buffer
351         (goto-char (point-max))
352         (insert-buffer-substring buffer))
353       (kill-buffer buffer))))
354
355 ;; Sign+encrypt buffer
356
357 (defun smime-sign-buffer (&optional keyfile buffer)
358   "S/MIME sign BUFFER with key in KEYFILE.
359 KEYFILE should contain a PEM encoded key and certificate."
360   (interactive)
361   (with-current-buffer (or buffer (current-buffer))
362     (unless (smime-sign-region
363              (point-min) (point-max)
364              (if keyfile
365                  keyfile
366                (smime-get-key-with-certs-by-email
367                 (completing-read
368                  (concat "Sign using which key? "
369                          (if smime-keys (concat "(default " (caar smime-keys) ") ")
370                            ""))
371                  smime-keys nil nil (car-safe (car-safe smime-keys))))))
372       (error "Signing failed"))))
373
374 (defun smime-encrypt-buffer (&optional certfiles buffer)
375   "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
376 CERTFILES is a list of filenames, each file is expected to consist of
377 a PEM encoded key and certificate.  Uses current buffer if BUFFER is
378 nil."
379   (interactive)
380   (with-current-buffer (or buffer (current-buffer))
381     (unless (smime-encrypt-region
382              (point-min) (point-max)
383              (or certfiles
384                  (list (read-file-name "Recipient's S/MIME certificate: "
385                                        smime-certificate-directory nil))))
386       (error "Encryption failed"))))
387
388 ;; Verify+decrypt region
389
390 (defun smime-verify-region (b e)
391   "Verify S/MIME message in region between B and E.
392 Returns non-nil on success.
393 Any details (stdout and stderr) are left in the buffer specified by
394 `smime-details-buffer'."
395   (smime-new-details-buffer)
396   (let ((CAs (append (if smime-CA-file
397                          (list "-CAfile"
398                                (expand-file-name smime-CA-file)))
399                      (if smime-CA-directory
400                          (list "-CApath"
401                                (expand-file-name smime-CA-directory))))))
402     (unless CAs
403       (error "No CA configured"))
404     (if smime-crl-check
405         (add-to-list 'CAs smime-crl-check))
406     (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
407                "smime" "-verify" "-out" "/dev/null" CAs)
408         t
409       (insert-buffer-substring smime-details-buffer)
410       nil)))
411
412 (defun smime-noverify-region (b e)
413   "Verify integrity of S/MIME message in region between B and E.
414 Returns non-nil on success.
415 Any details (stdout and stderr) are left in the buffer specified by
416 `smime-details-buffer'."
417   (smime-new-details-buffer)
418   (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
419              "smime" "-verify" "-noverify" "-out" '("/dev/null"))
420       t
421     (insert-buffer-substring smime-details-buffer)
422     nil))
423
424 (eval-when-compile
425   (defvar from))
426
427 (defun smime-decrypt-region (b e keyfile)
428   "Decrypt S/MIME message in region between B and E with key in KEYFILE.
429 On success, replaces region with decrypted data and return non-nil.
430 Any details (stderr on success, stdout and stderr on error) are left
431 in the buffer specified by `smime-details-buffer'."
432   (smime-new-details-buffer)
433   (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
434         CAs (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
435         (tmpfile (smime-make-temp-file "smime")))
436     (if passphrase
437         (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
438     (if (prog1
439             (apply 'smime-call-openssl-region b e
440                    (list buffer tmpfile)
441                    "smime" "-decrypt" "-recip" (expand-file-name keyfile)
442                    (if passphrase
443                        (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
444           (if passphrase
445               (setenv "GNUS_SMIME_PASSPHRASE" "" t))
446           (with-current-buffer smime-details-buffer
447             (insert-file-contents tmpfile)
448             (delete-file tmpfile)))
449         (progn
450           (delete-region b e)
451           (when (boundp 'from)
452             ;; `from' is dynamically bound in mm-dissect.
453             (insert "From: " from "\n"))
454           (insert-buffer-substring buffer)
455           (kill-buffer buffer)
456           t)
457       (with-current-buffer smime-details-buffer
458         (insert-buffer-substring buffer))
459       (kill-buffer buffer)
460       (delete-region b e)
461       (insert-buffer-substring smime-details-buffer)
462       nil)))
463
464 ;; Verify+Decrypt buffer
465
466 (defun smime-verify-buffer (&optional buffer)
467   "Verify integrity of S/MIME message in BUFFER.
468 Uses current buffer if BUFFER is nil. Returns non-nil on success.
469 Any details (stdout and stderr) are left in the buffer specified by
470 `smime-details-buffer'."
471   (interactive)
472   (with-current-buffer (or buffer (current-buffer))
473     (smime-verify-region (point-min) (point-max))))
474
475 (defun smime-noverify-buffer (&optional buffer)
476   "Verify integrity of S/MIME message in BUFFER.
477 Does NOT verify validity of certificate (only message integrity).
478 Uses current buffer if BUFFER is nil. Returns non-nil on success.
479 Any details (stdout and stderr) are left in the buffer specified by
480 `smime-details-buffer'."
481   (interactive)
482   (with-current-buffer (or buffer (current-buffer))
483     (smime-noverify-region (point-min) (point-max))))
484
485 (defun smime-decrypt-buffer (&optional buffer keyfile)
486   "Decrypt S/MIME message in BUFFER using KEYFILE.
487 Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
488 On success, replaces data in buffer and return non-nil.
489 Any details (stderr on success, stdout and stderr on error) are left
490 in the buffer specified by `smime-details-buffer'."
491   (interactive)
492   (with-current-buffer (or buffer (current-buffer))
493     (smime-decrypt-region
494      (point-min) (point-max)
495      (expand-file-name
496       (or keyfile
497           (smime-get-key-by-email
498            (completing-read
499             (concat "Decipher using which key? "
500                     (if smime-keys (concat "(default " (caar smime-keys) ") ")
501                       ""))
502             smime-keys nil nil (car-safe (car-safe smime-keys)))))))))
503
504 ;; Various operations
505
506 (defun smime-new-details-buffer ()
507   (with-current-buffer (get-buffer-create smime-details-buffer)
508     (erase-buffer)))
509
510 (defun smime-pkcs7-region (b e)
511   "Convert S/MIME message between points B and E into a PKCS7 message."
512   (smime-new-details-buffer)
513   (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
514     (delete-region b e)
515     (insert-buffer-substring smime-details-buffer)
516     t))
517
518 (defun smime-pkcs7-certificates-region (b e)
519   "Extract any certificates enclosed in PKCS7 message between points B and E."
520   (smime-new-details-buffer)
521   (when (smime-call-openssl-region
522          b e smime-details-buffer "pkcs7" "-print_certs" "-text")
523     (delete-region b e)
524     (insert-buffer-substring smime-details-buffer)
525     t))
526
527 (defun smime-pkcs7-email-region (b e)
528   "Get email addresses contained in certificate between points B and E.
529 A string or a list of strings is returned."
530   (smime-new-details-buffer)
531   (when (smime-call-openssl-region
532          b e smime-details-buffer "x509" "-email" "-noout")
533     (delete-region b e)
534     (insert-buffer-substring smime-details-buffer)
535     t))
536
537 ;; Utility functions
538
539 (defun smime-get-certfiles (keyfile keys)
540   (if keys
541       (let ((curkey (car keys))
542             (otherkeys (cdr keys)))
543         (if (string= keyfile (cadr curkey))
544             (caddr curkey)
545           (smime-get-certfiles keyfile otherkeys)))))
546
547 (defun smime-buffer-as-string-region (b e)
548   "Return each line in region between B and E as a list of strings."
549   (save-excursion
550     (goto-char b)
551     (let (res)
552       (while (< (point) e)
553         (let ((str (buffer-substring (point) (point-at-eol))))
554           (unless (string= "" str)
555             (push str res)))
556         (forward-line))
557       res)))
558
559 ;; Find certificates
560
561 (defun smime-mail-to-domain (mailaddr)
562   (if (string-match "@" mailaddr)
563       (replace-match "." 'fixedcase 'literal mailaddr)
564     mailaddr))
565
566 (defun smime-cert-by-dns (mail)
567   "Find certificate via DNS for address MAIL."
568   (let* ((dig-dns-server smime-dns-server)
569          (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
570          (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
571          (certrr (with-current-buffer digbuf
572                    (dig-extract-rr (smime-mail-to-domain mail) "cert")))
573          (cert (and certrr (dig-rr-get-pkix-cert certrr))))
574       (if cert
575           (with-current-buffer retbuf
576             (insert "-----BEGIN CERTIFICATE-----\n")
577             (let ((i 0) (len (length cert)))
578               (while (> (- len 64) i)
579                 (insert (substring cert i (+ i 64)) "\n")
580                 (setq i (+ i 64)))
581               (insert (substring cert i len) "\n"))
582             (insert "-----END CERTIFICATE-----\n"))
583         (kill-buffer retbuf)
584         (setq retbuf nil))
585       (kill-buffer digbuf)
586       retbuf))
587
588 (defun smime-cert-by-ldap-1 (mail host)
589   "Get cetificate for MAIL from the ldap server at HOST."
590   (let ((ldapresult (smime-ldap-search (concat "mail=" mail)
591                                        host '("userCertificate") nil))
592         (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
593         cert)
594     (if (>= (length ldapresult) 1)
595         (with-current-buffer retbuf
596           ;; Certificates on LDAP servers _should_ be in DER format,
597           ;; but there are some servers out there that distributes the
598           ;; certificates in PEM format (with or without
599           ;; header/footer) so we try to handle them anyway.
600           (if (or (string= (substring (cadaar ldapresult) 0 27)
601                            "-----BEGIN CERTIFICATE-----")
602                   (string= (substring (cadaar ldapresult) 0 3)
603                            "MII"))
604               (setq cert
605                     (smime-replace-in-string
606                      (cadaar ldapresult)
607                      (concat "\\(\n\\|\r\\|-----BEGIN CERTIFICATE-----\\|"
608                              "-----END CERTIFICATE-----\\)")
609                      "" t))
610             (setq cert (base64-encode-string (cadaar ldapresult) t)))
611           (insert "-----BEGIN CERTIFICATE-----\n")
612           (let ((i 0) (len (length cert)))
613             (while (> (- len 64) i)
614               (insert (substring cert i (+ i 64)) "\n")
615               (setq i (+ i 64)))
616             (insert (substring cert i len) "\n"))
617           (insert "-----END CERTIFICATE-----\n"))
618       (kill-buffer retbuf)
619       (setq retbuf nil))
620     retbuf))
621
622 (defun smime-cert-by-ldap (mail)
623   "Find certificate via LDAP for address MAIL."
624   (if smime-ldap-host-list
625       (catch 'certbuf
626         (dolist (host smime-ldap-host-list)
627           (let ((retbuf (smime-cert-by-ldap-1 mail host)))
628             (when retbuf
629               (throw 'certbuf retbuf)))))))
630
631 ;; User interface.
632
633 (defvar smime-buffer "*SMIME*")
634
635 (defvar smime-mode-map nil)
636 (put 'smime-mode 'mode-class 'special)
637
638 (unless smime-mode-map
639   (setq smime-mode-map (make-sparse-keymap))
640   (suppress-keymap smime-mode-map)
641
642   (define-key smime-mode-map "q" 'smime-exit)
643   (define-key smime-mode-map "f" 'smime-certificate-info))
644
645 (defun smime-mode ()
646   "Major mode for browsing, viewing and fetching certificates.
647
648 All normal editing commands are switched off.
649 \\<smime-mode-map>
650
651 The following commands are available:
652
653 \\{smime-mode-map}"
654   (interactive)
655   (kill-all-local-variables)
656   (setq major-mode 'smime-mode)
657   (setq mode-name "SMIME")
658   (setq mode-line-process nil)
659   (use-local-map smime-mode-map)
660   (buffer-disable-undo)
661   (setq truncate-lines t)
662   (setq buffer-read-only t)
663   (gnus-run-mode-hooks 'smime-mode-hook))
664
665 (defun smime-certificate-info (certfile)
666   (interactive "fCertificate file: ")
667   (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
668     (switch-to-buffer buffer)
669     (erase-buffer)
670     (call-process smime-openssl-program nil buffer 'display
671                   "x509" "-in" (expand-file-name certfile) "-text")
672     (fundamental-mode)
673     (set-buffer-modified-p nil)
674     (toggle-read-only t)
675     (goto-char (point-min))))
676
677 (defun smime-draw-buffer ()
678   (with-current-buffer smime-buffer
679     (let (buffer-read-only)
680       (erase-buffer)
681       (insert "\nYour keys:\n")
682       (dolist (key smime-keys)
683         (insert
684          (format "\t\t%s: %s\n" (car key) (cadr key))))
685       (insert "\nTrusted Certificate Authoritys:\n")
686       (insert "\nKnown Certificates:\n"))))
687
688 (defun smime ()
689   "Go to the SMIME buffer."
690   (interactive)
691   (unless (get-buffer smime-buffer)
692     (save-excursion
693       (set-buffer (get-buffer-create smime-buffer))
694       (smime-mode)))
695   (smime-draw-buffer)
696   (switch-to-buffer smime-buffer))
697
698 (defun smime-exit ()
699   "Quit the S/MIME buffer."
700   (interactive)
701   (kill-buffer (current-buffer)))
702
703 ;; Other functions
704
705 (defun smime-get-key-by-email (email)
706   (cadr (assoc email smime-keys)))
707
708 (defun smime-get-key-with-certs-by-email (email)
709   (cdr (assoc email smime-keys)))
710
711 (provide 'smime)
712
713 ;;; arch-tag: e3f9b938-5085-4510-8a11-6625269c9a9e
714 ;;; smime.el ends here