Relicense "GPLv2 or later" files to "GPLv3 or later".
[gnus] / lisp / encrypt.el
1 ;;; encrypt.el --- file encryption routines
2 ;; Copyright (C) 2002, 2003, 2004, 2005 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 3, 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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, 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 ;;; Use in Gnus like this:
32 ;;; (setq
33 ;;;   nnimap-authinfo-file "~/.authinfo.enc"
34 ;;;   nntp-authinfo-file "~/.authinfo.enc"
35 ;;;   smtpmail-auth-credentials "~/.authinfo.enc"
36 ;;;   ;; using the AES256 cipher, feel free to use your own favorite
37 ;;;   encrypt-file-alist (quote (("~/.authinfo.enc" (gpg "AES256"))))
38 ;;;   password-cache-expiry 600)
39
40 ;;; Then write ~/.authinfo.enc:
41
42 ;;; 1) open the old authinfo
43 ;;; C-x C-f ~/.authinfo
44
45 ;;; 2) write the new authinfo.enc
46 ;;; M-x encrypt-file-contents ~/.authinfo.enc
47
48 ;;; 3) verify the new authinfo is correct (this will show the contents in the minibuffer)
49 ;;; M-: (encrypt-get-file-contents "~/.authinfo.enc")
50
51
52 ;;; Code:
53
54 ;; autoload password
55 (eval-and-compile
56   (autoload 'password-read "password"))
57
58 (defgroup encrypt '((password-cache custom-variable)
59                     (password-cache-expiry custom-variable))
60   "File encryption configuration."
61   :group 'applications)
62
63 (defcustom encrypt-file-alist nil
64   "List of file names or regexes matched with encryptions.
65 Format example:
66  '((\"beta\"
67     (gpg \"AES\"))
68    (\"/home/tzz/alpha\"
69     (encrypt-xor \"Semi-Secret\")))"
70
71   :type '(repeat
72           (list :tag "Encryption entry"
73            (radio :tag "What to encrypt"
74                   (file :tag "Filename")
75                   (regexp :tag "Regular expression match"))
76            (radio :tag "How to encrypt it"
77                   (list
78                    :tag "GPG Encryption"
79                    (const :tag "GPG Program" gpg)
80                    (radio :tag "Choose a cipher"
81                           (const :tag "3DES Encryption" "3DES")
82                           (const :tag "CAST5 Encryption" "CAST5")
83                           (const :tag "Blowfish Encryption" "BLOWFISH")
84                           (const :tag "AES Encryption" "AES")
85                           (const :tag "AES192 Encryption" "AES192")
86                           (const :tag "AES256 Encryption" "AES256")
87                           (const :tag "Twofish Encryption" "TWOFISH")
88                           (string :tag "Cipher Name")))
89                   (list
90                    :tag "Built-in simple XOR"
91                    (const :tag "XOR Encryption" encrypt-xor)
92                    (string :tag "XOR Cipher Value (seed value)")))))
93   :group 'encrypt)
94
95 ;; TODO: now, load gencrypt.el and if successful, modify the
96 ;; custom-type of encrypt-file-alist to add the gencrypt.el options
97
98 ;; (plist-get (symbol-plist 'encrypt-file-alist) 'custom-type)
99 ;; then use plist-put
100
101 (defcustom encrypt-gpg-path (executable-find "gpg")
102   "Path to the GPG program."
103   :type '(radio
104           (file :tag "Location of the GPG executable")
105           (const :tag "GPG is not installed" nil))
106   :group 'encrypt)
107
108 (defvar encrypt-temp-prefix "encrypt"
109   "Prefix for temporary filenames")
110
111 ;;;###autoload
112 (defun encrypt-find-model (filename)
113   "Given a filename, find a encrypt-file-alist entry"
114   (dolist (entry encrypt-file-alist)
115     (let ((match (nth 0 entry))
116           (model (nth 1 entry)))
117       (when (or (eq match filename)
118                 (string-match match filename))
119         (return model)))))
120
121 ;;;###autoload
122 (defun encrypt-insert-file-contents (file &optional model)
123   "Decrypt FILE into the current buffer."
124   (interactive "fFile to insert: ")
125   (let* ((model (or model (encrypt-find-model file)))
126          (method (nth 0 model))
127          (cipher (nth 1 model))
128          (password-key (format "encrypt-password-%s-%s %s"
129                                (symbol-name method) cipher file))
130          (passphrase
131           (password-read-and-add
132            (format "%s password for cipher %s (file %s)? "
133                    file (symbol-name method) cipher)
134            password-key))
135           (buffer-file-coding-system 'binary)
136          (coding-system-for-read 'binary)
137          outdata)
138
139     ;; note we only insert-file-contents if the method is known to be valid
140     (cond
141      ((eq method 'gpg)
142       (insert-file-contents file)
143       (setq outdata (encrypt-gpg-decode-buffer passphrase cipher)))
144      ((eq method 'encrypt-xor)
145       (insert-file-contents file)
146       (setq outdata (encrypt-xor-decode-buffer passphrase cipher))))
147
148     (if outdata
149         (progn
150           (message "%s was decrypted with %s (cipher %s)"
151                    file (symbol-name method) cipher)
152           (delete-region (point-min) (point-max))
153           (goto-char (point-min))
154           (insert outdata))
155       ;; the decryption failed, alas
156       (password-cache-remove password-key)
157       (gnus-error 5 "%s was NOT decrypted with %s (cipher %s)"
158                   file (symbol-name method) cipher))))
159
160 (defun encrypt-get-file-contents (file &optional model)
161   "Decrypt FILE and return the contents."
162   (interactive "fFile to decrypt: ")
163   (with-temp-buffer
164     (encrypt-insert-file-contents file model)
165     (buffer-string)))
166
167 (defun encrypt-put-file-contents (file data &optional model)
168   "Encrypt the DATA to FILE, then continue normally."
169   (with-temp-buffer
170     (insert data)
171     (encrypt-write-file-contents file model)))
172
173 (defun encrypt-write-file-contents (file &optional model)
174   "Encrypt the current buffer to FILE, then continue normally."
175   (interactive "sFile to write: ")
176   (setq model (or model (encrypt-find-model file)))
177   (if model
178       (let* ((method (nth 0 model))
179              (cipher (nth 1 model))
180              (password-key (format "encrypt-password-%s-%s %s"
181                                    (symbol-name method) cipher file))
182              (passphrase
183               (password-read
184                (format "%s password for cipher %s? "
185                        (symbol-name method) cipher)
186                password-key))
187              outdata)
188
189         (cond
190          ((eq method 'gpg)
191           (setq outdata (encrypt-gpg-encode-buffer passphrase cipher)))
192          ((eq method 'encrypt-xor)
193           (setq outdata (encrypt-xor-encode-buffer passphrase cipher))))
194
195         (if outdata
196             (progn
197               (message "%s was encrypted with %s (cipher %s)"
198                        file (symbol-name method) cipher)
199               (delete-region (point-min) (point-max))
200               (goto-char (point-min))
201               (insert outdata)
202               ;; do not confirm overwrites
203               (write-file file nil))
204           ;; the decryption failed, alas
205           (password-cache-remove password-key)
206           (gnus-error 5 "%s was NOT encrypted with %s (cipher %s)"
207                       file (symbol-name method) cipher)))
208     (gnus-error 1 "%s has no associated encryption model!  See encrypt-file-alist." file)))
209
210 (defun encrypt-xor-encode-buffer (passphrase cipher)
211   (encrypt-xor-process-buffer passphrase cipher t))
212
213 (defun encrypt-xor-decode-buffer (passphrase cipher)
214   (encrypt-xor-process-buffer passphrase cipher nil))
215
216 (defun encrypt-xor-process-buffer (passphrase
217                                         cipher
218                                         &optional encode)
219   "Given PASSPHRASE, xor-encode or decode the contents of the current buffer."
220   (let* ((bs (buffer-substring-no-properties (point-min) (point-max)))
221          ;; passphrase-sum is a simple additive checksum of the
222          ;; passphrase and the cipher
223         (passphrase-sum
224          (when (stringp passphrase)
225            (apply '+ (append cipher passphrase nil))))
226         new-list)
227
228     (with-temp-buffer
229       (if encode
230           (progn
231             (dolist (x (append bs nil))
232               (setq new-list (cons (logxor x passphrase-sum) new-list)))
233
234             (dolist (x new-list)
235               (insert (format "%d " x))))
236         (progn
237           (setq new-list (reverse (split-string bs)))
238           (dolist (x new-list)
239             (setq x (string-to-number x))
240             (insert (format "%c" (logxor x passphrase-sum))))))
241       (buffer-substring-no-properties (point-min) (point-max)))))
242
243 (defun encrypt-gpg-encode-buffer (passphrase cipher)
244   (encrypt-gpg-process-buffer passphrase cipher t))
245
246 (defun encrypt-gpg-decode-buffer (passphrase cipher)
247   (encrypt-gpg-process-buffer passphrase cipher nil))
248
249 (defun encrypt-gpg-process-buffer (passphrase 
250                                         cipher 
251                                         &optional encode)
252   "With PASSPHRASE, use GPG to encode or decode the current buffer."
253   (let* ((program encrypt-gpg-path)
254          (input (buffer-substring-no-properties (point-min) (point-max)))
255          (temp-maker (if (fboundp 'make-temp-file) 
256                          'make-temp-file 
257                        'make-temp-name))
258          (temp-file (funcall temp-maker encrypt-temp-prefix))
259          (default-enable-multibyte-characters nil)
260          (args `("--cipher-algo" ,cipher
261                  "--status-fd" "2"
262                  "--logger-fd" "2"
263                  "--passphrase-fd" "0"
264                  "--no-tty"))
265          exit-status exit-data)
266     
267     (when encode
268       (setq args
269             (append args
270                     '("--symmetric"
271                       "--armor"))))
272
273     (if program
274         (with-temp-buffer
275           (when passphrase
276             (insert passphrase "\n"))
277           (insert input)
278           (setq exit-status
279                 (apply #'call-process-region (point-min) (point-max) program
280                        t `(t ,temp-file) nil args))
281           (if (equal exit-status 0)
282               (setq exit-data
283                     (buffer-substring-no-properties (point-min) (point-max)))
284             (with-temp-buffer
285               (when (file-exists-p temp-file)
286                 (insert-file-contents temp-file))
287               (gnus-error 5 (format "%s exited abnormally: '%s' [%s]"
288                                     program exit-status (buffer-string)))))
289           (delete-file temp-file))
290       (gnus-error 5 "GPG is not installed."))
291     exit-data))
292
293 (provide 'encrypt)
294 ;;; encrypt.el ends here
295
296 ;; arch-tag: d907e4f1-71b5-42b1-a180-fc7b84ff0648