ce7e9847114602a8fd9f83e8ba6ef069f521ef6b
[elisp/semi.git] / smime.el
1 ;;; smime.el --- S/MIME interface.
2
3 ;; Copyright (C) 1999 Daiki Ueno
4
5 ;; Author: Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
6 ;; Created: 1999/12/08
7 ;; Keywords: S/MIME, OpenSSL
8
9 ;; This file is part of SEMI (Secure Emacs MIME Interface).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program 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., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26
27 ;;; Commentary:
28
29 ;;    This module is based on
30
31 ;;      [SMIMEV3] RFC 2633: "S/MIME Version 3 Message Specification"
32 ;;          by Crocker, D., Flanigan, B., Hoffman, P., Housley, R.,
33 ;;          Pawling, J. and Schaad, J. (1999/06)
34
35 ;;      [SMIMEV2] RFC 2311: "S/MIME Version 2 Message Specification"
36 ;;          by Dusse, S., Hoffman, P., Ramsdell, B., Lundblade, L.
37 ;;          and L. Repka. (1998/03)
38
39 ;;; Code:
40
41 (require 'path-util)
42
43 (defgroup smime ()
44   "S/MIME interface"
45   :group 'mime)
46
47 (defcustom smime-program "smime" 
48   "The S/MIME executable."
49   :group 'smime
50   :type 'string)
51
52 (defcustom smime-shell-file-name "/bin/sh"
53   "File name to load inferior shells from.  Bourne shell or its equivalent
54 \(not tcsh) is needed for \"2>\"."
55   :group 'smime
56   :type 'string)
57
58 (defcustom smime-shell-command-switch "-c"
59   "Switch used to have the shell execute its command line argument."
60   :group 'smime
61   :type 'string)
62
63 (defcustom smime-x509-program
64   (let ((file (exec-installed-p "openssl")))
65     (and file (list file "x509" "-noout")))
66   "External program for x509 parser."
67   :group 'smime
68   :type 'string)
69
70 (defcustom smime-cache-passphrase t
71   "Cache passphrase."
72   :group 'smime
73   :type 'boolean)
74
75 (defcustom smime-certificate-directory "~/.w3/certs"
76   "Certificate directory."
77   :group 'smime
78   :type 'directory)
79
80 (defcustom smime-public-key-file nil
81   "Public key file."
82   :group 'smime
83   :type 'boolean)
84
85 (defcustom smime-private-key-file nil
86   "Private key file."
87   :group 'smime
88   :type 'boolean)
89
90 (defvar smime-errors-buffer " *S/MIME errors*")
91 (defvar smime-output-buffer " *S/MIME output*")
92
93 ;;; @ utility functions
94 ;;;
95 (put 'smime-process-when-success 'lisp-indent-function 0)
96
97 (defmacro smime-process-when-success (&rest body)
98   `(with-current-buffer smime-output-buffer
99      (if (zerop (buffer-size)) nil ,@body t)))
100
101 (defvar smime-passphrase-cache-expiry 16)
102 (defvar smime-passphrase-cache (make-vector 7 0))
103
104 (defvar smime-read-passphrase nil)
105 (defun smime-read-passphrase (prompt &optional key)
106   (if (not smime-read-passphrase)
107       (if (functionp 'read-passwd)
108           (setq smime-read-passphrase 'read-passwd)
109         (if (load "passwd" t)
110             (setq smime-read-passphrase 'read-passwd)
111           (autoload 'ange-ftp-read-passwd "ange-ftp")
112           (setq smime-read-passphrase 'ange-ftp-read-passwd))))
113   (or (and smime-cache-passphrase
114            (symbol-value (intern-soft key smime-passphrase-cache)))
115       (funcall smime-read-passphrase prompt)))
116
117 (defun smime-add-passphrase-cache (key passphrase)
118   (set (intern key smime-passphrase-cache)
119        passphrase)
120   (run-at-time smime-passphrase-cache-expiry nil
121                #'smime-remove-passphrase-cache
122                key))
123
124 (defun smime-remove-passphrase-cache (key)
125   (let ((passphrase (symbol-value (intern-soft key smime-passphrase-cache))))
126     (when passphrase
127       (fillarray passphrase ?_)
128       (unintern key smime-passphrase-cache))))
129
130 (defsubst smime-parse-attribute (string)
131   (delq nil (mapcar 
132              (lambda (attr)
133                (if (string-match "=" attr)
134                    (cons (intern (substring attr 0 (match-beginning 0)))
135                          (substring attr (match-end 0)))
136                  nil))
137              (split-string string "/"))))
138
139 (defsubst smime-query-signer (start end)
140   (smime-process-region start end smime-program (list "-qs"))
141   (with-current-buffer smime-output-buffer
142     (if (zerop (buffer-size)) nil
143       (goto-char (point-min))
144       (when (re-search-forward "^/" nil t)
145         (smime-parse-attribute 
146          (buffer-substring (point) (progn (end-of-line)(point)))))
147       )))
148
149 (defsubst smime-x509-hash (cert-file)
150   (with-current-buffer (get-buffer-create smime-output-buffer)
151     (buffer-disable-undo)
152     (erase-buffer)
153     (apply #'call-process (car smime-x509-program) nil t nil 
154            (append (cdr smime-x509-program) 
155                    (list "-hash" "-in" cert-file)))
156     (if (zerop (buffer-size)) nil
157       (buffer-substring (point-min) (1- (point-max))))))
158
159 (defsubst smime-x509-subject (cert-file)
160   (with-current-buffer (get-buffer-create smime-output-buffer)
161     (buffer-disable-undo)
162     (erase-buffer)
163     (apply #'call-process (car smime-x509-program) nil t nil 
164            (append (cdr smime-x509-program)
165                    (list "-subject" "-in" cert-file)))
166     (if (zerop (buffer-size)) nil
167       (goto-char (point-min))
168       (when (re-search-forward "^subject=" nil t)
169         (smime-parse-attribute
170          (buffer-substring (point)(progn (end-of-line)(point))))))))
171
172 (defsubst smime-search-certificate (attr)
173   (let ((files (if (file-directory-p smime-certificate-directory)
174                    (directory-files smime-certificate-directory)
175                  nil)))
176     (catch 'found
177       (while files
178         (if (or (string-equal 
179                  (cdr (assq 'CN (smime-x509-subject (car files))))
180                  (cdr (assq 'CN attr)))
181                 (string-equal
182                  (cdr (assq 'Email (smime-x509-subject (car files))))
183                  (cdr (assq 'Email attr))))
184             (throw 'found (car files)))
185         (pop files)))))
186
187 (defun smime-process-region (start end program args)
188   (let* ((errors-file-name
189           (concat temporary-file-directory 
190                   (make-temp-name "smime-errors")))
191          (args (append args (list (concat "2>" errors-file-name))))
192          (shell-file-name smime-shell-file-name)
193          (shell-command-switch smime-shell-command-switch)
194          (process-connection-type nil)
195          process status exit-status)
196     (with-current-buffer (get-buffer-create smime-output-buffer)
197       (buffer-disable-undo)
198       (erase-buffer))
199     (as-binary-process
200      (setq process
201            (apply #'start-process-shell-command "*S/MIME*"
202                   smime-output-buffer program args)))
203     (set-process-sentinel process 'ignore)
204     (process-send-region process start end)
205     (process-send-eof process)
206     (while (eq 'run (process-status process))
207       (accept-process-output process 5))
208     (setq status (process-status process)
209           exit-status (process-exit-status process))
210     (delete-process process)
211     (with-current-buffer smime-output-buffer
212       (goto-char (point-min))
213       (while (re-search-forward "\r$" (point-max) t)
214         (replace-match ""))
215
216       (if (memq status '(stop signal))
217           (error "%s exited abnormally: '%s'" program exit-status))
218       (if (= 127 exit-status)
219           (error "%s could not be found" program))
220
221       (set-buffer (get-buffer-create smime-errors-buffer))
222       (buffer-disable-undo)
223       (erase-buffer)
224       (insert-file-contents errors-file-name)
225       (delete-file errors-file-name)
226       
227       (if (and process (eq 'run (process-status process)))
228           (interrupt-process process))
229       )
230     ))
231
232 ;;; @ interface functions
233 ;;;
234
235 ;;;###autoload
236 (defun smime-encrypt-region (start end)
237   "Encrypt the current region between START and END."
238   (let* ((key-file
239           (or smime-private-key-file
240               (expand-file-name (read-file-name "Public key file: "))))
241          (args (list "-e" key-file)))
242     (smime-process-region start end smime-program args)
243     (smime-process-when-success nil)))
244
245 ;;;###autoload
246 (defun smime-decrypt-region (start end)
247   "Decrypt the current region between START and END."
248   (let* ((key-file
249           (or smime-private-key-file
250               (expand-file-name (read-file-name "Private key file: "))))
251          (hash (smime-x509-hash key-file))
252          (passphrase (smime-read-passphrase 
253                       (format "S/MIME passphrase for %s: " hash)
254                       hash))
255          (args (list "-d" key-file passphrase)))
256     (smime-process-region start end smime-program args)
257     (smime-process-when-success 
258       (when smime-cache-passphrase
259         (smime-add-passphrase-cache hash passphrase)))))
260          
261 ;;;###autoload
262 (defun smime-sign-region (start end &optional cleartext)
263   "Make the signature from text between START and END.
264 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
265 a detached signature."
266   (let* ((key-file
267           (or smime-private-key-file
268               (expand-file-name (read-file-name "Private key file: "))))
269          (hash (smime-x509-hash key-file))
270          (passphrase (smime-read-passphrase 
271                       (format "S/MIME passphrase for %s: " hash)
272                       hash))
273          (args (list "-ds" key-file passphrase)))
274     (smime-process-region start end smime-program args)
275     (smime-process-when-success 
276       (when smime-cache-passphrase
277         (smime-add-passphrase-cache hash passphrase)))))
278
279 ;;;###autoload
280 (defun smime-verify-region (start end signature)
281   "Verify the current region between START and END.
282 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
283 the detached signature of the current region."
284   (let* ((basename (expand-file-name "smime" temporary-file-directory))
285          (orig-file (make-temp-name basename))
286          (args (list "-qs" signature))
287          (orig-mode (default-file-modes))
288          cert-file)
289     (unwind-protect
290         (progn
291           (set-default-file-modes 448)
292           (write-region-as-binary start end orig-file)
293           )
294       (set-default-file-modes orig-mode))
295     (with-temp-buffer
296       (insert-file-contents-as-binary signature)
297       (goto-char (point-max))
298       (insert "\n")
299       (insert-file-contents-as-binary
300        (or (smime-search-certificate 
301             (smime-query-signer (point-min)(point-max)))
302            (expand-file-name 
303             (read-file-name "Certificate file: "))))
304       (smime-process-region (point-min)(point-max) smime-program args))
305     (smime-process-when-success 
306       (when smime-cache-passphrase
307         (smime-add-passphrase-cache hash passphrase)))
308     ))
309
310 (provide 'smime)
311
312 ;;; smime.el ends here