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