1 ;;; smime.el --- S/MIME support library
2 ;; Copyright (c) 2000, 2001, 2003 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 only from DNS. LDAP support (via EUDC) is planned.
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
122 (eval-when-compile (require 'cl))
125 "S/MIME configuration.")
127 (defcustom smime-keys nil
128 "*Map mail addresses to a file containing Certificate (and private key).
129 The file is assumed to be in PEM format. You can also associate additional
130 certificates to be sent with every message to each address."
131 :type '(repeat (list (string :tag "Mail address")
132 (file :tag "File name")
133 (repeat :tag "Additional certificate files"
134 (file :tag "File name"))))
137 (defcustom smime-CA-directory nil
138 "*Directory containing certificates for CAs you trust.
139 Directory should contain files (in PEM format) named to the X.509
140 hash of the certificate. This can be done using OpenSSL such as:
142 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`.0
144 where `ca.pem' is the file containing a PEM encoded X.509 CA
146 :type '(choice (const :tag "none" nil)
150 (defcustom smime-CA-file nil
151 "*Files containing certificates for CAs you trust.
152 File should contain certificates in PEM format."
153 :type '(choice (const :tag "none" nil)
157 (defcustom smime-certificate-directory "~/Mail/certs/"
158 "*Directory containing other people's certificates.
159 It should contain files named to the X.509 hash of the certificate,
160 and the files themself should be in PEM format."
161 ;The S/MIME library provide simple functionality for fetching
162 ;certificates into this directory, so there is no need to populate it
167 (defcustom smime-openssl-program
168 (and (condition-case ()
169 (eq 0 (call-process "openssl" nil nil nil "version"))
172 "*Name of OpenSSL binary."
176 ;; OpenSSL option to select the encryption cipher
178 (defcustom smime-encrypt-cipher "-des3"
179 "*Cipher algorithm used for encryption."
180 :type '(choice (const :tag "Triple DES" "-des3")
181 (const :tag "DES" "-des")
182 (const :tag "RC2 40 bits" "-rc2-40")
183 (const :tag "RC2 64 bits" "-rc2-64")
184 (const :tag "RC2 128 bits" "-rc2-128"))
187 (defcustom smime-crl-check nil
188 "*Check revocation status of signers certificate using CRLs."
189 :type '(choice (const :tag "No check" nil)
190 (const :tag "Check certificate" "-crl_check")
191 (const :tag "Check certificate chain" "-crl_check_all"))
194 (defcustom smime-dns-server nil
195 "*DNS server to query certificates from.
196 If nil, use system defaults."
197 :type '(choice (const :tag "System defaults")
201 (defvar smime-details-buffer "*OpenSSL output*")
205 (defalias 'smime-make-temp-file
206 (if (fboundp 'make-temp-file)
208 (lambda (prefix &optional dir-flag) ;; Simple implementation
210 (make-temp-name prefix)
211 (if (fboundp 'temp-directory)
213 temporary-file-directory))))))
215 ;; Password dialog function
217 (defun smime-ask-passphrase ()
218 "Asks the passphrase to unlock the secret key."
221 "Passphrase for secret key (RET for no passphrase): ")))
222 (if (string= passphrase "")
228 (defun smime-call-openssl-region (b e buf &rest args)
229 (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
231 (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
232 (2 (message "OpenSSL: One of the input files could not be read.") nil)
233 (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
234 (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
235 (t (error "Unknown OpenSSL exitcode") nil)))
237 (defun smime-make-certfiles (certfiles)
239 (append (list "-certfile" (expand-file-name (car certfiles)))
240 (smime-make-certfiles (cdr certfiles)))))
242 ;; Sign+encrypt region
244 (defun smime-sign-region (b e keyfile)
245 "Sign region with certified key in KEYFILE.
246 If signing fails, the buffer is not modified. Region is assumed to
247 have proper MIME tags. KEYFILE is expected to contain a PEM encoded
248 private key and certificate as its car, and a list of additional
249 certificates to include in its caar. If no additional certificates is
250 included, KEYFILE may be the file containing the PEM encoded private
251 key and certificate itself."
252 (smime-new-details-buffer)
253 (let ((keyfile (or (car-safe keyfile) keyfile))
254 (certfiles (and (cdr-safe keyfile) (cadr keyfile)))
255 (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
256 (passphrase (smime-ask-passphrase))
257 (tmpfile (smime-make-temp-file "smime")))
259 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
262 (apply 'smime-call-openssl-region b e (list buffer tmpfile)
263 "smime" "-sign" "-signer" (expand-file-name keyfile)
265 (smime-make-certfiles certfiles)
267 (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
269 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
270 (with-current-buffer smime-details-buffer
271 (insert-file-contents tmpfile)
272 (delete-file tmpfile)))
274 (insert-buffer-substring buffer)
276 (when (looking-at "^MIME-Version: 1.0$")
277 (delete-region (point) (progn (forward-line 1) (point))))
279 (with-current-buffer smime-details-buffer
280 (goto-char (point-max))
281 (insert-buffer-substring buffer))
282 (kill-buffer buffer))))
284 (defun smime-encrypt-region (b e certfiles)
285 "Encrypt region for recipients specified in CERTFILES.
286 If encryption fails, the buffer is not modified. Region is assumed to
287 have proper MIME tags. CERTFILES is a list of filenames, each file
288 is expected to contain of a PEM encoded certificate."
289 (smime-new-details-buffer)
290 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
291 (tmpfile (smime-make-temp-file "smime")))
294 (apply 'smime-call-openssl-region b e (list buffer tmpfile)
295 "smime" "-encrypt" smime-encrypt-cipher
296 (mapcar 'expand-file-name certfiles))
297 (with-current-buffer smime-details-buffer
298 (insert-file-contents tmpfile)
299 (delete-file tmpfile)))
301 (insert-buffer-substring buffer)
303 (when (looking-at "^MIME-Version: 1.0$")
304 (delete-region (point) (progn (forward-line 1) (point))))
306 (with-current-buffer smime-details-buffer
307 (goto-char (point-max))
308 (insert-buffer-substring buffer))
309 (kill-buffer buffer))))
311 ;; Sign+encrypt buffer
313 (defun smime-sign-buffer (&optional keyfile buffer)
314 "S/MIME sign BUFFER with key in KEYFILE.
315 KEYFILE should contain a PEM encoded key and certificate."
317 (with-current-buffer (or buffer (current-buffer))
319 (point-min) (point-max)
322 (smime-get-key-with-certs-by-email
324 (concat "Sign using which key? "
325 (if smime-keys (concat "(default " (caar smime-keys) ") ")
327 smime-keys nil nil (car-safe (car-safe smime-keys))))))))
329 (defun smime-encrypt-buffer (&optional certfiles buffer)
330 "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
331 CERTFILES is a list of filenames, each file is expected to consist of
332 a PEM encoded key and certificate. Uses current buffer if BUFFER is
335 (with-current-buffer (or buffer (current-buffer))
336 (smime-encrypt-region
337 (point-min) (point-max)
339 (list (read-file-name "Recipient's S/MIME certificate: "
340 smime-certificate-directory nil))))))
342 ;; Verify+decrypt region
344 (defun smime-verify-region (b e)
345 "Verify S/MIME message in region between B and E.
346 Returns non-nil on success.
347 Any details (stdout and stderr) are left in the buffer specified by
348 `smime-details-buffer'."
349 (smime-new-details-buffer)
350 (let ((CAs (append (if smime-CA-file
352 (expand-file-name smime-CA-file)))
353 (if smime-CA-directory
355 (expand-file-name smime-CA-directory))))))
357 (error "No CA configured"))
359 (add-to-list 'CAs smime-crl-check))
360 (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
361 "smime" "-verify" "-out" "/dev/null" CAs)
363 (insert-buffer-substring smime-details-buffer)
366 (defun smime-noverify-region (b e)
367 "Verify integrity of S/MIME message in region between B and E.
368 Returns non-nil on success.
369 Any details (stdout and stderr) are left in the buffer specified by
370 `smime-details-buffer'."
371 (smime-new-details-buffer)
372 (if (apply 'smime-call-openssl-region b e (list smime-details-buffer t)
373 "smime" "-verify" "-noverify" "-out" '("/dev/null"))
375 (insert-buffer-substring smime-details-buffer)
381 (defun smime-decrypt-region (b e keyfile)
382 "Decrypt S/MIME message in region between B and E with key in KEYFILE.
383 On success, replaces region with decrypted data and return non-nil.
384 Any details (stderr on success, stdout and stderr on error) are left
385 in the buffer specified by `smime-details-buffer'."
386 (smime-new-details-buffer)
387 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
388 CAs (passphrase (smime-ask-passphrase))
389 (tmpfile (smime-make-temp-file "smime")))
391 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
393 (apply 'smime-call-openssl-region b e
394 (list buffer tmpfile)
395 "smime" "-decrypt" "-recip" (expand-file-name keyfile)
397 (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
399 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
400 (with-current-buffer smime-details-buffer
401 (insert-file-contents tmpfile)
402 (delete-file tmpfile)))
406 ;; `from' is dynamically bound in mm-dissect.
407 (insert "From: " from "\n"))
408 (insert-buffer-substring buffer)
411 (with-current-buffer smime-details-buffer
412 (insert-buffer-substring buffer))
415 (insert-buffer-substring smime-details-buffer)
418 ;; Verify+Decrypt buffer
420 (defun smime-verify-buffer (&optional buffer)
421 "Verify integrity of S/MIME message in BUFFER.
422 Uses current buffer if BUFFER is nil. Returns non-nil on success.
423 Any details (stdout and stderr) are left in the buffer specified by
424 `smime-details-buffer'."
426 (with-current-buffer (or buffer (current-buffer))
427 (smime-verify-region (point-min) (point-max))))
429 (defun smime-noverify-buffer (&optional buffer)
430 "Verify integrity of S/MIME message in BUFFER.
431 Does NOT verify validity of certificate (only message integrity).
432 Uses current buffer if BUFFER is nil. Returns non-nil on success.
433 Any details (stdout and stderr) are left in the buffer specified by
434 `smime-details-buffer'."
436 (with-current-buffer (or buffer (current-buffer))
437 (smime-noverify-region (point-min) (point-max))))
439 (defun smime-decrypt-buffer (&optional buffer keyfile)
440 "Decrypt S/MIME message in BUFFER using KEYFILE.
441 Uses current buffer if BUFFER is nil, and query user of KEYFILE if it's nil.
442 On success, replaces data in buffer and return non-nil.
443 Any details (stderr on success, stdout and stderr on error) are left
444 in the buffer specified by `smime-details-buffer'."
446 (with-current-buffer (or buffer (current-buffer))
447 (smime-decrypt-region
448 (point-min) (point-max)
451 (smime-get-key-by-email
453 (concat "Decipher using which key? "
454 (if smime-keys (concat "(default " (caar smime-keys) ") ")
456 smime-keys nil nil (car-safe (car-safe smime-keys)))))))))
458 ;; Various operations
460 (defun smime-new-details-buffer ()
461 (with-current-buffer (get-buffer-create smime-details-buffer)
464 (defun smime-pkcs7-region (b e)
465 "Convert S/MIME message between points B and E into a PKCS7 message."
466 (smime-new-details-buffer)
467 (when (smime-call-openssl-region b e smime-details-buffer "smime" "-pk7out")
469 (insert-buffer-substring smime-details-buffer)
472 (defun smime-pkcs7-certificates-region (b e)
473 "Extract any certificates enclosed in PKCS7 message between points B and E."
474 (smime-new-details-buffer)
475 (when (smime-call-openssl-region
476 b e smime-details-buffer "pkcs7" "-print_certs" "-text")
478 (insert-buffer-substring smime-details-buffer)
481 (defun smime-pkcs7-email-region (b e)
482 "Get email addresses contained in certificate between points B and E.
483 A string or a list of strings is returned."
484 (smime-new-details-buffer)
485 (when (smime-call-openssl-region
486 b e smime-details-buffer "x509" "-email" "-noout")
488 (insert-buffer-substring smime-details-buffer)
493 (defun smime-get-certfiles (keyfile keys)
495 (let ((curkey (car keys))
496 (otherkeys (cdr keys)))
497 (if (string= keyfile (cadr curkey))
499 (smime-get-certfiles keyfile otherkeys)))))
503 (defalias 'smime-point-at-eol
504 (if (fboundp 'point-at-eol)
506 'line-end-position)))
508 (defun smime-buffer-as-string-region (b e)
509 "Return each line in region between B and E as a list of strings."
514 (let ((str (buffer-substring (point) (smime-point-at-eol))))
515 (unless (string= "" str)
522 (defun smime-mail-to-domain (mailaddr)
523 (if (string-match "@" mailaddr)
524 (replace-match "." 'fixedcase 'literal mailaddr)
527 (defun smime-cert-by-dns (mail)
528 (let* ((dig-dns-server smime-dns-server)
529 (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
530 (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
531 (certrr (with-current-buffer digbuf
532 (dig-extract-rr (smime-mail-to-domain mail) "cert")))
533 (cert (and certrr (dig-rr-get-pkix-cert certrr))))
535 (with-current-buffer retbuf
536 (insert "-----BEGIN CERTIFICATE-----\n")
537 (let ((i 0) (len (length cert)))
538 (while (> (- len 64) i)
539 (insert (substring cert i (+ i 64)) "\n")
541 (insert (substring cert i len) "\n"))
542 (insert "-----END CERTIFICATE-----\n"))
550 (defvar smime-buffer "*SMIME*")
552 (defvar smime-mode-map nil)
553 (put 'smime-mode 'mode-class 'special)
555 (unless smime-mode-map
556 (setq smime-mode-map (make-sparse-keymap))
557 (suppress-keymap smime-mode-map)
559 (define-key smime-mode-map "q" 'smime-exit)
560 (define-key smime-mode-map "f" 'smime-certificate-info))
563 "Major mode for browsing, viewing and fetching certificates.
565 All normal editing commands are switched off.
568 The following commands are available:
572 (kill-all-local-variables)
573 (setq major-mode 'smime-mode)
574 (setq mode-name "SMIME")
575 (setq mode-line-process nil)
576 (use-local-map smime-mode-map)
577 (buffer-disable-undo)
578 (setq truncate-lines t)
579 (setq buffer-read-only t))
581 (defun smime-certificate-info (certfile)
582 (interactive "fCertificate file: ")
583 (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
584 (switch-to-buffer buffer)
586 (call-process smime-openssl-program nil buffer 'display
587 "x509" "-in" (expand-file-name certfile) "-text")
589 (set-buffer-modified-p nil)
591 (goto-char (point-min))))
593 (defun smime-draw-buffer ()
594 (with-current-buffer smime-buffer
595 (let (buffer-read-only)
597 (insert "\nYour keys:\n")
598 (dolist (key smime-keys)
600 (format "\t\t%s: %s\n" (car key) (cadr key))))
601 (insert "\nTrusted Certificate Authoritys:\n")
602 (insert "\nKnown Certificates:\n"))))
605 "Go to the SMIME buffer."
607 (unless (get-buffer smime-buffer)
609 (set-buffer (get-buffer-create smime-buffer))
612 (switch-to-buffer smime-buffer))
615 "Quit the S/MIME buffer."
617 (kill-buffer (current-buffer)))
621 (defun smime-get-key-by-email (email)
622 (cadr (assoc email smime-keys)))
624 (defun smime-get-key-with-certs-by-email (email)
625 (cdr (assoc email smime-keys)))
629 ;;; smime.el ends here