1 ;;; smime.el --- S/MIME support library
2 ;; Copyright (c) 2000, 2001, 2003, 2005 Free Software Foundation, Inc.
4 ;; Author: Simon Josefsson <simon@josefsson.org>
5 ;; Keywords: SMIME X.509 PEM OpenSSL
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published
11 ;; by the Free Software Foundation; either version 2, or (at your
12 ;; option) any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful, but
15 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 ;; General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
26 ;; This library perform S/MIME operations from within Emacs.
28 ;; Functions for fetching certificates from public repositories are
29 ;; provided, currently from DNS and LDAP.
31 ;; It uses OpenSSL (tested with version 0.9.5a and 0.9.6) for signing,
32 ;; encryption and decryption.
34 ;; Some general knowledge of S/MIME, X.509, PKCS#12, PEM etc is
35 ;; probably required to use this library in any useful way.
36 ;; Especially, don't expect this library to buy security for you. If
37 ;; you don't understand what you are doing, you're as likely to lose
38 ;; security than gain any by using this library.
40 ;; This library is not intended to provide a "raw" API for S/MIME,
41 ;; PKCSx or similar, it's intended to perform common operations
42 ;; done on messages encoded in these formats. The terminology chosen
45 ;; The home of this file is in Gnus CVS, but also available from
46 ;; http://josefsson.org/smime.html.
48 ;;; Quick introduction:
50 ;; Get your S/MIME certificate from VeriSign or someplace. I used
51 ;; Netscape to generate the key and certificate request and stuff, and
52 ;; Netscape can export the key into PKCS#12 format.
54 ;; Enter OpenSSL. To be able to use this library, it need to have the
55 ;; SMIME key readable in PEM format. OpenSSL is used to convert the
58 ;; $ openssl pkcs12 -in mykey.p12 -clcerts -nodes > mykey.pem
61 ;; Now, use M-x customize-variable smime-keys and add mykey.pem as
64 ;; Now you should be able to sign messages! Create a buffer and write
65 ;; something and run M-x smime-sign-buffer RET RET and you should see
66 ;; your message MIME armoured and a signature. Encryption, M-x
67 ;; smime-encrypt-buffer, should also work.
69 ;; To be able to verify messages you need to build up trust with
70 ;; someone. Perhaps you trust the CA that issued your certificate, at
71 ;; least I did, so I export it's certificates from my PKCS#12
74 ;; $ openssl pkcs12 -in mykey.p12 -cacerts -nodes > cacert.pem
77 ;; Now, use M-x customize-variable smime-CAs and add cacert.pem as a
80 ;; You should now be able to sign messages, and even verify messages
81 ;; sent by others that use the same CA as you.
85 ;; Don't complain that this package doesn't do encrypted PEM files,
86 ;; submit a patch instead. I store my keys in a safe place, so I
87 ;; didn't need the encryption. Also, programming was made easier by
88 ;; that decision. One might think that this even influenced were I
89 ;; store my keys, and one would probably be right. :-)
91 ;; Update: Mathias Herberts sent the patch. However, it uses
92 ;; environment variables to pass the password to OpenSSL, which is
93 ;; slightly insecure. Hence a new todo: use a better -passin method.
95 ;; Cache password for e.g. 1h
97 ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
101 ;; I would include pointers to introductory text on concepts used in
102 ;; this library here, but the material I've read are so horrible I
103 ;; don't want to recomend them.
105 ;; Why can't someone write a simple introduction to all this stuff?
106 ;; Until then, much of this resemble security by obscurity.
108 ;; Also, I'm not going to mention anything about the wonders of
109 ;; cryptopolitics. Oops, I just did.
113 ;;; Revision history:
115 ;; 2000-06-05 initial version, committed to Gnus CVS contrib/
116 ;; 2000-10-28 retrieve certificates via DNS CERT RRs
117 ;; 2001-10-14 posted to gnu.emacs.sources
118 ;; 2005-02-13 retrieve certificates via LDAP
123 (require 'smime-ldap)
125 (eval-when-compile (require 'cl))
128 "S/MIME configuration.")
130 (defcustom smime-keys nil
131 "*Map mail addresses to a file containing Certificate (and private key).
132 The file is assumed to be in PEM format. You can also associate additional
133 certificates to be sent with every message to each address."
134 :type '(repeat (list (string :tag "Mail address")
135 (file :tag "File name")
136 (repeat :tag "Additional certificate files"
137 (file :tag "File name"))))
140 (defcustom smime-CA-directory nil
141 "*Directory containing certificates for CAs you trust.
142 Directory should contain files (in PEM format) named to the X.509
143 hash of the certificate. This can be done using OpenSSL such as:
145 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`.0
147 where `ca.pem' is the file containing a PEM encoded X.509 CA
149 :type '(choice (const :tag "none" nil)
153 (defcustom smime-CA-file nil
154 "*Files containing certificates for CAs you trust.
155 File should contain certificates in PEM format."
157 :type '(choice (const :tag "none" nil)
161 (defcustom smime-certificate-directory "~/Mail/certs/"
162 "*Directory containing other people's certificates.
163 It should contain files named to the X.509 hash of the certificate,
164 and the files themself should be in PEM format."
165 ;The S/MIME library provide simple functionality for fetching
166 ;certificates into this directory, so there is no need to populate it
171 (defcustom smime-openssl-program
172 (and (condition-case ()
173 (eq 0 (call-process "openssl" nil nil nil "version"))
176 "*Name of OpenSSL binary."
180 ;; OpenSSL option to select the encryption cipher
182 (defcustom smime-encrypt-cipher "-des3"
183 "*Cipher algorithm used for encryption."
185 :type '(choice (const :tag "Triple DES" "-des3")
186 (const :tag "DES" "-des")
187 (const :tag "RC2 40 bits" "-rc2-40")
188 (const :tag "RC2 64 bits" "-rc2-64")
189 (const :tag "RC2 128 bits" "-rc2-128"))
192 (defcustom smime-crl-check nil
193 "*Check revocation status of signers certificate using CRLs.
194 Enabling this will have OpenSSL check the signers certificate
195 against a certificate revocation list (CRL).
197 For this to work the CRL must be up-to-date and since they are
198 normally updated quite often (ie. several times a day) you
199 probably need some tool to keep them up-to-date. Unfortunately
200 Gnus cannot do this for you.
202 The CRL should either be appended (in PEM format) to your
203 `smime-CA-file' or be located in a file (also in PEM format) in
204 your `smime-certificate-directory' named to the X.509 hash of the
205 certificate with .r0 as file name extension.
207 At least OpenSSL version 0.9.7 is required for this to work."
208 :type '(choice (const :tag "No check" nil)
209 (const :tag "Check certificate" "-crl_check")
210 (const :tag "Check certificate chain" "-crl_check_all"))
213 (defcustom smime-dns-server nil
214 "*DNS server to query certificates from.
215 If nil, use system defaults."
217 :type '(choice (const :tag "System defaults")
221 (defcustom smime-ldap-host-list nil
222 "A list of LDAP hosts with S/MIME user certificates.
223 If needed search base, binddn, passwd, etc. for the LDAP host
224 must be set in `ldap-host-parameters-alist'."
225 :type '(repeat (string :tag "Host name"))
228 (defvar smime-details-buffer "*OpenSSL output*")
232 (defalias 'smime-make-temp-file
233 (if (fboundp 'make-temp-file)
235 (lambda (prefix &optional dir-flag) ;; Simple implementation
237 (make-temp-name prefix)
238 (if (fboundp 'temp-directory)
240 temporary-file-directory))))))
242 ;; Password dialog function
244 (defun smime-ask-passphrase (&optional cache-key)
245 "Asks the passphrase to unlock the secret key.
246 If `cache-key' and `password-cache' is non-nil then cache the
247 password under `cache-key'."
249 (password-read-and-add
250 "Passphrase for secret key (RET for no passphrase): " cache-key)))
251 (if (string= passphrase "")
257 (defun smime-call-openssl-region (b e buf &rest args)
258 (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
260 (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
261 (2 (message "OpenSSL: One of the input files could not be read.") nil)
262 (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
263 (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
264 (t (error "Unknown OpenSSL exitcode") nil)))
266 (defun smime-make-certfiles (certfiles)
268 (append (list "-certfile" (expand-file-name (car certfiles)))
269 (smime-make-certfiles (cdr certfiles)))))
271 ;; Sign+encrypt region
273 (defun smime-sign-region (b e keyfile)
274 "Sign region with certified key in KEYFILE.
275 If signing fails, the buffer is not modified. Region is assumed to
276 have proper MIME tags. KEYFILE is expected to contain a PEM encoded
277 private key and certificate as its car, and a list of additional
278 certificates to include in its caar. If no additional certificates is
279 included, KEYFILE may be the file containing the PEM encoded private
280 key and certificate itself."
281 (smime-new-details-buffer)
282 (let* ((certfiles (and (cdr-safe keyfile) (cadr keyfile)))
283 (keyfile (or (car-safe keyfile) keyfile))
284 (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
285 (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
286 (tmpfile (smime-make-temp-file "smime")))
288 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
291 (apply 'smime-call-openssl-region b e (list buffer tmpfile)
292 "smime" "-sign" "-signer" (expand-file-name keyfile)
294 (smime-make-certfiles certfiles)
296 (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
298 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
299 (with-current-buffer smime-details-buffer
300 (insert-file-contents tmpfile)
301 (delete-file tmpfile)))
303 (insert-buffer-substring buffer)
305 (when (looking-at "^MIME-Version: 1.0$")
306 (delete-region (point) (progn (forward-line 1) (point))))
308 (with-current-buffer smime-details-buffer
309 (goto-char (point-max))
310 (insert-buffer-substring buffer))
311 (kill-buffer buffer))))
313 (defun smime-encrypt-region (b e certfiles)
314 "Encrypt region for recipients specified in CERTFILES.
315 If encryption fails, the buffer is not modified. Region is assumed to
316 have proper MIME tags. CERTFILES is a list of filenames, each file
317 is expected to contain of a PEM encoded certificate."
318 (smime-new-details-buffer)
319 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
320 (tmpfile (smime-make-temp-file "smime")))
323 (apply 'smime-call-openssl-region b e (list buffer tmpfile)
324 "smime" "-encrypt" smime-encrypt-cipher
325 (mapcar 'expand-file-name certfiles))
326 (with-current-buffer smime-details-buffer
327 (insert-file-contents tmpfile)
328 (delete-file tmpfile)))
330 (insert-buffer-substring buffer)
332 (when (looking-at "^MIME-Version: 1.0$")
333 (delete-region (point) (progn (forward-line 1) (point))))
335 (with-current-buffer smime-details-buffer
336 (goto-char (point-max))
337 (insert-buffer-substring buffer))
338 (kill-buffer buffer))))
340 ;; Sign+encrypt buffer
342 (defun smime-sign-buffer (&optional keyfile buffer)
343 "S/MIME sign BUFFER with key in KEYFILE.
344 KEYFILE should contain a PEM encoded key and certificate."
346 (with-current-buffer (or buffer (current-buffer))
347 (unless (smime-sign-region
348 (point-min) (point-max)
351 (smime-get-key-with-certs-by-email
353 (concat "Sign using which key? "
354 (if smime-keys (concat "(default " (caar smime-keys) ") ")
356 smime-keys nil nil (car-safe (car-safe smime-keys))))))
357 (error "Signing failed"))))
359 (defun smime-encrypt-buffer (&optional certfiles buffer)
360 "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
361 CERTFILES is a list of filenames, each file is expected to consist of
362 a PEM encoded key and certificate. Uses current buffer if BUFFER is
365 (with-current-buffer (or buffer (current-buffer))
366 (unless (smime-encrypt-region
367 (point-min) (point-max)
369 (list (read-file-name "Recipient's S/MIME certificate: "
370 smime-certificate-directory nil))))
371 (error "Encryption failed"))))
373 ;; Verify+decrypt region
375 (defun smime-verify-region (b e)
376 "Verify S/MIME message in region between B and E.
377 Returns non-nil on success.
378 Any details (stdout and stderr) are left in the buffer specified by
379 `smime-details-buffer'."
380 (smime-new-details-buffer)
381 (let ((CAs (append (if smime-CA-file
383 (expand-file-name smime-CA-file)))
384 (if smime-CA-directory
386 (expand-file-name smime-CA-directory))))))
388 (error "No CA configured"))
390 (add-to-list 'CAs smime-crl-check))
391 (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
392 "smime" "-verify" "-out" "/dev/null" CAs)
394 (insert-buffer-substring smime-details-buffer)
397 (defun smime-noverify-region (b e)
398 "Verify integrity of S/MIME message in region between B and E.
399 Returns non-nil on success.
400 Any details (stdout and stderr) are left in the buffer specified by
401 `smime-details-buffer'."
402 (smime-new-details-buffer)
403 (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
404 "smime" "-verify" "-noverify" "-out" '("/dev/null"))
406 (insert-buffer-substring smime-details-buffer)
412 (defun smime-decrypt-region (b e keyfile)
413 "Decrypt S/MIME message in region between B and E with key in KEYFILE.
414 On success, replaces region with decrypted data and return non-nil.
415 Any details (stderr on success, stdout and stderr on error) are left
416 in the buffer specified by `smime-details-buffer'."
417 (smime-new-details-buffer)
418 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
419 CAs (passphrase (smime-ask-passphrase (expand-file-name keyfile)))
420 (tmpfile (smime-make-temp-file "smime")))
422 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
424 (apply 'smime-call-openssl-region b e
425 (list buffer tmpfile)
426 "smime" "-decrypt" "-recip" (expand-file-name keyfile)
428 (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
430 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
431 (with-current-buffer smime-details-buffer
432 (insert-file-contents tmpfile)
433 (delete-file tmpfile)))
437 ;; `from' is dynamically bound in mm-dissect.
438 (insert "From: " from "\n"))
439 (insert-buffer-substring buffer)
442 (with-current-buffer smime-details-buffer
443 (insert-buffer-substring buffer))
446 (insert-buffer-substring smime-details-buffer)
449 ;; Verify+Decrypt buffer
451 (defun smime-verify-buffer (&optional buffer)
452 "Verify integrity of S/MIME message in BUFFER.
453 Uses current buffer if BUFFER is nil. Returns non-nil on success.
454 Any details (stdout and stderr) are left in the buffer specified by
455 `smime-details-buffer'."
457 (with-current-buffer (or buffer (current-buffer))
458 (smime-verify-region (point-min) (point-max))))
460 (defun smime-noverify-buffer (&optional buffer)
461 "Verify integrity of S/MIME message in BUFFER.
462 Does NOT verify validity of certificate (only message integrity).
463 Uses current buffer if BUFFER is nil. Returns non-nil on success.
464 Any details (stdout and stderr) are left in the buffer specified by
465 `smime-details-buffer'."
467 (with-current-buffer (or buffer (current-buffer))
468 (smime-noverify-region (point-min) (point-max))))
470 (defun smime-decrypt-buffer (&optional buffer keyfile)
471 "Decrypt S/MIME message in BUFFER using KEYFILE.
472 Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
473 On success, replaces data in buffer and return non-nil.
474 Any details (stderr on success, stdout and stderr on error) are left
475 in the buffer specified by `smime-details-buffer'."
477 (with-current-buffer (or buffer (current-buffer))
478 (smime-decrypt-region
479 (point-min) (point-max)
482 (smime-get-key-by-email
484 (concat "Decipher using which key? "
485 (if smime-keys (concat "(default " (caar smime-keys) ") ")
487 smime-keys nil nil (car-safe (car-safe smime-keys)))))))))
489 ;; Various operations
491 (defun smime-new-details-buffer ()
492 (with-current-buffer (get-buffer-create smime-details-buffer)
495 (defun smime-pkcs7-region (b e)
496 "Convert S/MIME message between points B and E into a PKCS7 message."
497 (smime-new-details-buffer)
498 (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
500 (insert-buffer-substring smime-details-buffer)
503 (defun smime-pkcs7-certificates-region (b e)
504 "Extract any certificates enclosed in PKCS7 message between points B and E."
505 (smime-new-details-buffer)
506 (when (smime-call-openssl-region
507 b e smime-details-buffer "pkcs7" "-print_certs" "-text")
509 (insert-buffer-substring smime-details-buffer)
512 (defun smime-pkcs7-email-region (b e)
513 "Get email addresses contained in certificate between points B and E.
514 A string or a list of strings is returned."
515 (smime-new-details-buffer)
516 (when (smime-call-openssl-region
517 b e smime-details-buffer "x509" "-email" "-noout")
519 (insert-buffer-substring smime-details-buffer)
524 (defun smime-get-certfiles (keyfile keys)
526 (let ((curkey (car keys))
527 (otherkeys (cdr keys)))
528 (if (string= keyfile (cadr curkey))
530 (smime-get-certfiles keyfile otherkeys)))))
532 (defun smime-buffer-as-string-region (b e)
533 "Return each line in region between B and E as a list of strings."
538 (let ((str (buffer-substring (point) (point-at-eol))))
539 (unless (string= "" str)
546 (defun smime-mail-to-domain (mailaddr)
547 (if (string-match "@" mailaddr)
548 (replace-match "." 'fixedcase 'literal mailaddr)
551 (defun smime-cert-by-dns (mail)
552 "Find certificate via DNS for address MAIL."
553 (let* ((dig-dns-server smime-dns-server)
554 (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
555 (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
556 (certrr (with-current-buffer digbuf
557 (dig-extract-rr (smime-mail-to-domain mail) "cert")))
558 (cert (and certrr (dig-rr-get-pkix-cert certrr))))
560 (with-current-buffer retbuf
561 (insert "-----BEGIN CERTIFICATE-----\n")
562 (let ((i 0) (len (length cert)))
563 (while (> (- len 64) i)
564 (insert (substring cert i (+ i 64)) "\n")
566 (insert (substring cert i len) "\n"))
567 (insert "-----END CERTIFICATE-----\n"))
573 (defun smime-cert-by-ldap-1 (mail host)
574 "Get cetificate for MAIL from the ldap server at HOST."
575 (let ((ldapresult (smime-ldap-search (concat "mail=" mail)
576 host '("userCertificate") nil))
577 (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
579 (if (> (length ldapresult) 1)
580 (with-current-buffer retbuf
581 (setq cert (base64-encode-string (nth 1 (car (nth 1 ldapresult))) t))
582 (insert "-----BEGIN CERTIFICATE-----\n")
583 (let ((i 0) (len (length cert)))
584 (while (> (- len 64) i)
585 (insert (substring cert i (+ i 64)) "\n")
587 (insert (substring cert i len) "\n"))
588 (insert "-----END CERTIFICATE-----\n"))
593 (defun smime-cert-by-ldap (mail)
594 "Find certificate via LDAP for address MAIL."
595 (if smime-ldap-host-list
597 (dolist (host smime-ldap-host-list)
598 (let ((retbuf (smime-cert-by-ldap-1 mail host)))
600 (throw 'certbuf retbuf)))))))
604 (defvar smime-buffer "*SMIME*")
606 (defvar smime-mode-map nil)
607 (put 'smime-mode 'mode-class 'special)
609 (unless smime-mode-map
610 (setq smime-mode-map (make-sparse-keymap))
611 (suppress-keymap smime-mode-map)
613 (define-key smime-mode-map "q" 'smime-exit)
614 (define-key smime-mode-map "f" 'smime-certificate-info))
617 "Major mode for browsing, viewing and fetching certificates.
619 All normal editing commands are switched off.
622 The following commands are available:
626 (kill-all-local-variables)
627 (setq major-mode 'smime-mode)
628 (setq mode-name "SMIME")
629 (setq mode-line-process nil)
630 (use-local-map smime-mode-map)
631 (buffer-disable-undo)
632 (setq truncate-lines t)
633 (setq buffer-read-only t))
635 (defun smime-certificate-info (certfile)
636 (interactive "fCertificate file: ")
637 (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
638 (switch-to-buffer buffer)
640 (call-process smime-openssl-program nil buffer 'display
641 "x509" "-in" (expand-file-name certfile) "-text")
643 (set-buffer-modified-p nil)
645 (goto-char (point-min))))
647 (defun smime-draw-buffer ()
648 (with-current-buffer smime-buffer
649 (let (buffer-read-only)
651 (insert "\nYour keys:\n")
652 (dolist (key smime-keys)
654 (format "\t\t%s: %s\n" (car key) (cadr key))))
655 (insert "\nTrusted Certificate Authoritys:\n")
656 (insert "\nKnown Certificates:\n"))))
659 "Go to the SMIME buffer."
661 (unless (get-buffer smime-buffer)
663 (set-buffer (get-buffer-create smime-buffer))
666 (switch-to-buffer smime-buffer))
669 "Quit the S/MIME buffer."
671 (kill-buffer (current-buffer)))
675 (defun smime-get-key-by-email (email)
676 (cadr (assoc email smime-keys)))
678 (defun smime-get-key-with-certs-by-email (email)
679 (cdr (assoc email smime-keys)))
683 ;;; arch-tag: e3f9b938-5085-4510-8a11-6625269c9a9e
684 ;;; smime.el ends here