_From Daiki Ueno <ueno(at)unixuser.org>
[gnus] / lisp / pgg-gpg.el
1 ;;; pgg-gpg.el --- GnuPG support for PGG.
2
3 ;; Copyright (C) 1999, 2000, 2002, 2003, 2004,
4 ;;   2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Daiki Ueno <ueno@unixuser.org>
7 ;; Symmetric encryption added by: Sascha Wilde <wilde@sha-bang.de>
8 ;; Created: 1999/10/28
9 ;; Keywords: PGP, OpenPGP, GnuPG
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Code:
29
30 (eval-when-compile
31   (require 'cl)                         ; for gpg macros
32   (require 'pgg))
33
34 (defgroup pgg-gpg ()
35   "GnuPG interface."
36   :group 'pgg)
37
38 (defcustom pgg-gpg-program "gpg"
39   "The GnuPG executable."
40   :group 'pgg-gpg
41   :type 'string)
42
43 (defcustom pgg-gpg-extra-args nil
44   "Extra arguments for every GnuPG invocation."
45   :group 'pgg-gpg
46   :type '(repeat (string :tag "Argument")))
47
48 (defcustom pgg-gpg-recipient-argument "--recipient"
49   "GnuPG option to specify recipient."
50   :group 'pgg-gpg
51   :type '(choice (const :tag "New `--recipient' option" "--recipient")
52                  (const :tag "Old `--remote-user' option" "--remote-user")))
53
54 (defvar pgg-gpg-user-id nil
55   "GnuPG ID of your default identity.")
56
57 (defun pgg-gpg-process-region (start end passphrase program args)
58   (let* ((output-file-name (pgg-make-temp-file "pgg-output"))
59          (args
60           `("--status-fd" "2"
61             ,@(if passphrase '("--passphrase-fd" "0"))
62             "--yes" ; overwrite
63             "--output" ,output-file-name
64             ,@pgg-gpg-extra-args ,@args))
65          (output-buffer pgg-output-buffer)
66          (errors-buffer pgg-errors-buffer)
67          (orig-mode (default-file-modes))
68          (process-connection-type nil)
69          exit-status)
70     (with-current-buffer (get-buffer-create errors-buffer)
71       (buffer-disable-undo)
72       (erase-buffer))
73     (unwind-protect
74         (progn
75           (set-default-file-modes 448)
76           (let ((coding-system-for-write 'binary)
77                 (input (buffer-substring-no-properties start end))
78                 (default-enable-multibyte-characters nil))
79             (with-temp-buffer
80               (when passphrase
81                 (insert passphrase "\n"))
82               (insert input)
83               (setq exit-status
84                     (apply #'call-process-region (point-min) (point-max) program
85                            nil errors-buffer nil args))))
86           (with-current-buffer (get-buffer-create output-buffer)
87             (buffer-disable-undo)
88             (erase-buffer)
89             (if (file-exists-p output-file-name)
90                 (let ((coding-system-for-read (if pgg-text-mode
91                                                   'raw-text
92                                                 'binary)))
93                   (insert-file-contents output-file-name)))
94             (set-buffer errors-buffer)
95             (if (not (equal exit-status 0))
96                 (insert (format "\n%s exited abnormally: '%s'\n"
97                                 program exit-status)))))
98       (if (file-exists-p output-file-name)
99           (delete-file output-file-name))
100       (set-default-file-modes orig-mode))))
101
102 (defun pgg-gpg-possibly-cache-passphrase (passphrase &optional key notruncate)
103   (if (and pgg-cache-passphrase
104            (progn
105              (goto-char (point-min))
106              (re-search-forward "^\\[GNUPG:] \\(GOOD_PASSPHRASE\\>\\)\\|\\(SIG_CREATED\\)" nil t)))
107       (pgg-add-passphrase-to-cache
108        (or key
109            (progn
110              (goto-char (point-min))
111              (if (re-search-forward
112                   "^\\[GNUPG:] NEED_PASSPHRASE\\(_PIN\\)? \\w+ ?\\w*" nil t)
113                  (substring (match-string 0) -8))))
114        passphrase
115        notruncate)))
116
117 (defvar pgg-gpg-all-secret-keys 'unknown)
118
119 (defun pgg-gpg-lookup-all-secret-keys ()
120   "Return all secret keys present in secret key ring."
121   (when (eq pgg-gpg-all-secret-keys 'unknown)
122     (setq pgg-gpg-all-secret-keys '())
123     (let ((args (list "--with-colons" "--no-greeting" "--batch"
124                       "--list-secret-keys")))
125       (with-temp-buffer
126         (apply #'call-process pgg-gpg-program nil t nil args)
127         (goto-char (point-min))
128         (while (re-search-forward
129                 "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)" nil t)
130           (push (substring (match-string 2) 8)
131                 pgg-gpg-all-secret-keys)))))
132   pgg-gpg-all-secret-keys)
133
134 (defun pgg-gpg-lookup-key (string &optional type)
135   "Search keys associated with STRING."
136   (let ((args (list "--with-colons" "--no-greeting" "--batch"
137                     (if type "--list-secret-keys" "--list-keys")
138                     string)))
139     (with-temp-buffer
140       (apply #'call-process pgg-gpg-program nil t nil args)
141       (goto-char (point-min))
142       (if (re-search-forward "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)"
143                              nil t)
144           (substring (match-string 2) 8)))))
145
146 (defun pgg-gpg-lookup-key-owner (string &optional all)
147   "Search keys associated with STRING and return owner of identified key.
148
149 The value may be just the bare key id, or it may be a combination of the
150 user name associated with the key and the key id, with the key id enclosed
151 in \"<...>\" angle brackets.
152
153 Optional ALL non-nil means search all keys, including secret keys."
154   (let ((args (list "--with-colons" "--no-greeting" "--batch"
155                     (if all "--list-secret-keys" "--list-keys")
156                     string))
157         (key-regexp (concat "^\\(sec\\|pub\\)"
158                             ":[^:]*:[^:]*:[^:]*:\\([^:]*\\):[^:]*"
159                             ":[^:]*:[^:]*:[^:]*:\\([^:]*\\):")))
160     (with-temp-buffer
161       (apply #'call-process pgg-gpg-program nil t nil args)
162       (goto-char (point-min))
163       (if (re-search-forward key-regexp
164                              nil t)
165           (match-string 3)))))
166
167 (defun pgg-gpg-key-id-from-key-owner (key-owner)
168   (cond ((not key-owner) nil)
169         ;; Extract bare key id from outermost paired angle brackets, if any:
170         ((string-match "[^<]*<\\(.+\\)>[^>]*" key-owner)
171          (substring key-owner (match-beginning 1)(match-end 1)))
172         (key-owner)))
173
174 (defun pgg-gpg-encrypt-region (start end recipients &optional sign passphrase)
175   "Encrypt the current region between START and END.
176
177 If optional argument SIGN is non-nil, do a combined sign and encrypt.
178
179 If optional PASSPHRASE is not specified, it will be obtained from the
180 passphrase cache or user."
181   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
182          (passphrase (or passphrase
183                          (when sign
184                            (pgg-read-passphrase
185                             (format "GnuPG passphrase for %s: "
186                                     pgg-gpg-user-id)
187                             pgg-gpg-user-id))))
188          (args
189           (append
190            (list "--batch" "--armor" "--always-trust" "--encrypt")
191            (if pgg-text-mode (list "--textmode"))
192            (if sign (list "--sign" "--local-user" pgg-gpg-user-id))
193            (if recipients
194                (apply #'nconc
195                       (mapcar (lambda (rcpt)
196                                 (list pgg-gpg-recipient-argument rcpt))
197                               (append recipients
198                                       (if pgg-encrypt-for-me
199                                           (list pgg-gpg-user-id)))))))))
200     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
201     (when sign
202       (with-current-buffer pgg-errors-buffer
203         ;; Possibly cache passphrase under, e.g. "jas", for future sign.
204         (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
205         ;; Possibly cache passphrase under, e.g. B565716F, for future decrypt.
206         (pgg-gpg-possibly-cache-passphrase passphrase)))
207     (pgg-process-when-success)))
208
209 (defun pgg-gpg-encrypt-symmetric-region (start end &optional passphrase)
210   "Encrypt the current region between START and END with symmetric cipher.
211
212 If optional PASSPHRASE is not specified, it will be obtained from the
213 passphrase cache or user."
214   (let* ((passphrase (or passphrase
215                          (pgg-read-passphrase
216                           "GnuPG passphrase for symmetric encryption: ")))
217          (args
218           (append (list "--batch" "--armor" "--symmetric" )
219                   (if pgg-text-mode (list "--textmode")))))
220     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
221     (pgg-process-when-success)))
222
223 (defun pgg-gpg-decrypt-region (start end &optional passphrase)
224   "Decrypt the current region between START and END.
225
226 If optional PASSPHRASE is not specified, it will be obtained from the
227 passphrase cache or user."
228   (let* ((current-buffer (current-buffer))
229          (message-keys (with-temp-buffer
230                          (insert-buffer-substring current-buffer)
231                          (pgg-decode-armor-region (point-min) (point-max))))
232          (secret-keys (pgg-gpg-lookup-all-secret-keys))
233          ;; XXX the user is stuck if they need to use the passphrase for
234          ;;     any but the first secret key for which the message is
235          ;;     encrypted.  ideally, we would incrementally give them a
236          ;;     chance with subsequent keys each time they fail with one.
237          (key (pgg-gpg-select-matching-key message-keys secret-keys))
238          (key-owner (and key (pgg-gpg-lookup-key-owner key t)))
239          (key-id (pgg-gpg-key-id-from-key-owner key-owner))
240          (pgg-gpg-user-id (or key-id key
241                               pgg-gpg-user-id pgg-default-user-id))
242          (passphrase (or passphrase
243                          (pgg-read-passphrase
244                           (format (if (pgg-gpg-symmetric-key-p message-keys)
245                                       "Passphrase for symmetric decryption: "
246                                     "GnuPG passphrase for %s: ")
247                                   (or key-owner "??"))
248                           pgg-gpg-user-id)))
249          (args '("--batch" "--decrypt")))
250     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
251     (with-current-buffer pgg-errors-buffer
252       (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
253       (goto-char (point-min))
254       (re-search-forward "^\\[GNUPG:] DECRYPTION_OKAY\\>" nil t))))
255
256 ;;;###autoload
257 (defun pgg-gpg-symmetric-key-p (message-keys)
258   "True if decoded armor MESSAGE-KEYS has symmetric encryption indicator."
259   (let (result)
260     (dolist (key message-keys result)
261       (when (and (eq (car key) 3)
262                  (member '(symmetric-key-algorithm) key))
263         (setq result key)))))
264
265 (defun pgg-gpg-select-matching-key (message-keys secret-keys)
266   "Choose a key from MESSAGE-KEYS that matches one of the keys in SECRET-KEYS."
267   (loop for message-key in message-keys
268         for message-key-id = (and (equal (car message-key) 1)
269                                   (cdr (assq 'key-identifier
270                                              (cdr message-key))))
271         for key = (and message-key-id (pgg-lookup-key message-key-id 'encrypt))
272         when (and key (member key secret-keys)) return key))
273
274 (defun pgg-gpg-sign-region (start end &optional cleartext passphrase)
275   "Make detached signature from text between START and END."
276   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
277          (passphrase (or passphrase
278                          (pgg-read-passphrase
279                           (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
280                           pgg-gpg-user-id)))
281          (args
282           (append (list (if cleartext "--clearsign" "--detach-sign")
283                         "--armor" "--batch" "--verbose"
284                         "--local-user" pgg-gpg-user-id)
285                   (if pgg-text-mode (list "--textmode"))))
286          (inhibit-read-only t)
287          buffer-read-only)
288     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
289     (with-current-buffer pgg-errors-buffer
290       ;; Possibly cache passphrase under, e.g. "jas", for future sign.
291       (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
292       ;; Possibly cache passphrase under, e.g. B565716F, for future decrypt.
293       (pgg-gpg-possibly-cache-passphrase passphrase))
294     (pgg-process-when-success)))
295
296 (defun pgg-gpg-verify-region (start end &optional signature)
297   "Verify region between START and END as the detached signature SIGNATURE."
298   (let ((args '("--batch" "--verify")))
299     (when (stringp signature)
300       (setq args (append args (list signature))))
301     (setq args (append args '("-")))
302     (pgg-gpg-process-region start end nil pgg-gpg-program args)
303     (with-current-buffer pgg-errors-buffer
304       (goto-char (point-min))
305       (while (re-search-forward "^gpg: \\(.*\\)\n" nil t)
306         (with-current-buffer pgg-output-buffer
307           (insert-buffer-substring pgg-errors-buffer
308                                    (match-beginning 1) (match-end 0)))
309         (delete-region (match-beginning 0) (match-end 0)))
310       (goto-char (point-min))
311       (re-search-forward "^\\[GNUPG:] GOODSIG\\>" nil t))))
312
313 (defun pgg-gpg-insert-key ()
314   "Insert public key at point."
315   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
316          (args (list "--batch" "--export" "--armor"
317                      pgg-gpg-user-id)))
318     (pgg-gpg-process-region (point)(point) nil pgg-gpg-program args)
319     (insert-buffer-substring pgg-output-buffer)))
320
321 (defun pgg-gpg-snarf-keys-region (start end)
322   "Add all public keys in region between START and END to the keyring."
323   (let ((args '("--import" "--batch" "-")) status)
324     (pgg-gpg-process-region start end nil pgg-gpg-program args)
325     (set-buffer pgg-errors-buffer)
326     (goto-char (point-min))
327     (when (re-search-forward "^\\[GNUPG:] IMPORT_RES\\>" nil t)
328       (setq status (buffer-substring (match-end 0)
329                                      (progn (end-of-line)(point)))
330             status (vconcat (mapcar #'string-to-number (split-string status))))
331       (erase-buffer)
332       (insert (format "Imported %d key(s).
333 \tArmor contains %d key(s) [%d bad, %d old].\n"
334                       (+ (aref status 2)
335                          (aref status 10))
336                       (aref status 0)
337                       (aref status 1)
338                       (+ (aref status 4)
339                          (aref status 11)))
340               (if (zerop (aref status 9))
341                   ""
342                 "\tSecret keys are imported.\n")))
343     (append-to-buffer pgg-output-buffer (point-min)(point-max))
344     (pgg-process-when-success)))
345
346 (provide 'pgg-gpg)
347
348 ;;; arch-tag: 2aa5d5d8-93a0-4865-9312-33e29830e000
349 ;;; pgg-gpg.el ends here