1 ;;; smime.el --- S/MIME support library
2 ;; Copyright (c) 2000, 2001 Free Software Foundation, Inc.
4 ;; Author: Simon Josefsson <simon@josefsson.org>
5 ;; Keywords: SMIME X.509 PEM OpenSSL
7 ;; This file is not a part of GNU Emacs, but the same permissions apply.
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 ;;; Quick introduction:
47 ;; Get your S/MIME certificate from VeriSign or someplace. I used
48 ;; Netscape to generate the key and certificate request and stuff, and
49 ;; Netscape can export the key into PKCS#12 format.
51 ;; Enter OpenSSL. To be able to use this library, it need to have the
52 ;; SMIME key readable in PEM format. OpenSSL is used to convert the
55 ;; $ openssl pkcs12 -in mykey.p12 -clcerts -nodes > mykey.pem
58 ;; Now, use M-x customize-variable smime-keys and add mykey.pem as
61 ;; Now you should be able to sign messages! Create a buffer and write
62 ;; something and run M-x smime-sign-buffer RET RET and you should see
63 ;; your message MIME armoured and a signature. Encryption, M-x
64 ;; smime-encrypt-buffer, should also work.
66 ;; To be able to verify messages you need to build up trust with
67 ;; someone. Perhaps you trust the CA that issued your certificate, at
68 ;; least I did, so I export it's certificates from my PKCS#12
71 ;; $ openssl pkcs12 -in mykey.p12 -cacerts -nodes > cacert.pem
74 ;; Now, use M-x customize-variable smime-CAs and add cacert.pem as a
77 ;; You should now be able to sign messages, and even verify messages
78 ;; sent by others that use the same CA as you.
82 ;; Don't complain that this package doesn't do encrypted PEM files,
83 ;; submit a patch instead. I store my keys in a safe place, so I
84 ;; didn't need the encryption. Also, programming was made easier by
85 ;; that decision. One might think that this even influenced were I
86 ;; store my keys, and one would probably be right. :-)
88 ;; Update: Mathias Herberts sent the patch. However, it uses
89 ;; environment variables to pass the password to OpenSSL, which is
90 ;; slightly insecure. Hence a new todo: use a better -passin method.
92 ;; Suggestions and comments are appreciated, mail me at simon@josefsson.org.
96 ;; I would include pointers to introductory text on concepts used in
97 ;; this library here, but the material I've read are so horrible I
98 ;; don't want to recomend them.
100 ;; Why can't someone write a simple introduction to all this stuff?
101 ;; Until then, much of this resemble security by obscurity.
103 ;; Also, I'm not going to mention anything about the wonders of
104 ;; cryptopolitics. Oops, I just did.
108 ;;; Revision history:
110 ;; version 0 not released
116 (eval-when-compile (require 'cl))
119 "S/MIME configuration.")
121 (defcustom smime-keys nil
122 "Map mail addresses to a file containing Certificate (and private key).
123 The file is assumed to be in PEM format and not encrypted."
124 :type '(repeat (list (string :tag "Mail address")
125 (file :tag "File name")))
128 (defcustom smime-CA-directory nil
129 "Directory containing certificates for CAs you trust.
130 Directory should contain files (in PEM format) named to the X.509
131 hash of the certificate. This can be done using OpenSSL such as:
133 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`
135 where `ca.pem' is the file containing a PEM encoded X.509 CA
137 :type '(choice (const :tag "none" nil)
141 (defcustom smime-CA-file nil
142 "Files containing certificates for CAs you trust.
143 File should contain certificates in PEM format."
144 :type '(choice (const :tag "none" nil)
148 (defcustom smime-certificate-directory "~/Mail/certs/"
149 "Directory containing other people's certificates.
150 It should contain files named to the X.509 hash of the certificate,
151 and the files themself should be in PEM format."
152 ;The S/MIME library provide simple functionality for fetching
153 ;certificates into this directory, so there is no need to populate it
158 (defcustom smime-openssl-program
159 (and (condition-case ()
160 (eq 0 (call-process "openssl" nil nil nil "version"))
163 "Name of OpenSSL binary."
167 ;; OpenSSL option to select the encryption cipher
169 (defcustom smime-encrypt-cipher "-des3"
170 "Cipher algorithm used for encryption."
171 :type '(choice (const :tag "Triple DES" "-des3")
172 (const :tag "DES" "-des")
173 (const :tag "RC2 40 bits" "-rc2-40")
174 (const :tag "RC2 64 bits" "-rc2-64")
175 (const :tag "RC2 128 bits" "-rc2-128"))
178 (defcustom smime-dns-server nil
179 "DNS server to query certificates from.
180 If nil, use system defaults."
181 :type '(choice (const :tag "System defaults")
185 (defvar smime-details-buffer "*OpenSSL output*")
187 ;; Password dialog function
189 (defun smime-ask-passphrase ()
190 "Asks the passphrase to unlock the secret key."
193 "Passphrase for secret key (RET for no passphrase): " t)))
194 (if (string= passphrase "")
200 (defun smime-call-openssl-region (b e buf &rest args)
201 (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
203 (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
204 (2 (message "OpenSSL: One of the input files could not be read.") nil)
205 (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
206 (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
207 (t (error "Unknown OpenSSL exitcode") nil)))
209 ;; Sign+encrypt region
211 (defun smime-sign-region (b e keyfile)
212 "Sign region with certified key in KEYFILE.
213 If signing fails, the buffer is not modified. Region is assumed to
214 have proper MIME tags. KEYFILE is expected to contain a PEM encoded
215 private key and certificate."
216 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
217 (passphrase (smime-ask-passphrase)))
219 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
221 (when (apply 'smime-call-openssl-region b e buffer "smime" "-sign"
222 "-signer" (expand-file-name keyfile)
224 (list "-passin" "env:GNUS_SMIME_PASSPHRASE")))
226 (insert-buffer buffer)
227 (when (looking-at "^MIME-Version: 1.0$")
228 (delete-region (point) (progn (forward-line 1) (point))))
231 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
232 (with-current-buffer (get-buffer-create smime-details-buffer)
233 (goto-char (point-max))
234 (insert-buffer buffer))
235 (kill-buffer buffer))))
237 (defun smime-encrypt-region (b e certfiles)
238 "Encrypt region for recipients specified in CERTFILES.
239 If encryption fails, the buffer is not modified. Region is assumed to
240 have proper MIME tags. CERTFILES is a list of filenames, each file
241 is expected to contain of a PEM encoded certificate."
242 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
244 (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
245 smime-encrypt-cipher (mapcar 'expand-file-name certfiles))
247 (insert-buffer buffer)
248 (when (looking-at "^MIME-Version: 1.0$")
249 (delete-region (point) (progn (forward-line 1) (point))))
251 (with-current-buffer (get-buffer-create smime-details-buffer)
252 (goto-char (point-max))
253 (insert-buffer buffer))
254 (kill-buffer buffer))))
256 ;; Sign+encrypt buffer
258 (defun smime-sign-buffer (&optional keyfile buffer)
259 "S/MIME sign BUFFER with key in KEYFILE.
260 KEYFILE should contain a PEM encoded key and certificate."
262 (with-current-buffer (or buffer (current-buffer))
264 (point-min) (point-max)
266 (smime-get-key-by-email
267 (completing-read "Sign using which signature? " smime-keys nil nil
268 (and (listp (car-safe smime-keys))
269 (caar smime-keys))))))))
271 (defun smime-encrypt-buffer (&optional certfiles buffer)
272 "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
273 CERTFILES is a list of filenames, each file is expected to consist of
274 a PEM encoded key and certificate. Uses current buffer if BUFFER is
277 (with-current-buffer (or buffer (current-buffer))
278 (smime-encrypt-region
279 (point-min) (point-max)
281 (list (read-file-name "Recipient's S/MIME certificate: "
282 smime-certificate-directory nil))))))
284 ;; Verify+decrypt region
286 (defun smime-verify-region (b e)
287 (let ((buffer (get-buffer-create smime-details-buffer))
288 (CAs (cond (smime-CA-file
289 (list "-CAfile" (expand-file-name smime-CA-file)))
291 (list "-CApath" (expand-file-name smime-CA-directory)))
293 (error "No CA configured.")))))
294 (with-current-buffer buffer
296 (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
297 "-out" "/dev/null" CAs)
298 (message "S/MIME message verified succesfully.")
299 (message "S/MIME message NOT verified successfully.")
302 (defun smime-noverify-region (b e)
303 (let ((buffer (get-buffer-create smime-details-buffer)))
304 (with-current-buffer buffer
306 (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
307 "-noverify" "-out" '("/dev/null"))
308 (message "S/MIME message verified succesfully.")
309 (message "S/MIME message NOT verified successfully.")
312 (defun smime-decrypt-region (b e keyfile)
313 (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
314 CAs (passphrase (smime-ask-passphrase)))
316 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
317 (when (apply 'smime-call-openssl-region
318 b e buffer "smime" "-decrypt"
319 "-recip" (list keyfile)
321 (list "-passin" "env:GNUS_SMIME_PASSPHRASE" )))
324 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
325 (with-current-buffer (get-buffer-create smime-details-buffer)
326 (goto-char (point-max))
327 (insert-buffer buffer))
328 (kill-buffer buffer)))
330 ;; Verify+Decrypt buffer
332 (defun smime-verify-buffer (&optional buffer)
333 "Verify integrity of S/MIME message in BUFFER.
334 Uses current buffer if BUFFER is nil."
336 (with-current-buffer (or buffer (current-buffer))
337 (smime-verify-region (point-min) (point-max))))
339 (defun smime-noverify-buffer (&optional buffer)
340 "Verify integrity of S/MIME message in BUFFER.
341 Uses current buffer if BUFFER is nil.
342 Does NOT verify validity of certificate."
344 (with-current-buffer (or buffer (current-buffer))
345 (smime-noverify-region (point-min) (point-max))))
347 (defun smime-decrypt-buffer (&optional buffer keyfile)
348 "Decrypt S/MIME message in BUFFER using KEYFILE.
349 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
351 (with-current-buffer (or buffer (current-buffer))
352 (smime-decrypt-region
353 (point-min) (point-max)
356 (smime-get-key-by-email
357 (completing-read "Decrypt with which key? " smime-keys nil nil
358 (and (listp (car-safe smime-keys))
359 (caar smime-keys)))))))))
361 ;; Various operations
363 (defun smime-pkcs7-region (b e)
364 "Convert S/MIME message between points B and E into a PKCS7 message."
365 (let ((buffer (get-buffer-create smime-details-buffer)))
366 (with-current-buffer buffer
368 (when (smime-call-openssl-region b e buffer "smime" "-pk7out")
370 (insert-buffer-substring buffer)
373 (defun smime-pkcs7-certificates-region (b e)
374 "Extract any certificates enclosed in PKCS7 message between points B and E."
375 (let ((buffer (get-buffer-create smime-details-buffer)))
376 (with-current-buffer buffer
378 (when (smime-call-openssl-region b e buffer "pkcs7" "-print_certs" "-text")
380 (insert-buffer-substring buffer)
383 (defun smime-pkcs7-email-region (b e)
384 "Get email addresses contained in certificate between points B and E.
385 A string or a list of strings is returned."
386 (let ((buffer (get-buffer-create smime-details-buffer)))
387 (with-current-buffer buffer
389 (when (smime-call-openssl-region b e buffer "x509" "-email" "-noout")
391 (insert-buffer-substring buffer)
394 (defalias 'smime-point-at-eol
395 (if (fboundp 'point-at-eol)
399 (defun smime-buffer-as-string-region (b e)
400 "Return each line in region between B and E as a list of strings."
405 (let ((str (buffer-substring (point) (smime-point-at-eol))))
406 (unless (string= "" str)
413 (defun smime-mail-to-domain (mailaddr)
414 (if (string-match "@" mailaddr)
415 (replace-match "." 'fixedcase 'literal mailaddr)
418 (defun smime-cert-by-dns (mail)
419 (let* ((dig-dns-server smime-dns-server)
420 (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
421 (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
422 (certrr (with-current-buffer digbuf
423 (dig-extract-rr (smime-mail-to-domain mail) "cert")))
424 (cert (and certrr (dig-rr-get-pkix-cert certrr))))
426 (with-current-buffer retbuf
427 (insert "-----BEGIN CERTIFICATE-----\n")
428 (let ((i 0) (len (length cert)))
429 (while (> (- len 64) i)
430 (insert (substring cert i (+ i 64)) "\n")
432 (insert (substring cert i len) "\n"))
433 (insert "-----END CERTIFICATE-----\n"))
441 (defvar smime-buffer "*SMIME*")
443 (defvar smime-mode-map nil)
444 (put 'smime-mode 'mode-class 'special)
446 (unless smime-mode-map
447 (setq smime-mode-map (make-sparse-keymap))
448 (suppress-keymap smime-mode-map)
450 (define-key smime-mode-map "q" 'smime-exit)
451 (define-key smime-mode-map "f" 'smime-certificate-info))
454 "Major mode for browsing, viewing and fetching certificates.
456 All normal editing commands are switched off.
459 The following commands are available:
463 (kill-all-local-variables)
464 (setq major-mode 'smime-mode)
465 (setq mode-name "SMIME")
466 (setq mode-line-process nil)
467 (use-local-map smime-mode-map)
468 (buffer-disable-undo)
469 (setq truncate-lines t)
470 (setq buffer-read-only t))
472 (defun smime-certificate-info (certfile)
473 (interactive "fCertificate file: ")
474 (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
475 (switch-to-buffer buffer)
477 (call-process smime-openssl-program nil buffer 'display
478 "x509" "-in" (expand-file-name certfile) "-text")
480 (set-buffer-modified-p nil)
482 (goto-char (point-min))))
484 (defun smime-draw-buffer ()
485 (with-current-buffer smime-buffer
486 (let (buffer-read-only)
488 (insert "\nYour keys:\n")
489 (dolist (key smime-keys)
491 (format "\t\t%s: %s\n" (car key) (cadr key))))
492 (insert "\nTrusted Certificate Authoritys:\n")
493 (insert "\nKnown Certificates:\n"))))
496 "Go to the SMIME buffer."
498 (unless (get-buffer smime-buffer)
500 (set-buffer (get-buffer-create smime-buffer))
503 (switch-to-buffer smime-buffer))
506 "Quit the S/MIME buffer."
508 (kill-buffer (current-buffer)))
512 (defun smime-get-key-by-email (email)
513 (cadr (assoc email smime-keys)))
517 ;;; smime.el ends here