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. You can also associate additional
124 certificates to be sent with every message to each address."
125 :type '(repeat (list (string :tag "Mail address")
126 (file :tag "File name")
127 (repeat :tag "Additional certificate files"
128 (file :tag "File name"))))
131 (defcustom smime-CA-directory nil
132 "Directory containing certificates for CAs you trust.
133 Directory should contain files (in PEM format) named to the X.509
134 hash of the certificate. This can be done using OpenSSL such as:
136 $ ln -s ca.pem `openssl x509 -noout -hash -in ca.pem`
138 where `ca.pem' is the file containing a PEM encoded X.509 CA
140 :type '(choice (const :tag "none" nil)
144 (defcustom smime-CA-file nil
145 "Files containing certificates for CAs you trust.
146 File should contain certificates in PEM format."
147 :type '(choice (const :tag "none" nil)
151 (defcustom smime-certificate-directory "~/Mail/certs/"
152 "Directory containing other people's certificates.
153 It should contain files named to the X.509 hash of the certificate,
154 and the files themself should be in PEM format."
155 ;The S/MIME library provide simple functionality for fetching
156 ;certificates into this directory, so there is no need to populate it
161 (defcustom smime-openssl-program
162 (and (condition-case ()
163 (eq 0 (call-process "openssl" nil nil nil "version"))
166 "Name of OpenSSL binary."
170 ;; OpenSSL option to select the encryption cipher
172 (defcustom smime-encrypt-cipher "-des3"
173 "Cipher algorithm used for encryption."
174 :type '(choice (const :tag "Triple DES" "-des3")
175 (const :tag "DES" "-des")
176 (const :tag "RC2 40 bits" "-rc2-40")
177 (const :tag "RC2 64 bits" "-rc2-64")
178 (const :tag "RC2 128 bits" "-rc2-128"))
181 (defcustom smime-dns-server nil
182 "DNS server to query certificates from.
183 If nil, use system defaults."
184 :type '(choice (const :tag "System defaults")
188 (defvar smime-details-buffer "*OpenSSL output*")
190 ;; Password dialog function
192 (defun smime-ask-passphrase ()
193 "Asks the passphrase to unlock the secret key."
196 "Passphrase for secret key (RET for no passphrase): " t)))
197 (if (string= passphrase "")
203 (defun smime-call-openssl-region (b e buf &rest args)
204 (case (apply 'call-process-region b e smime-openssl-program nil buf nil args)
206 (1 (message "OpenSSL: An error occurred parsing the command options.") nil)
207 (2 (message "OpenSSL: One of the input files could not be read.") nil)
208 (3 (message "OpenSSL: An error occurred creating the PKCS#7 file or when reading the MIME message.") nil)
209 (4 (message "OpenSSL: An error occurred decrypting or verifying the message.") nil)
210 (t (error "Unknown OpenSSL exitcode") nil)))
212 (defun smime-make-certfiles (certfiles)
214 (append (list "-certfile" (expand-file-name (car certfiles)))
215 (smime-make-certfiles (cdr certfiles)))))
217 ;; Sign+encrypt region
219 (defun smime-sign-region (b e keyfiles)
220 "Sign region with certified key in KEYFILES.
221 If signing fails, the buffer is not modified. Region is assumed to
222 have proper MIME tags. KEYFILES is expected to contain a PEM encoded
223 private key and certificate as its car, and a list of additional certificates
224 to include in its caar."
225 (let ((keyfile (car keyfiles))
226 (certfiles (and (cdr keyfiles) (cadr keyfiles)))
227 (buffer (generate-new-buffer (generate-new-buffer-name " *smime*")))
228 (passphrase (smime-ask-passphrase)))
230 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
232 (when (apply 'smime-call-openssl-region b e buffer "smime" "-sign"
233 "-signer" (expand-file-name keyfile)
235 (smime-make-certfiles certfiles)
237 (list "-passin" "env:GNUS_SMIME_PASSPHRASE"))))
239 (insert-buffer buffer)
240 (when (looking-at "^MIME-Version: 1.0$")
241 (delete-region (point) (progn (forward-line 1) (point))))
244 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
245 (with-current-buffer (get-buffer-create smime-details-buffer)
246 (goto-char (point-max))
247 (insert-buffer buffer))
248 (kill-buffer buffer))))
250 (defun smime-encrypt-region (b e certfiles)
251 "Encrypt region for recipients specified in CERTFILES.
252 If encryption fails, the buffer is not modified. Region is assumed to
253 have proper MIME tags. CERTFILES is a list of filenames, each file
254 is expected to contain of a PEM encoded certificate."
255 (let ((buffer (generate-new-buffer (generate-new-buffer-name " *smime*"))))
257 (when (apply 'smime-call-openssl-region b e buffer "smime" "-encrypt"
258 smime-encrypt-cipher (mapcar 'expand-file-name certfiles))
260 (insert-buffer buffer)
261 (when (looking-at "^MIME-Version: 1.0$")
262 (delete-region (point) (progn (forward-line 1) (point))))
264 (with-current-buffer (get-buffer-create smime-details-buffer)
265 (goto-char (point-max))
266 (insert-buffer buffer))
267 (kill-buffer buffer))))
269 (defun smime-get-certfiles (keyfile keys)
271 (let ((curkey (car keys))
272 (otherkeys (cdr keys)))
273 (if (string= keyfile (cadr curkey))
275 (smime-get-certfiles keyfile otherkeys)))))
277 ;; Sign+encrypt buffer
279 (defun smime-sign-buffer (&optional keyfile buffer)
280 "S/MIME sign BUFFER with key in KEYFILE.
281 KEYFILE should contain a PEM encoded key and certificate."
283 (with-current-buffer (or buffer (current-buffer))
285 (point-min) (point-max)
287 (list keyfile (smime-get-certfiles keyfile smime-keys))
288 (smime-get-key-by-email
289 (completing-read "Sign using which signature? " smime-keys nil nil
290 (and (listp (car-safe smime-keys))
291 (cdr smime-keys))))))))
293 (defun smime-encrypt-buffer (&optional certfiles buffer)
294 "S/MIME encrypt BUFFER for recipients specified in CERTFILES.
295 CERTFILES is a list of filenames, each file is expected to consist of
296 a PEM encoded key and certificate. Uses current buffer if BUFFER is
299 (with-current-buffer (or buffer (current-buffer))
300 (smime-encrypt-region
301 (point-min) (point-max)
303 (list (read-file-name "Recipient's S/MIME certificate: "
304 smime-certificate-directory nil))))))
306 ;; Verify+decrypt region
308 (defun smime-verify-region (b e)
309 (let ((buffer (get-buffer-create smime-details-buffer))
310 (CAs (append (if smime-CA-file
312 (expand-file-name smime-CA-file)))
313 (if smime-CA-directory
315 (expand-file-name smime-CA-directory))))))
316 (unless CAs (error "No CA configured"))
317 (with-current-buffer buffer
319 (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
320 "-out" "/dev/null" CAs)
321 (message "S/MIME message verified succesfully.")
322 (message "S/MIME message NOT verified successfully.")
325 (defun smime-noverify-region (b e)
326 (let ((buffer (get-buffer-create smime-details-buffer)))
327 (with-current-buffer buffer
329 (if (apply 'smime-call-openssl-region b e buffer "smime" "-verify"
330 "-noverify" "-out" '("/dev/null"))
331 (message "S/MIME message verified succesfully.")
332 (message "S/MIME message NOT verified successfully.")
335 (defun smime-decrypt-region (b e keyfile)
336 (let ((buffer (generate-new-buffer (generate-new-buffer-name "*smime*")))
337 CAs (passphrase (smime-ask-passphrase)))
339 (setenv "GNUS_SMIME_PASSPHRASE" passphrase))
340 (when (apply 'smime-call-openssl-region
341 b e buffer "smime" "-decrypt"
344 (list "-passin" "env:GNUS_SMIME_PASSPHRASE" )))
346 (insert-buffer buffer))
348 (setenv "GNUS_SMIME_PASSPHRASE" "" t))
349 (with-current-buffer (get-buffer-create smime-details-buffer)
350 (goto-char (point-max))
351 (insert-buffer buffer))
352 (kill-buffer buffer)))
354 ;; Verify+Decrypt buffer
356 (defun smime-verify-buffer (&optional buffer)
357 "Verify integrity of S/MIME message in BUFFER.
358 Uses current buffer if BUFFER is nil."
360 (with-current-buffer (or buffer (current-buffer))
361 (smime-verify-region (point-min) (point-max))))
363 (defun smime-noverify-buffer (&optional buffer)
364 "Verify integrity of S/MIME message in BUFFER.
365 Uses current buffer if BUFFER is nil.
366 Does NOT verify validity of certificate."
368 (with-current-buffer (or buffer (current-buffer))
369 (smime-noverify-region (point-min) (point-max))))
371 (defun smime-decrypt-buffer (&optional buffer keyfile)
372 "Decrypt S/MIME message in BUFFER using KEYFILE.
373 Uses current buffer if BUFFER is nil, queries user of KEYFILE is nil."
375 (with-current-buffer (or buffer (current-buffer))
376 (smime-decrypt-region
377 (point-min) (point-max)
380 (smime-get-key-by-email
381 (completing-read "Decrypt with which key? " smime-keys nil nil
382 (and (listp (car-safe smime-keys))
383 (caar smime-keys)))))))))
385 ;; Various operations
387 (defun smime-pkcs7-region (b e)
388 "Convert S/MIME message between points B and E into a PKCS7 message."
389 (let ((buffer (get-buffer-create smime-details-buffer)))
390 (with-current-buffer buffer
392 (when (smime-call-openssl-region b e buffer "smime" "-pk7out")
394 (insert-buffer-substring buffer)
397 (defun smime-pkcs7-certificates-region (b e)
398 "Extract any certificates enclosed in PKCS7 message between points B and E."
399 (let ((buffer (get-buffer-create smime-details-buffer)))
400 (with-current-buffer buffer
402 (when (smime-call-openssl-region b e buffer "pkcs7" "-print_certs" "-text")
404 (insert-buffer-substring buffer)
407 (defun smime-pkcs7-email-region (b e)
408 "Get email addresses contained in certificate between points B and E.
409 A string or a list of strings is returned."
410 (let ((buffer (get-buffer-create smime-details-buffer)))
411 (with-current-buffer buffer
413 (when (smime-call-openssl-region b e buffer "x509" "-email" "-noout")
415 (insert-buffer-substring buffer)
418 (defalias 'smime-point-at-eol
419 (if (fboundp 'point-at-eol)
423 (defun smime-buffer-as-string-region (b e)
424 "Return each line in region between B and E as a list of strings."
429 (let ((str (buffer-substring (point) (smime-point-at-eol))))
430 (unless (string= "" str)
437 (defun smime-mail-to-domain (mailaddr)
438 (if (string-match "@" mailaddr)
439 (replace-match "." 'fixedcase 'literal mailaddr)
442 (defun smime-cert-by-dns (mail)
443 (let* ((dig-dns-server smime-dns-server)
444 (digbuf (dig-invoke (smime-mail-to-domain mail) "cert" nil nil "+vc"))
445 (retbuf (generate-new-buffer (format "*certificate for %s*" mail)))
446 (certrr (with-current-buffer digbuf
447 (dig-extract-rr (smime-mail-to-domain mail) "cert")))
448 (cert (and certrr (dig-rr-get-pkix-cert certrr))))
450 (with-current-buffer retbuf
451 (insert "-----BEGIN CERTIFICATE-----\n")
452 (let ((i 0) (len (length cert)))
453 (while (> (- len 64) i)
454 (insert (substring cert i (+ i 64)) "\n")
456 (insert (substring cert i len) "\n"))
457 (insert "-----END CERTIFICATE-----\n"))
465 (defvar smime-buffer "*SMIME*")
467 (defvar smime-mode-map nil)
468 (put 'smime-mode 'mode-class 'special)
470 (unless smime-mode-map
471 (setq smime-mode-map (make-sparse-keymap))
472 (suppress-keymap smime-mode-map)
474 (define-key smime-mode-map "q" 'smime-exit)
475 (define-key smime-mode-map "f" 'smime-certificate-info))
478 "Major mode for browsing, viewing and fetching certificates.
480 All normal editing commands are switched off.
483 The following commands are available:
487 (kill-all-local-variables)
488 (setq major-mode 'smime-mode)
489 (setq mode-name "SMIME")
490 (setq mode-line-process nil)
491 (use-local-map smime-mode-map)
492 (buffer-disable-undo)
493 (setq truncate-lines t)
494 (setq buffer-read-only t))
496 (defun smime-certificate-info (certfile)
497 (interactive "fCertificate file: ")
498 (let ((buffer (get-buffer-create (format "*certificate %s*" certfile))))
499 (switch-to-buffer buffer)
501 (call-process smime-openssl-program nil buffer 'display
502 "x509" "-in" (expand-file-name certfile) "-text")
504 (set-buffer-modified-p nil)
506 (goto-char (point-min))))
508 (defun smime-draw-buffer ()
509 (with-current-buffer smime-buffer
510 (let (buffer-read-only)
512 (insert "\nYour keys:\n")
513 (dolist (key smime-keys)
515 (format "\t\t%s: %s\n" (car key) (cadr key))))
516 (insert "\nTrusted Certificate Authoritys:\n")
517 (insert "\nKnown Certificates:\n"))))
520 "Go to the SMIME buffer."
522 (unless (get-buffer smime-buffer)
524 (set-buffer (get-buffer-create smime-buffer))
527 (switch-to-buffer smime-buffer))
530 "Quit the S/MIME buffer."
532 (kill-buffer (current-buffer)))
536 (defun smime-get-key-by-email (email)
537 (cadr (assoc email smime-keys)))
541 ;;; smime.el ends here