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