Synch to No Gnus 200501120840.
[elisp/gnus.git-] / lisp / encrypt.el
1 ;;; encrypt.el --- file encryption routines
2 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3
4 ;; Author: Teodor Zlatanov <tzz@lifelogs.com>
5 ;; Created: 2003/01/24
6 ;; Keywords: files
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; This module addresses data encryption.  Page breaks are used for
28 ;;; grouping declarations and documentation relating to each
29 ;;; particular aspect.
30
31 ;;; Code:
32
33 ;; autoload password
34 (eval-and-compile
35   (autoload 'password-read "password")
36   ;; The following section is needed since T-gnus won't load password.el
37   ;; by way of pgg.el at the compile time.
38   (autoload 'password-read-and-add "password")
39   (autoload 'password-cache-remove "password")
40   (defvar password-cache-expiry))
41
42 (defgroup encrypt nil
43   "File encryption configuration.")
44
45 (defcustom encrypt-password-cache-expiry 200
46   "Encryption password timeout.
47 When set, directly sets password-cache-expiry"
48   :type 'integer
49   :group 'encrypt
50   :set (lambda (symbol value)
51          (set symbol value)
52          (setq password-cache-expiry value)))
53
54 (defcustom encrypt-file-alist nil
55   "List of file names or regexes matched with encryptions.
56 Format example:
57  '((\"beta\"
58     (gpg \"AES\"))
59    (\"/home/tzz/alpha\"
60     (encrypt-xor \"Semi-Secret\")))"
61
62   :type '(repeat
63           (list :tag "Encryption entry"
64            (radio :tag "What to encrypt"
65                   (file :tag "Filename")
66                   (regexp :tag "Regular expression match"))
67            (radio :tag "How to encrypt it"
68                   (list
69                    :tag "GPG Encryption"
70                    (const :tag "GPG Program" gpg)
71                    (radio :tag "Choose a cipher"
72                           (const :tag "3DES Encryption" "3DES")
73                           (const :tag "CAST5 Encryption" "CAST5")
74                           (const :tag "Blowfish Encryption" "BLOWFISH")
75                           (const :tag "AES Encryption" "AES")
76                           (const :tag "AES192 Encryption" "AES192")
77                           (const :tag "AES256 Encryption" "AES256")
78                           (const :tag "Twofish Encryption" "TWOFISH")
79                           (string :tag "Cipher Name")))
80                   (list
81                    :tag "Built-in simple XOR"
82                    (const :tag "XOR Encryption" encrypt-xor)
83                    (string :tag "XOR Cipher Value (seed value)")))))
84   :group 'encrypt)
85
86 ;; TODO: now, load gencrypt.el and if successful, modify the
87 ;; custom-type of encrypt-file-alist to add the gencrypt.el options
88
89 ;; (plist-get (symbol-plist 'encrypt-file-alist) 'custom-type)
90 ;; then use plist-put
91
92 (defcustom encrypt-gpg-path (executable-find "gpg")
93   "Path to the GPG program."
94   :type '(radio
95           (file :tag "Location of the GPG executable")
96           (const :tag "GPG is not installed" nil))
97   :group 'encrypt)
98
99 (defvar encrypt-temp-prefix "encrypt"
100   "Prefix for temporary filenames")
101
102 ;;;###autoload
103 (defun encrypt-find-model (filename)
104   "Given a filename, find a encrypt-file-alist entry"
105   (dolist (entry encrypt-file-alist)
106     (let ((match (nth 0 entry))
107           (model (nth 1 entry)))
108       (when (or (eq match filename)
109                 (string-match match filename))
110         (return model)))))
111
112 ;;;###autoload
113 (defun encrypt-insert-file-contents (file &optional model)
114   "Decrypt FILE into the current buffer."
115   (interactive "fFile to insert: ")
116   (let* ((model (or model (encrypt-find-model file)))
117          (method (nth 0 model))
118          (cipher (nth 1 model))
119          (password-key (format "encrypt-password-%s-%s %s"
120                                (symbol-name method) cipher file))
121          (passphrase
122           (password-read-and-add
123            (format "%s password for cipher %s? "
124                    (symbol-name method) cipher)
125            password-key))
126           (buffer-file-coding-system 'binary)
127          (coding-system-for-read 'binary)
128          outdata)
129
130     ;; note we only insert-file-contents if the method is known to be valid
131     (cond
132      ((eq method 'gpg)
133       (insert-file-contents file)
134       (setq outdata (encrypt-gpg-decode-buffer passphrase cipher)))
135      ((eq method 'encrypt-xor)
136       (insert-file-contents file)
137       (setq outdata (encrypt-xor-decode-buffer passphrase cipher))))
138
139     (if outdata
140         (progn
141           (gnus-message 9 "%s was decrypted with %s (cipher %s)"
142                         file (symbol-name method) cipher)
143           (delete-region (point-min) (point-max))
144           (goto-char (point-min))
145           (insert outdata))
146       ;; the decryption failed, alas
147       (password-cache-remove password-key)
148       (gnus-error 5 "%s was NOT decrypted with %s (cipher %s)"
149                   file (symbol-name method) cipher))))
150
151 (defun encrypt-get-file-contents (file &optional model)
152   "Decrypt FILE and return the contents."
153   (interactive "fFile to decrypt: ")
154   (with-temp-buffer
155     (encrypt-insert-file-contents file model)
156     (buffer-string)))
157
158 (defun encrypt-put-file-contents (file data &optional model)
159   "Encrypt the DATA to FILE, then continue normally."
160   (with-temp-buffer
161     (insert data)
162     (encrypt-write-file-contents file model)))
163
164 (defun encrypt-write-file-contents (file &optional model)
165   "Encrypt the current buffer to FILE, then continue normally."
166   (interactive "fFile to write: ")
167   (let* ((model (or model (encrypt-find-model file)))
168          (method (nth 0 model))
169          (cipher (nth 1 model))
170          (password-key (format "encrypt-password-%s-%s %s"
171                                (symbol-name method) cipher file))
172          (passphrase
173           (password-read
174            (format "%s password for cipher %s? "
175                    (symbol-name method) cipher)
176            password-key))
177          outdata)
178
179     (cond
180      ((eq method 'gpg)
181       (setq outdata (encrypt-gpg-encode-buffer passphrase cipher)))
182      ((eq method 'encrypt-xor)
183       (setq outdata (encrypt-xor-encode-buffer passphrase cipher))))
184
185     (if outdata
186         (progn
187           (gnus-message 9 "%s was encrypted with %s (cipher %s)"
188                         file (symbol-name method) cipher)
189           (delete-region (point-min) (point-max))
190           (goto-char (point-min))
191           (insert outdata)
192           ;; do not confirm overwrites
193           (write-file file nil))
194       ;; the decryption failed, alas
195       (password-cache-remove password-key)
196       (gnus-error 5 "%s was NOT encrypted with %s (cipher %s)"
197                   file (symbol-name method) cipher))))
198
199 (defun encrypt-xor-encode-buffer (passphrase cipher)
200   (encrypt-xor-process-buffer passphrase cipher t))
201
202 (defun encrypt-xor-decode-buffer (passphrase cipher)
203   (encrypt-xor-process-buffer passphrase cipher nil))
204
205 (defun encrypt-xor-process-buffer (passphrase
206                                         cipher
207                                         &optional encode)
208   "Given PASSPHRASE, xor-encode or decode the contents of the current buffer."
209   (let* ((bs (buffer-substring-no-properties (point-min) (point-max)))
210          ;; passphrase-sum is a simple additive checksum of the
211          ;; passphrase and the cipher
212         (passphrase-sum
213          (when (stringp passphrase)
214            (apply '+ (append cipher passphrase nil))))
215         new-list)
216
217     (with-temp-buffer
218       (if encode
219           (progn
220             (dolist (x (append bs nil))
221               (setq new-list (cons (logxor x passphrase-sum) new-list)))
222
223             (dolist (x new-list)
224               (insert (format "%d " x))))
225         (progn
226           (setq new-list (reverse (split-string bs)))
227           (dolist (x new-list)
228             (setq x (string-to-int x))
229             (insert (format "%c" (logxor x passphrase-sum))))))
230       (buffer-substring-no-properties (point-min) (point-max)))))
231
232 (defun encrypt-gpg-encode-buffer (passphrase cipher)
233   (encrypt-gpg-process-buffer passphrase cipher t))
234
235 (defun encrypt-gpg-decode-buffer (passphrase cipher)
236   (encrypt-gpg-process-buffer passphrase cipher nil))
237
238 (defun encrypt-gpg-process-buffer (passphrase 
239                                         cipher 
240                                         &optional encode)
241   "With PASSPHRASE, use GPG to encode or decode the current buffer."
242   (let* ((program encrypt-gpg-path)
243          (input (buffer-substring-no-properties (point-min) (point-max)))
244          (temp-maker (if (fboundp 'make-temp-file) 
245                          'make-temp-file 
246                        'make-temp-name))
247          (temp-file (funcall temp-maker encrypt-temp-prefix))
248          (default-enable-multibyte-characters nil)
249          (args `("--cipher-algo" ,cipher
250                  "--status-fd" "2"
251                  "--logger-fd" "2"
252                  "--passphrase-fd" "0"
253                  "--no-tty"))
254          exit-status exit-data)
255     
256     (when encode
257       (setq args
258             (append args
259                     '("--symmetric"
260                       "--armor"))))
261
262     (if program
263         (with-temp-buffer
264           (when passphrase
265             (insert passphrase "\n"))
266           (insert input)
267           (setq exit-status
268                 (apply #'call-process-region (point-min) (point-max) program
269                        t `(t ,temp-file) nil args))
270           (if (equal exit-status 0)
271               (setq exit-data
272                     (buffer-substring-no-properties (point-min) (point-max)))
273             (with-temp-buffer
274               (when (file-exists-p temp-file)
275                 (insert-file-contents temp-file))
276               (gnus-error 5 (format "%s exited abnormally: '%s' [%s]"
277                                     program exit-status (buffer-string)))))
278           (delete-file temp-file))
279       (gnus-error 5 "GPG is not installed."))
280     exit-data))
281
282 (provide 'encrypt)
283 ;;; encrypt.el ends here