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