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