Synch with the semi-1_14 branch.
[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 (eval-when-compile (require 'static))
43
44 (defgroup smime ()
45   "S/MIME interface"
46   :group 'mime)
47
48 (defcustom smime-program "smime" 
49   "The S/MIME executable."
50   :group 'smime
51   :type 'string)
52
53 (defcustom smime-shell-file-name "/bin/sh"
54   "File name to load inferior shells from.  Bourne shell or its equivalent
55 \(not tcsh) is needed for \"2>\"."
56   :group 'smime
57   :type 'string)
58
59 (defcustom smime-shell-command-switch "-c"
60   "Switch used to have the shell execute its command line argument."
61   :group 'smime
62   :type 'string)
63
64 (defcustom smime-x509-program
65   (let ((file (exec-installed-p "openssl")))
66     (and file (list file "x509" "-noout")))
67   "External program for x509 parser."
68   :group 'smime
69   :type 'string)
70
71 (defcustom smime-cache-passphrase t
72   "Cache passphrase."
73   :group 'smime
74   :type 'boolean)
75
76 (defcustom smime-certificate-directory "~/.w3/certs"
77   "Certificate directory."
78   :group 'smime
79   :type 'directory)
80
81 (defcustom smime-public-key-file nil
82   "Public key file."
83   :group 'smime
84   :type 'boolean)
85
86 (defcustom smime-private-key-file nil
87   "Private key file."
88   :group 'smime
89   :type 'boolean)
90
91 (defvar smime-errors-buffer " *S/MIME errors*")
92 (defvar smime-output-buffer " *S/MIME output*")
93
94 ;;; @ utility functions
95 ;;;
96 (put 'smime-process-when-success 'lisp-indent-function 0)
97
98 (defmacro smime-process-when-success (&rest body)
99   `(with-current-buffer smime-output-buffer
100      (if (zerop (buffer-size)) nil ,@body t)))
101
102 (defvar smime-passphrase-cache-expiry 16)
103 (defvar smime-passphrase-cache (make-vector 7 0))
104
105 (defvar smime-read-passphrase nil)
106 (defun smime-read-passphrase (prompt &optional key)
107   (if (not smime-read-passphrase)
108       (if (functionp 'read-passwd)
109           (setq smime-read-passphrase 'read-passwd)
110         (if (load "passwd" t)
111             (setq smime-read-passphrase 'read-passwd)
112           (autoload 'ange-ftp-read-passwd "ange-ftp")
113           (setq smime-read-passphrase 'ange-ftp-read-passwd))))
114   (or (and smime-cache-passphrase
115            (symbol-value (intern-soft key smime-passphrase-cache)))
116       (funcall smime-read-passphrase prompt)))
117
118 (defun smime-add-passphrase-cache (key passphrase)
119   (set (intern key smime-passphrase-cache)
120        passphrase)
121   (run-at-time smime-passphrase-cache-expiry nil
122                #'smime-remove-passphrase-cache
123                key))
124
125 (defun smime-remove-passphrase-cache (key)
126   (let ((passphrase (symbol-value (intern-soft key smime-passphrase-cache))))
127     (when passphrase
128       (fillarray passphrase ?_)
129       (unintern key smime-passphrase-cache))))
130
131 (defsubst smime-parse-attribute (string)
132   (delq nil (mapcar 
133              (lambda (attr)
134                (if (string-match "=" attr)
135                    (cons (intern (substring attr 0 (match-beginning 0)))
136                          (substring attr (match-end 0)))
137                  nil))
138              (split-string string "/"))))
139
140 (defsubst smime-query-signer (start end)
141   (smime-process-region start end smime-program (list "-qs"))
142   (with-current-buffer smime-output-buffer
143     (if (zerop (buffer-size)) nil
144       (goto-char (point-min))
145       (when (re-search-forward "^/" nil t)
146         (smime-parse-attribute 
147          (buffer-substring (point) (progn (end-of-line)(point))))))))
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-find-certificate (attr)
173   (let ((files
174          (and (file-directory-p smime-certificate-directory)
175               (delq nil (mapcar (lambda (file) 
176                                   (if (file-directory-p file) nil
177                                     file))
178                                 (directory-files 
179                                  smime-certificate-directory
180                                  'full))))))
181     (catch 'found
182       (while files
183         (if (or (string-equal 
184                  (cdr (assq 'CN (smime-x509-subject (car files))))
185                  (cdr (assq 'CN attr)))
186                 (string-equal
187                  (cdr (assq 'Email (smime-x509-subject (car files))))
188                  (cdr (assq 'Email attr))))
189             (throw 'found (car files)))
190         (pop files)))))
191
192 (defun smime-process-region (start end program args)
193   (let* ((errors-file-name
194           (concat temporary-file-directory 
195                   (make-temp-name "smime-errors")))
196          (args (append args (list (concat "2>" errors-file-name))))
197          (shell-file-name smime-shell-file-name)
198          (shell-command-switch smime-shell-command-switch)
199          (process-connection-type nil)
200          process status exit-status)
201     (with-current-buffer (get-buffer-create smime-output-buffer)
202       (buffer-disable-undo)
203       (erase-buffer))
204     (as-binary-process
205      (setq process
206            (apply #'start-process-shell-command "*S/MIME*"
207                   smime-output-buffer program args)))
208     (set-process-sentinel process 'ignore)
209     (process-send-region process start end)
210     (process-send-eof process)
211     (while (eq 'run (process-status process))
212       (accept-process-output process 5))
213     (setq status (process-status process)
214           exit-status (process-exit-status process))
215     (delete-process process)
216     (with-current-buffer smime-output-buffer
217       (goto-char (point-min))
218       (while (re-search-forward "\r$" (point-max) t)
219         (replace-match ""))
220
221       (if (memq status '(stop signal))
222           (error "%s exited abnormally: '%s'" program exit-status))
223       (if (= 127 exit-status)
224           (error "%s could not be found" program))
225
226       (set-buffer (get-buffer-create smime-errors-buffer))
227       (buffer-disable-undo)
228       (erase-buffer)
229       (insert-file-contents errors-file-name)
230       (delete-file errors-file-name)
231       
232       (if (and process (eq 'run (process-status process)))
233           (interrupt-process process)))))
234
235 ;;; @ interface functions
236 ;;;
237
238 ;;;###autoload
239 (defun smime-encrypt-region (start end)
240   "Encrypt the current region between START and END."
241   (let* ((key-file
242           (or smime-private-key-file
243               (expand-file-name (read-file-name "Public key file: "))))
244          (args (list "-e" key-file)))
245     (smime-process-region start end smime-program args)
246     (smime-process-when-success 
247       (goto-char (point-min))
248       (delete-region (point-min) (progn
249                                    (re-search-forward "^$" nil t)
250                                    (1+ (point)))))))
251
252 ;;;###autoload
253 (defun smime-decrypt-region (start end)
254   "Decrypt the current region between START and END."
255   (let* ((key-file
256           (or smime-private-key-file
257               (expand-file-name (read-file-name "Private key file: "))))
258          (hash (smime-x509-hash key-file))
259          (passphrase (smime-read-passphrase 
260                       (format "S/MIME passphrase for %s: " hash)
261                       hash))
262          (args (list "-d" key-file passphrase)))
263     (smime-process-region start end smime-program args)
264     (smime-process-when-success 
265       (when smime-cache-passphrase
266         (smime-add-passphrase-cache hash passphrase)))))
267          
268 ;;;###autoload
269 (defun smime-sign-region (start end &optional cleartext)
270   "Make the signature from text between START and END.
271 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
272 a detached signature."
273   (let* ((key-file
274           (or smime-private-key-file
275               (expand-file-name (read-file-name "Private key file: "))))
276          (hash (smime-x509-hash key-file))
277          (passphrase (smime-read-passphrase 
278                       (format "S/MIME passphrase for %s: " hash)
279                       hash))
280          (args (list "-ds" key-file passphrase)))
281     (smime-process-region start end smime-program args)
282     (smime-process-when-success 
283       (goto-char (point-min))
284       (delete-region (point-min) (progn
285                                    (re-search-forward "^$" nil t)
286                                    (1+ (point))))
287       (when smime-cache-passphrase
288         (smime-add-passphrase-cache hash passphrase)))))
289
290 ;;;###autoload
291 (defun smime-verify-region (start end signature)
292   "Verify the current region between START and END.
293 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
294 the detached signature of the current region."
295   (let* ((basename (expand-file-name "smime" temporary-file-directory))
296          (orig-file (make-temp-name basename))
297          (orig-mode (default-file-modes)))
298     (unwind-protect
299         (progn
300           (set-default-file-modes 448)
301           (write-region-as-binary start end orig-file))
302       (set-default-file-modes orig-mode))
303     (with-temp-buffer
304       (insert-file-contents-as-binary signature)
305       (goto-char (point-max))
306       (insert-file-contents-as-binary
307        (or (smime-find-certificate 
308             (smime-query-signer (point-min)(point-max)))
309            (expand-file-name 
310             (read-file-name "Certificate file: "))))
311       (smime-process-region (point-min)(point-max) smime-program 
312                             (list "-dv" orig-file)))
313     (smime-process-when-success nil)))
314
315 (provide 'smime)
316
317 ;;; smime.el ends here