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