1 ;;; gpg.el --- Interface to GNU Privacy Guard
3 ;; Copyright (C) 2000 RUS-CERT, University Of Stuttgart
5 ;; Author: Florian Weimer <Florian.Weimer@RUS.Uni-Stuttgart.DE>
6 ;; Maintainer: Florian Weimer <Florian.Weimer@RUS.Uni-Stuttgart.DE>
10 ;; $Id: gpg.el,v 6.2 2000/10/31 22:16:42 zsh Exp $
12 ;; This file is NOT (yet?) part of GNU Emacs.
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
31 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
32 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
34 ;; This code is not well-tested. BE CAREFUL!
36 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
37 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
39 ;; Implemented features which can be tested:
41 ;; * Customization for all flavors of PGP is possible.
42 ;; * The main operations (verify, decrypt, sign, encrypt, sign &
43 ;; encrypt) are implemented.
44 ;; * Gero Treuner's gpg-2comp script is supported, and data which is is
45 ;; compatible with PGP 2.6.3 is generated.
47 ;; Customizing external programs
48 ;; =============================
50 ;; The customization are very similar to those of others programs,
51 ;; only the C-ish "%" constructs have been replaced by more Lisp-like
54 ;; First, you have to adjust the default executable paths
55 ;; (`gpg-command-default-alist', customization group `gpg-options',
56 ;; "Controlling GnuPG invocation."). After that, you should
57 ;; change the configuration options which control how specific
58 ;; command line flags are built (`gpg-command-flag-sign-with-key',
59 ;; (`gpg-command-flag-recipient'). The elements of these lists are
60 ;; concatenated without spaces, and a new argument is only started
61 ;; where indicated. The `gpg-command-flag-recipient' list is special:
62 ;; it consists of two parts, the first one remains at the beginning
63 ;; of the argument, the second one is repeated for each recipient.
64 ;; Finally, `gpg-command-passphrase-env' has to be changed if there's
65 ;; no command line flag to force the external program to read the data
66 ;; from standard input before the message.
68 ;; In customization group `gpg-commands', "Controlling GnuPG
69 ;; invocation.", you have to supply the actual syntax for external
70 ;; program calls. Each variable consists of a pair of a program
71 ;; specification (if a Lisp symbol is given here, it is translated
72 ;; via `gpg-command-default-alist') and a list of program arguments
73 ;; with placeholders. Please read the documentation of each variable
74 ;; before making your adjustments and try to match the given
75 ;; requirements as closely as possible!
77 ;; The `gpg-commands-key' group, "GnuPG Key Management Commands.",
78 ;; specifies key management commands. The syntax of these variables
79 ;; is like those in the `gpg-commands' group. Note that the output
80 ;; format of some of these external programs has to match very close
81 ;; that of GnuPG. Additional tools (Thomas Roessler's "pgpring.c")
82 ;; are available if your favorite implementation of OpenPGP cannot
83 ;; output the this format.
85 ;; Security considerations
86 ;; =======================
88 ;; On a typical multiuser UNIX system, the memory image of the
89 ;; Emacs process is not locked, therefore it can be swapped to disk
90 ;; at any time. As a result, the passphrase might show up in the
91 ;; swap space (even if you don't use the passphrase cache, i.e. if
92 ;; `gpg-passphrase-timeout' is 0). If someone is able to run `gdb' or
93 ;; another debugger on your Emacs process, he might be able to recover
94 ;; the passphrase as well. Unfortunately, nothing can be done in
95 ;; order to prevent this at the moment.
97 ;; BE CAREFUL: If you use the passphrase cache feature, the passphrase
98 ;; is stored in the variable `gpg-passphrase' -- and it is NOT
99 ;; encrypted in any way. (This is a conceptual problem because the
100 ;; nature of the passphrase cache requires that Emacs is able to
101 ;; decrypt automatically, so only a very weak protection could be
104 ;; In addition, if you use an unpatched Emacs 20 (and earlier
105 ;; versions), passwords show up in the output of the `view-lossage'
106 ;; function (bound to `C-h l' by default).
117 ;;; Customization: Groups:
120 "GNU Privacy Guard interface."
124 (defgroup gpg-options nil
125 "Controlling GnuPG invocation."
129 (defgroup gpg-commands nil
130 "Primary GnuPG Operations."
131 :tag "GnuPG Commands"
134 (defgroup gpg-commands-key nil
135 "Commands for GnuPG key management."
136 :tag "GnuPG Key Commands"
137 :group 'gpg-commands)
139 ;;; Customization: Widgets:
141 (define-widget 'gpg-command-alist 'alist
142 "An association list for GnuPG command names."
143 :key-type '(symbol :tag "Abbreviation")
144 :value-type '(string :tag "Program name")
145 :convert-widget 'widget-alist-convert-widget
148 (define-widget 'gpg-command-program 'choice
149 "Widget for entering the name of a program (mostly the GnuPG binary)."
151 :args '((const :tag "Default GnuPG program."
153 (const :tag "GnuPG compatibility wrapper."
155 (const :tag "Disabled"
157 (string :tag "Custom program" :format "%v")))
159 (define-widget 'gpg-command-sign-options 'cons
160 "Widget for entering signing options."
161 :args '(gpg-command-program
165 :format "%[Type%] %v"
166 (const :tag "Insert armor option here if necessary."
168 (const :tag "Insert text mode option here if necessary."
170 (const :tag "Insert the sign with key option here if necessary."
171 :value sign-with-key)
172 (string :format "%v")))))
174 (define-widget 'gpg-command-key-options 'cons
175 "Widget for entering key command options."
176 :args '(gpg-command-program
180 :format "%[Type%] %v"
181 (const :tag "Insert key ID here."
183 (string :format "%v")))))
185 ;;; Customization: Variables:
187 ;;; Customization: Variables: Paths and Flags:
189 (defcustom gpg-passphrase-timeout
191 "Timeout (in seconds) for the passphrase cache.
192 The passphrase cache is cleared after is hasn't been used for this
193 many seconds. The values 0 means that the passphrase is not cached at
195 :tag "Passphrase Timeout"
199 (defcustom gpg-default-key-id
201 "Default key/user ID used for signatures."
202 :tag "Default Key ID"
204 (const :tag "Use GnuPG default." :value nil)
208 (defcustom gpg-temp-directory
209 (expand-file-name "~/tmp")
210 "Directory for temporary files.
211 If you are running Emacs 20, this directory must have mode 0700."
212 :tag "Temp directory"
216 (defcustom gpg-command-default-alist
218 (gpg-2comp . "gpg-2comp"))
219 "Default paths for some GnuPG-related programs.
220 Modify this variable if you have to change the paths to the
221 executables required by the GnuPG interface. You can enter \"gpg\"
222 for `gpg-2comp' if you don't have this script, but you'll lose PGP
223 2.6.x compatibility."
224 :tag "GnuPG programs"
225 :type 'gpg-command-alist
228 (defcustom gpg-command-flag-textmode "--textmode"
229 "The flag to indicate canonical text mode to GnuPG."
230 :tag "Text mode flag"
234 (defcustom gpg-command-flag-armor "--armor"
235 "The flag to request ASCII-armoring output from GnuPG."
240 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
241 "String to include to specify the signing key ID.
242 The elements are concatenated (without spaces) to form a command line
244 :tag "Sign with key flag"
245 :type '(repeat :tag "Argument parts"
246 (choice :format "%[Type%] %v"
247 (const :tag "Start next argument." :value next-argument)
248 (const :tag "Insert signing key ID here." :value sign-with-key)
252 (defcustom gpg-command-flag-recipient
253 '(nil . ("-r" next-argument recipient next-argument))
254 "Format of a recipient specification.
255 The elements are concatenated (without spaces) to form a command line
256 option. The second part is repeated for each recipient."
257 :tag "Recipients Flag"
259 (repeat :tag "Common prefix"
260 (choice :format "%[Type%] %v"
261 (const :tag "Start next argument." :value next-argument)
263 (repeat :tag "For each recipient"
264 (choice :format "%[Type%] %v"
265 (const :tag "Start next argument." :value next-argument)
266 (const :tag "Insert recipient key ID here." :value recipient)
270 (defcustom gpg-command-passphrase-env
272 "Environment variable to set when a passphrase is required, or nil.
273 If an operation is invoked which requires a passphrase, this
274 environment variable is set before calling the external program to
275 indicate that it should read the passphrase from standard input."
276 :tag "Passphrase environment"
278 (const :tag "Disabled" :value nil)
280 (string :tag "Variable")
281 (string :tag "Value")))
284 ;;; Customization: Variables: GnuPG Commands:
286 (defcustom gpg-command-verify
287 '(gpg . ("--batch" "--verbose" "--verify" signature-file message-file))
288 "Command to verify a detached signature.
289 The invoked program has to read the signed message and the signature
290 from the given files. It should write human-readable information to
291 standard output and/or standard error. The program shall not convert
292 charsets or line endings; the input data shall be treated as binary."
293 :tag "Verify Command"
299 :format "%[Type%] %v"
300 (const :tag "Insert name of file containing the message here."
302 (const :tag "Insert name of file containing the signature here."
303 :value signature-file)
304 (string :format "%v"))))
305 :group 'gpg-commands)
307 (defcustom gpg-command-decrypt
308 '(gpg . ("--decrypt" "--batch" "--passphrase-fd=0"))
309 "Command to decrypt a message.
310 The invoked program has to read the passphrase from standard
311 input, followed by the encrypted message. It writes the decrypted
312 message to standard output, and human-readable diagnostic messages to
314 :tag "Decrypt Command"
320 :format "%[Type%] %v"
321 (const :tag "Insert name of file containing the message here."
323 (string :format "%v"))))
324 :group 'gpg-commands)
326 (defcustom gpg-command-sign-cleartext
327 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
328 armor textmode "--clearsign"
330 "Command to create a create a \"clearsign\" text file.
331 The invoked program has to read the passphrase from standard input,
332 followed by the message to sign. It should write the ASCII-amored
333 signed text message to standard output, and diagnostic messages to
335 :tag "Clearsign Command"
336 :type 'gpg-command-sign-options
337 :group 'gpg-commands)
339 (defcustom gpg-command-sign-detached
340 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
341 armor textmode "--detach-sign"
343 "Command to create a create a detached signature.
344 The invoked program has to read the passphrase from standard input,
345 followed by the message to sign. It should write the ASCII-amored
346 detached signature to standard output, and diagnostic messages to
347 standard error. The program shall not convert charsets or line
348 endings; the input data shall be treated as binary."
349 :tag "Sign Detached Command"
350 :type 'gpg-command-sign-options
351 :group 'gpg-commands)
353 (defcustom gpg-command-sign-encrypt
354 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
355 armor textmode "--always-trust" sign-with-key recipients
356 "--sign" "--encrypt" plaintext-file))
357 "Command to sign and encrypt a file.
358 The invoked program has to read the passphrase from standard input,
359 followed by the message to sign and encrypt if there is no
360 `plaintext-file' placeholder. It should write the ASCII-amored
361 encrypted message to standard output, and diagnostic messages to
363 :tag "Sign And Encrypt Command"
369 :format "%[Type%] %v"
370 (const :tag "Insert the `sign with key' option here if necessary."
371 :value sign-with-key)
372 (const :tag "Insert list of recipients here."
374 (const :tag "Insert here name of file with plaintext."
375 :value plaintext-file)
376 (string :format "%v"))))
377 :group 'gpg-commands)
379 (defcustom gpg-command-encrypt
380 '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust"
381 "--encrypt" recipients plaintext-file))
382 "Command to encrypt a file.
383 The invoked program has to read the message to encrypt from standard
384 input or from the plaintext file (if the `plaintext-file' placeholder
385 is present). It should write the ASCII-amored encrypted message to
386 standard output, and diagnostic messages to standard error."
392 :format "%[Type%] %v"
393 (const :tag "Insert list of recipients here."
395 (const :tag "Insert here name of file with plaintext."
396 :value plaintext-file)
397 (string :format "%v"))))
398 :group 'gpg-commands)
400 ;;; Customization: Variables: Key Management Commands:
402 (defcustom gpg-command-key-import
403 '(gpg . ("--import" "--verbose" message-file))
404 "Command to import a public key from a file."
405 :tag "Import Command"
411 :format "%[Type%] %v"
412 (const :tag "Insert name of file containing the key here."
414 (string :format "%v"))))
415 :group 'gpg-commands-key)
417 (defcustom gpg-command-key-export
418 '(gpg . ("--no-verbose" "--armor" "--export" key-id))
419 "Command to export a public key from the key ring.
420 The key should be written to standard output using ASCII armor."
421 :tag "Export Command"
422 :type 'gpg-command-key-options
423 :group 'gpg-commands-key)
425 (defcustom gpg-command-key-verify
426 '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
427 "Command to verify a public key."
428 :tag "Verification Command"
429 :type 'gpg-command-key-options
430 :group 'gpg-commands-key)
432 (defcustom gpg-command-key-public-ring
433 '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
434 "Command to list the contents of the public key ring."
435 :tag "List Public Key Ring Command"
436 :type 'gpg-command-key-options
437 :group 'gpg-commands-key)
439 (defcustom gpg-command-key-secret-ring
440 '(gpg . ("--no-verbose" "--batch" "--with-colons"
441 "--list-secret-keys" key-id))
442 "Command to list the contents of the secret key ring."
443 :tag "List Secret Key Ring Command"
444 :type 'gpg-command-key-options
445 :group 'gpg-commands-key)
447 (defcustom gpg-command-key-retrieve
448 '(gpg . ("--batch" "--recv-keys" key-id))
449 "Command to retrieve public keys."
450 :tag "Retrieve Keys Command"
451 :type 'gpg-command-key-options
452 :group 'gpg-commands-key)
455 ;;;; Helper functions for GnuPG invocation:
457 ;;; Build the GnuPG command line:
459 (defun gpg-build-argument (template substitutions &optional pass-start)
460 "Build command line argument(s) by substituting placeholders.
461 TEMPLATE is a list of strings and symbols. The placeholder symbols in
462 it are replaced by SUBSTITUTIONS, the elements between
463 `next-argument' symbols are concatenated without spaces and are
466 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
467 a string (which is inserted literally), a list of strings (which are
468 inserted as well), or nil, which means to insert nothing.
470 If PASS-START is t, `next-argument' is also inserted into the result,
471 and symbols without a proper substitution are retained in the output,
472 otherwise, an untranslated symbol results in an error.
474 This function does not handle empty arguments reliably."
475 (let ((current-arg "")
478 (let* ((templ (pop template))
479 (repl (assoc templ substitutions))
480 (new (if repl (cdr repl) templ)))
482 ((eq templ 'next-argument)
483 ;; If the current argument is not empty, start a new one.
484 (unless (equal current-arg "")
485 (setq arglist (nconc arglist
487 (list current-arg 'next-argument)
488 (list current-arg))))
489 (setq current-arg "")))
490 ((null new) nil) ; Drop it.
491 ((and (not (stringp templ)) (null repl))
492 ;; Retain an untranslated symbol in the output if
493 ;; `pass-start' is true.
495 (error "No replacement for `%s'" templ))
496 (setq arglist (nconc arglist (list current-arg templ)))
497 (setq current-arg ""))
500 (setq new (list new)))
501 (setq current-arg (concat current-arg
502 (apply 'concat new)))))))
503 (unless (equal current-arg "")
504 (setq arglist (nconc arglist (list current-arg))))
507 (defun gpg-build-arg-list (template substitutions)
508 "Build command line by substituting placeholders.
509 TEMPLATE is a list of strings and symbols. The placeholder symbols in
510 it are replaced by SUBSTITUTIONS.
512 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
513 string (which is inserted literally), a list of strings (which are
514 inserted as well), or nil, which means to insert nothing."
517 (let* ((templ (pop template))
518 (repl (assoc templ substitutions))
519 (new (if repl (cdr repl) templ)))
521 ((and (symbolp templ) (null repl))
522 (error "No replacement for `%s'" templ))
523 ((null new) nil) ; Drop it.
526 (setq new (list new)))
527 (setq arglist (nconc arglist new))))))
530 (defun gpg-build-flag-recipients-one (recipient)
531 "Build argument for one RECIPIENT."
532 (gpg-build-argument (cdr gpg-command-flag-recipient)
533 `((recipient . ,recipient)) t))
535 (defun gpg-build-flag-recipients (recipients)
536 "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
538 (apply 'append (car gpg-command-flag-recipient)
539 (mapcar 'gpg-build-flag-recipients-one
543 (defun gpg-read-recipients ()
544 "Query the user for several recipients."
548 (setq r (read-string "Enter recipient ID [RET when no more]: "))
551 (setq recipients (nconc recipients (list r)))))
554 (defun gpg-build-flag-sign-with-key (key)
555 "Build sign with key flag using `gpg-command-flag-sign-with-key'."
557 (if gpg-default-key-id gpg-default-key-id
560 (gpg-build-argument gpg-command-flag-sign-with-key
561 (list (cons 'sign-with-key k)))
564 (defmacro gpg-with-passphrase-env (&rest body)
565 "Adjust the process environment and evaluate BODY.
566 During the evaluation of the body forms, the process environment is
567 adjust according to `gpg-command-passphrase-env'."
568 (let ((env-value (make-symbol "env-value")))
572 (when gpg-command-passphrase-env
573 (setq ,env-value (getenv (car gpg-command-passphrase-env)))
574 (setenv (car gpg-command-passphrase-env)
575 (cdr gpg-command-passphrase-env)))
577 (when gpg-command-passphrase-env
578 ;; This will clear the variable if it wasn't set before.
579 (setenv (car gpg-command-passphrase-env) ,env-value))))))
583 (defun gpg-make-temp-file ()
584 "Create a temporary file in a safe way"
585 (let ((name (concat gpg-temp-directory "/gnupg")))
586 (if (fboundp 'make-temp-file)
587 ;; If we've got make-temp-file, we are on the save side.
588 (make-temp-file name)
589 ;; make-temp-name doesn't create the file, and an ordinary
590 ;; write-file operation is prone to nasty symlink attacks if the
591 ;; temporary file resides in a world-writable directory.
592 (unless (eq (file-modes gpg-temp-directory) 448) ; mode 0700
593 (error "Directory for temporary files must have mode 0700."))
594 (setq name (make-temp-name name))
595 (let ((mode (default-file-modes)))
598 (set-default-file-modes 384) ; mode 0600
599 (with-temp-file name))
600 (set-default-file-modes mode)))
603 (defvar gpg-temp-files nil
604 "List of temporary files used by the GnuPG interface.
605 Do not set this variable. Call `gpg-with-temp-files' if you need
608 (defun gpg-with-temp-files-create (count)
609 "Do not call this function. Used internally by `gpg-with-temp-files'."
611 (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
612 (setq count (1- count))))
614 (defun gpg-with-temp-files-delete ()
615 "Do not call this function. Used internally by `gpg-with-temp-files'."
616 (while gpg-temp-files
617 (let ((file (pop gpg-temp-files)))
622 (defmacro gpg-with-temp-files (count &rest body)
623 "Create COUNT temporary files, USE them, and delete them.
624 The function USE is called with the names of all temporary files as
626 `(let ((gpg-temp-files))
629 ;; Create the temporary files.
630 (gpg-with-temp-files-create ,count)
632 (gpg-with-temp-files-delete))))
634 ;;; Making subprocesses:
636 (defun gpg-exec-path (option)
637 "Return the program name for OPTION.
638 OPTION is of the form (PROGRAM . ARGLIST). This functions returns
639 PROGRAM, but takes default values into account."
640 (let* ((prg (car option))
641 (path (assq prg gpg-command-default-alist)))
643 (path (if (null (cdr path))
644 (error "Command `%s' is not available" prg)
646 ((null prg) (error "Command is disabled"))
649 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
650 "Invoke external program CMD with ARGS on buffer STDIN.
651 Standard output is insert before point in STDOUT, standard error in
652 STDERR. If PASSPHRASE is given, send it before STDIN. PASSPHRASE
653 should not end with a line feed (\"\\n\").
655 If `stdin-file' is present in ARGS, it is replaced by the name of a
656 temporary file. Before invoking CMD, the contents of STDIN is written
658 (gpg-with-temp-files 2
659 (let* ((coding-system-for-read 'no-conversion)
660 (coding-system-for-write 'no-conversion)
661 (have-stdin-file (memq 'stdin-file args))
662 (stdin-file (nth 0 gpg-temp-files))
663 (stderr-file (nth 1 gpg-temp-files))
666 (,stdout ,stderr-file)
668 ;; Replace `stdin-file'.
669 ,@(gpg-build-arg-list
670 args (list (cons 'stdin-file stdin-file)))))
672 (when have-stdin-file
673 (with-temp-file stdin-file
674 (buffer-disable-undo)
675 (insert-buffer-substring stdin)))
679 (buffer-disable-undo)
680 (insert passphrase "\n")
681 (unless have-stdin-file
682 (apply 'insert-buffer-substring
683 (if (listp stdin) stdin (list stdin))))
684 (apply 'call-process-region (point-min) (point-max) cpr-args)
685 ;; Wipe out passphrase.
686 (goto-char (point-min))
687 (translate-region (point) (line-end-position)
688 (make-string 256 ? )))
690 (with-current-buffer (car stdin)
691 (apply 'call-process-region
693 (if have-stdin-file (cadr stdin) (caddr stdin))
695 (with-current-buffer stdin
696 (apply 'call-process-region
698 (if have-stdin-file (point-min) (point-max))
700 (with-current-buffer stderr
701 (insert-file-contents-literally stderr-file))
702 (if (or (stringp res) (> res 0))
703 ;; Signal or abnormal exit.
704 (with-current-buffer stderr
705 (goto-char (point-max))
706 (insert (format "\nCommand exit status: %s\n" res))
710 (defvar gpg-result-buffer nil
711 "The result of a GnuPG operation is stored in this buffer.
712 Never set this variable directly, use `gpg-show-result' instead.")
714 (defun gpg-show-result-buffer (always-show result)
715 "Called by `gpg-show-results' to actually show the buffer."
716 (with-current-buffer gpg-result-buffer
717 ;; Only proceed if the buffer is non-empty.
718 (when (and (/= (point-min) (point-max))
719 (or always-show (not result)))
720 (save-window-excursion
721 (display-buffer (current-buffer))
722 (unless (y-or-n-p "Continue? ")
723 (error "GnuPG operation aborted."))))))
725 (defmacro gpg-show-result (always-show &rest body)
726 "Show GnuPG result to user for confirmation.
727 This macro binds `gpg-result-buffer' to a temporary buffer and
728 evaluates BODY, like `progn'. If BODY evaluates to `nil' (or
729 `always-show' is not nil), the user is asked for confirmation."
730 `(let ((gpg-result-buffer (get-buffer-create
731 (generate-new-buffer-name "*GnuPG Output*"))))
733 (gpg-show-result-buffer ,always-show (progn ,@body))
734 (kill-buffer gpg-result-buffer))))
736 ;;; Passphrase handling:
738 (defvar gpg-passphrase-timer
740 "This timer will clear the passphrase cache periodically.")
742 (defvar gpg-passphrase
744 "The (unencrypted) passphrase cache.")
746 (defun gpg-passphrase-clear-string (str)
747 "Erases STR by overwriting all characters."
755 (defun gpg-passphrase-forget ()
756 "Forget stored passphrase."
758 (cancel-timer gpg-passphrase-timer)
759 (gpg-passphrase-clear-string gpg-passphrase)
760 (setq gpg-passphrase nil))
762 (defun gpg-passphrase-store (passphrase)
763 "Store PASSPHRASE in cache.
764 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
765 (unless (equal gpg-passphrase-timeout 0)
766 (timer-set-time gpg-passphrase-timer
767 (timer-relative-time (current-time)
768 gpg-passphrase-timeout))
769 (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
770 (timer-activate gpg-passphrase-timer)
771 (setq gpg-passphrase passphrase))
774 (defun gpg-passphrase-read ()
775 "Read a passphrase and remember it for some time."
778 ;; This reinitializes the timer.
779 (gpg-passphrase-store gpg-passphrase)
780 (let ((pp (read-passwd "Enter passphrase: ")))
781 (gpg-passphrase-store pp))))
784 ;;;; Main operations:
787 (defun gpg-verify (message signature result)
788 "Verify buffer MESSAGE against detached SIGNATURE buffer.
789 Returns t if everything worked out well, nil otherwise. Consult
790 buffer RESULT for details."
791 (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
792 (gpg-with-temp-files 2
793 (let* ((sig-file (nth 0 gpg-temp-files))
794 (msg-file (nth 1 gpg-temp-files))
795 (cmd (gpg-exec-path gpg-command-verify))
796 (args (gpg-build-arg-list (cdr gpg-command-verify)
797 `((signature-file . ,sig-file)
798 (message-file . ,msg-file))))
800 (with-temp-file sig-file
801 (buffer-disable-undo)
802 (apply 'insert-buffer-substring (if (listp signature)
805 (with-temp-file msg-file
806 (buffer-disable-undo)
807 (apply 'insert-buffer-substring (if (listp message)
810 (setq res (apply 'call-process-region
811 (point-min) (point-min) ; no data
817 (if (or (stringp res) (> res 0))
818 ;; Signal or abnormal exit.
819 (with-current-buffer result
820 (insert (format "\nCommand exit status: %s\n" res))
825 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
826 "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
827 Returns t if everything worked out well, nil otherwise. Consult
828 buffer RESULT for details. Reads a missing PASSPHRASE using
829 `gpg-passphrase-read'."
830 (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
831 (gpg-call-process (gpg-exec-path gpg-command-decrypt)
832 (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
833 ciphertext plaintext result
834 (if passphrase passphrase (gpg-passphrase-read)))
836 (gpg-passphrase-clear-string passphrase)))
839 (defun gpg-sign-cleartext
840 (plaintext signed-text result &optional passphrase sign-with-key)
841 "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
843 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
844 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
845 everything worked out well, nil otherwise. Consult buffer RESULT for
848 NOTE: Use of this function is deprecated."
849 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
850 (let ((subst (list (cons 'sign-with-key
851 (gpg-build-flag-sign-with-key sign-with-key))
852 (cons 'armor gpg-command-flag-armor)
853 (cons 'textmode gpg-command-flag-textmode))))
854 (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
855 (gpg-build-arg-list (cdr gpg-command-sign-cleartext)
857 plaintext signed-text result
858 (if passphrase passphrase (gpg-passphrase-read))))
860 (gpg-passphrase-clear-string passphrase)))
863 (defun gpg-sign-detached
864 (plaintext signature result &optional passphrase sign-with-key
866 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
867 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
868 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
869 everything worked out well, nil otherwise. Consult buffer RESULT for
870 details. ARMOR the result and activate canonical TEXTMODE if
872 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
873 (let ((subst (list (cons 'sign-with-key
874 (gpg-build-flag-sign-with-key sign-with-key))
875 (cons 'armor (if armor gpg-command-flag-armor))
876 (cons 'textmode (if armor gpg-command-flag-textmode)))))
877 (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
878 (gpg-build-arg-list (cdr gpg-command-sign-detached)
880 plaintext signature result
881 (if passphrase passphrase (gpg-passphrase-read))))
883 (gpg-passphrase-clear-string passphrase)))
887 (defun gpg-sign-encrypt
888 (plaintext ciphertext result recipients &optional passphrase sign-with-key
890 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
891 RECIPIENTS is a list of key IDs used for encryption. This function
892 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
893 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
894 ID. Returns t if everything worked out well, nil otherwise. Consult
895 buffer RESULT for details. ARMOR the result and activate canonical
896 TEXTMODE if requested."
898 (read-buffer "Buffer containing plaintext: " nil t)
899 (read-buffer "Buffer for ciphertext: " nil t)
900 (read-buffer "Buffer for status informationt: " nil t)
901 (gpg-read-recipients)))
902 (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key
904 (plaintext-file . stdin-file)
905 (recipients . ,(gpg-build-flag-recipients recipients))
906 (armor ,(if armor gpg-command-flag-armor))
907 (textmode ,(if armor gpg-command-flag-textmode)))))
908 (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
909 (gpg-build-arg-list (cdr gpg-command-sign-encrypt)
911 plaintext ciphertext result
912 (if passphrase passphrase (gpg-passphrase-read))))
914 (gpg-passphrase-clear-string passphrase)))
919 (plaintext ciphertext result recipients &optional passphrase armor textmode)
920 "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
921 RECIPIENTS is a list of key IDs used for encryption. Returns t if
922 everything worked out well, nil otherwise. Consult buffer RESULT for
923 details. ARMOR the result and activate canonical
924 TEXTMODE if requested."
926 (read-buffer "Buffer containing plaintext: " nil t)
927 (read-buffer "Buffer for ciphertext: " nil t)
928 (read-buffer "Buffer for status informationt: " nil t)
929 (gpg-read-recipients)))
930 (let ((subst `((plaintext-file . stdin-file)
931 (recipients . ,(gpg-build-flag-recipients recipients))
932 (armor ,(if armor gpg-command-flag-armor))
933 (textmode ,(if armor gpg-command-flag-textmode)))))
934 (gpg-call-process (gpg-exec-path gpg-command-encrypt)
935 (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
936 plaintext ciphertext result nil))
938 (gpg-passphrase-clear-string passphrase)))
945 (defun gpg-key-make (user-id key-id unique-id length algorithm
946 creation-date expire-date validity trust)
947 "Create a new key object (for internal use only)."
950 user-id key-id unique-id length algorithm
952 creation-date expire-date validity trust))
955 (defun gpg-key-p (key)
956 "Return t if KEY is a key specification."
957 (and (arrayp key) (equal (length key) 9) key))
959 (defmacro gpg-key-primary-user-id (key)
960 "The primary user ID for KEY (human-readable).
961 DO NOT USE this ID for selecting recipients. It is probably not
963 (list 'car (list 'aref key 0)))
965 (defmacro gpg-key-user-ids (key)
966 "A list of additional user IDs for KEY (human-readable).
967 DO NOT USE these IDs for selecting recipients. They are probably not
969 (list 'cdr (list 'aref key 0)))
971 (defmacro gpg-key-id (key)
973 DO NOT USE this ID for selecting recipients. It is not guaranteed to
977 (defun gpg-short-key-id (key)
978 "The short key ID of KEY."
979 (let* ((id (gpg-key-id key))
982 (substring id (- len 8))
985 (defmacro gpg-key-unique-id (key)
986 "A non-standard ID of KEY which is only valid locally.
987 This ID can be used to specify recipients in a safe manner. Note,
988 even this ID might not be unique unless GnuPG is used."
991 (defmacro gpg-key-unique-id-list (key-list)
992 "Like `gpg-key-unique-id', but operate on a list."
993 `(mapcar (lambda (key) (gpg-key-unique-id key))
996 (defmacro gpg-key-length (key)
997 "Returns the key length."
1000 (defmacro gpg-key-algorithm (key)
1001 "The encryption algorithm used by KEY.
1002 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1003 `elgamal-encrypt', `dsa'."
1006 (defmacro gpg-key-creation-date (key)
1007 "A string with the creation date of KEY in ISO format."
1010 (defmacro gpg-key-expire-date (key)
1011 "A string with the expiration date of KEY in ISO format."
1014 (defmacro gpg-key-validity (key)
1015 "The calculated validity of KEY.
1016 One of the symbols `not-known', `disabled', `revoked', `expired',
1017 `undefined', `trust-none', `trust-marginal', `trust-full',
1018 `trust-ultimate' (see the GnuPG documentation for details)."
1021 (defmacro gpg-key-trust (key)
1022 "The assigned trust for KEY.
1023 One of the symbols `not-known', `undefined', `trust-none',
1024 `trust-marginal', `trust-full' (see the GnuPG
1025 documentation for details)."
1028 (defun gpg-key-lessp (a b)
1029 "Returns t if primary user ID of A is less than B."
1030 (let ((res (compare-strings (gpg-key-primary-user-id a) 0 nil
1031 (gpg-key-primary-user-id b) 0 nil
1037 ;;; Accessing the key database:
1039 ;; Internal functions:
1041 (defmacro gpg-key-list-keys-skip-field ()
1042 '(search-forward ":" eol 'move))
1044 (defmacro gpg-key-list-keys-get-field ()
1045 '(buffer-substring (point) (if (gpg-key-list-keys-skip-field)
1048 (defmacro gpg-key-list-keys-string-field ()
1049 '(gpg-key-list-keys-get-field))
1051 (defmacro gpg-key-list-keys-read-field ()
1052 (let ((field (make-symbol "field")))
1053 `(let ((,field (gpg-key-list-keys-get-field)))
1054 (if (equal (length ,field) 0)
1058 (defun gpg-key-list-keys-parse-line ()
1059 "Parse the line in the current buffer and return a vector of fields."
1060 (let* ((eol (line-end-position))
1064 (gpg-key-list-keys-read-field) ; type
1065 (gpg-key-list-keys-get-field) ; trust
1066 (gpg-key-list-keys-read-field) ; key length
1067 (gpg-key-list-keys-read-field) ; algorithm
1068 (gpg-key-list-keys-get-field) ; key ID
1069 (gpg-key-list-keys-get-field) ; creation data
1070 (gpg-key-list-keys-get-field) ; expire
1071 (gpg-key-list-keys-get-field) ; unique (local) ID
1072 (gpg-key-list-keys-get-field) ; ownertrust
1073 (gpg-key-list-keys-string-field) ; user ID
1078 (error "Too many fields in GnuPG key database"))
1081 (defconst gpg-pubkey-algo-alist
1083 (2 . rsa-encrypt-only)
1085 (16 . elgamal-encrypt-only)
1088 "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1090 (defconst gpg-trust-alist
1096 (?q . trust-undefined)
1098 (?m . trust-marginal)
1100 (?u . trust-ultimate))
1101 "Alist mapping GnuPG trust value short forms to long symbols.")
1103 (defmacro gpg-key-list-keys-in-buffer-store ()
1104 '(when primary-user-id
1105 (sort user-id 'string-lessp)
1106 (push (gpg-key-make (cons primary-user-id user-id)
1107 key-id unique-id key-length
1108 algorithm creation-date
1109 expire-date validity trust)
1112 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1113 "Return a list of keys for BUFFER.
1114 If BUFFER is omitted, use current buffer."
1115 (with-current-buffer (if buffer buffer (current-buffer))
1116 (goto-char (point-min))
1117 ;; Skip key ring filename written by GnuPG.
1118 (search-forward "\n---------------------------\n" nil t)
1119 ;; Loop over all lines in buffer and analyze them.
1120 (let (primary-user-id user-id key-id unique-id ; current key components
1121 key-length algorithm creation-date expire-date validity trust
1122 line ; fields in current line
1123 key-list) ; keys gather so far
1125 (while (setq line (gpg-key-list-keys-parse-line))
1127 ;; Public or secret key.
1128 ((memq (aref line 0) '(pub sec))
1129 ;; Store previous key, if any.
1130 (gpg-key-list-keys-in-buffer-store)
1131 ;; Record field values.
1132 (setq primary-user-id (aref line 9))
1134 (setq key-id (aref line 4))
1135 ;; We use the key ID if no unique ID is available.
1136 (setq unique-id (if (> (length (aref line 7)) 0)
1137 (concat "#" (aref line 7))
1138 (concat "0x" key-id)))
1139 (setq key-length (aref line 2))
1140 (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1142 (setq algorithm (cdr algorithm))
1143 (error "Unknown algorithm %s" (aref line 3)))
1144 (setq creation-date (if (> (length (aref line 5)) 0)
1146 (setq expire-date (if (> (length (aref line 6)) 0)
1148 (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1150 (setq validity (cdr validity))
1151 (error "Unknown validity specification %S" (aref line 1)))
1152 (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1154 (setq trust (cdr trust))
1155 (error "Unknown trust specification %S" (aref line 8))))
1157 ;; Additional user ID
1158 ((eq 'uid (aref line 0))
1159 (setq user-id (cons (aref line 9) user-id)))
1161 ;; Subkeys are ignored for now.
1162 ((memq (aref line 0) '(sub ssb))
1164 (t (error "Unknown record type %S" (aref line 0)))))
1166 ;; Store the key retrieved last.
1167 (gpg-key-list-keys-in-buffer-store)
1168 ;; Sort the keys according to the primary user ID.
1169 (sort key-list 'gpg-key-lessp))))
1171 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1172 "Insert the output of COMMAND before point in current buffer."
1173 (let* ((cmd (gpg-exec-path command))
1174 (key (if (equal keyspec "") nil keyspec))
1175 (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1178 (apply 'call-process-region
1179 (point-min) (point-min) ; no data
1182 (if stderr t '(t nil))
1185 (unless (or ignore-error (equal exit-status 0))
1186 (error "GnuPG command exited unsuccessfully"))))
1189 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1190 "Return a list of keys matching KEYSPEC.
1191 COMMAND is used to obtain the key list. The usual substring search
1192 for keys is performed."
1194 (buffer-disable-undo)
1195 (gpg-key-list-keyspec command keyspec)
1196 (gpg-key-list-keys-in-buffer)))
1199 (defun gpg-key-list-keys (&optional keyspec)
1200 "A list of public keys matching KEYSPEC.
1201 The usual substring search for keys is performed."
1202 (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1205 (defun gpg-key-list-secret-keys (&optional keyspec)
1206 "A list of secret keys matching KEYSPEC.
1207 The usual substring search for keys is performed."
1208 (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1211 (defun gpg-key-insert-public-key (key)
1212 "Inserts the public key(s) matching KEYSPEC.
1213 The ASCII-armored key is inserted before point into current buffer."
1214 (gpg-key-list-keyspec gpg-command-key-export key))
1217 (defun gpg-key-insert-information (key)
1218 "Insert human-readable information (including fingerprint) on KEY.
1219 Insertion takes place in current buffer before point."
1220 (gpg-key-list-keyspec gpg-command-key-verify key))
1223 (defun gpg-key-retrieve (key)
1224 "Fetch KEY from default key server.
1225 KEY is a key ID or a list of key IDs. Status information about this
1226 operation is inserted into the current buffer before point."
1227 (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1230 (defun gpg-key-add-to-ring (key result)
1231 "Adds key in buffer KEY to the GnuPG key ring.
1232 Human-readable information on the RESULT is stored in buffer RESULT
1237 ;;; gpg.el ends here