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 ;; This file is NOT (yet?) part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
30 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
32 ;; This code is not well-tested. BE CAREFUL!
34 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
35 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
37 ;; Implemented features which can be tested:
39 ;; * Customization for all flavors of PGP is possible.
40 ;; * The main operations (verify, decrypt, sign, encrypt, sign &
41 ;; encrypt) are implemented.
42 ;; * Gero Treuner's gpg-2comp script is supported, and data which is is
43 ;; compatible with PGP 2.6.3 is generated.
45 ;; Customizing external programs
46 ;; =============================
48 ;; The customization are very similar to those of others programs,
49 ;; only the C-ish "%" constructs have been replaced by more Lisp-like
52 ;; First, you have to adjust the default executable paths
53 ;; (`gpg-command-default-alist', customization group `gpg-options',
54 ;; "Controlling GnuPG invocation."). After that, you should
55 ;; change the configuration options which control how specific
56 ;; command line flags are built (`gpg-command-flag-sign-with-key',
57 ;; (`gpg-command-flag-recipient'). The elements of these lists are
58 ;; concatenated without spaces, and a new argument is only started
59 ;; where indicated. The `gpg-command-flag-recipient' list is special:
60 ;; it consists of two parts, the first one remains at the beginning
61 ;; of the argument, the second one is repeated for each recipient.
62 ;; Finally, `gpg-command-passphrase-env' has to be changed if there's
63 ;; no command line flag to force the external program to read the data
64 ;; from standard input before the message.
66 ;; In customization group `gpg-commands', "Controlling GnuPG
67 ;; invocation.", you have to supply the actual syntax for external
68 ;; program calls. Each variable consists of a pair of a program
69 ;; specification (if a Lisp symbol is given here, it is translated
70 ;; via `gpg-command-default-alist') and a list of program arguments
71 ;; with placeholders. Please read the documentation of each variable
72 ;; before making your adjustments and try to match the given
73 ;; requirements as closely as possible!
75 ;; The `gpg-commands-key' group, "GnuPG Key Management Commands.",
76 ;; specifies key management commands. The syntax of these variables
77 ;; is like those in the `gpg-commands' group. Note that the output
78 ;; format of some of these external programs has to match very close
79 ;; that of GnuPG. Additional tools (Thomas Roessler's "pgpring.c")
80 ;; are available if your favorite implementation of OpenPGP cannot
81 ;; output the this format.
83 ;; Security considerations
84 ;; =======================
86 ;; On a typical multiuser UNIX system, the memory image of the
87 ;; Emacs process is not locked, therefore it can be swapped to disk
88 ;; at any time. As a result, the passphrase might show up in the
89 ;; swap space (even if you don't use the passphrase cache, i.e. if
90 ;; `gpg-passphrase-timeout' is 0). If someone is able to run `gdb' or
91 ;; another debugger on your Emacs process, he might be able to recover
92 ;; the passphrase as well. Unfortunately, nothing can be done in
93 ;; order to prevent this at the moment.
95 ;; BE CAREFUL: If you use the passphrase cache feature, the passphrase
96 ;; is stored in the variable `gpg-passphrase' -- and it is NOT
97 ;; encrypted in any way. (This is a conceptual problem because the
98 ;; nature of the passphrase cache requires that Emacs is able to
99 ;; decrypt automatically, so only a very weak protection could be
102 ;; In addition, if you use an unpatched Emacs 20 (and earlier
103 ;; versions), passwords show up in the output of the `view-lossage'
104 ;; function (bound to `C-h l' by default).
113 (defalias 'gpg-point-at-eol
114 (if (fboundp 'point-at-eol)
120 ;;; Customization: Groups:
123 "GNU Privacy Guard interface."
127 (defgroup gpg-options nil
128 "Controlling GnuPG invocation."
132 (defgroup gpg-commands nil
133 "Primary GnuPG Operations."
134 :tag "GnuPG Commands"
137 (defgroup gpg-commands-key nil
138 "Commands for GnuPG key management."
139 :tag "GnuPG Key Commands"
140 :group 'gpg-commands)
142 ;;; Customization: Widgets:
144 (if (get 'alist 'widget-type)
145 (define-widget 'gpg-command-alist 'alist
146 "An association list for GnuPG command names."
147 :key-type '(symbol :tag "Abbreviation")
148 :value-type '(string :tag "Program name")
149 :convert-widget 'widget-alist-convert-widget
151 (define-widget 'gpg-command-alist 'repeat
152 "An association list for GnuPG command names."
153 :args '((cons :format "%v"
154 (symbol :tag "Abbreviation")
155 (string :tag "Program name")))
158 (define-widget 'gpg-command-program 'choice
159 "Widget for entering the name of a program (mostly the GnuPG binary)."
161 :args '((const :tag "Default GnuPG program."
163 (const :tag "GnuPG compatibility wrapper."
165 (const :tag "Disabled"
167 (string :tag "Custom program" :format "%v")))
169 (define-widget 'gpg-command-sign-options 'cons
170 "Widget for entering signing options."
171 :args '(gpg-command-program
175 :format "%[Type%] %v"
176 (const :tag "Insert armor option here if necessary."
178 (const :tag "Insert text mode option here if necessary."
180 (const :tag "Insert the sign with key option here if necessary."
181 :value sign-with-key)
182 (string :format "%v")))))
184 (define-widget 'gpg-command-key-options 'cons
185 "Widget for entering key command options."
186 :args '(gpg-command-program
190 :format "%[Type%] %v"
191 (const :tag "Insert key ID here."
193 (string :format "%v")))))
195 ;;; Customization: Variables:
197 ;;; Customization: Variables: Paths and Flags:
199 (defcustom gpg-passphrase-timeout
201 "Timeout (in seconds) for the passphrase cache.
202 The passphrase cache is cleared after is hasn't been used for this
203 many seconds. The values 0 means that the passphrase is not cached at
205 :tag "Passphrase Timeout"
209 (defcustom gpg-default-key-id
211 "Default key/user ID used for signatures."
212 :tag "Default Key ID"
214 (const :tag "Use GnuPG default." :value nil)
218 (defcustom gpg-temp-directory
219 (expand-file-name "~/tmp")
220 "Directory for temporary files.
221 If you are running Emacs 20, this directory must have mode 0700."
222 :tag "Temp directory"
226 (defcustom gpg-command-default-alist
228 (gpg-2comp . "gpg-2comp"))
229 "Default paths for some GnuPG-related programs.
230 Modify this variable if you have to change the paths to the
231 executables required by the GnuPG interface. You can enter \"gpg\"
232 for `gpg-2comp' if you don't have this script, but you'll lose PGP
233 2.6.x compatibility."
234 :tag "GnuPG programs"
235 :type 'gpg-command-alist
238 (defcustom gpg-command-flag-textmode "--textmode"
239 "The flag to indicate canonical text mode to GnuPG."
240 :tag "Text mode flag"
244 (defcustom gpg-command-flag-armor "--armor"
245 "The flag to request ASCII-armoring output from GnuPG."
250 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
251 "String to include to specify the signing key ID.
252 The elements are concatenated (without spaces) to form a command line
254 :tag "Sign with key flag"
255 :type '(repeat :tag "Argument parts"
256 (choice :format "%[Type%] %v"
257 (const :tag "Start next argument." :value next-argument)
258 (const :tag "Insert signing key ID here." :value sign-with-key)
262 (defcustom gpg-command-flag-recipient
263 '(nil . ("-r" next-argument recipient next-argument))
264 "Format of a recipient specification.
265 The elements are concatenated (without spaces) to form a command line
266 option. The second part is repeated for each recipient."
267 :tag "Recipients Flag"
269 (repeat :tag "Common prefix"
270 (choice :format "%[Type%] %v"
271 (const :tag "Start next argument." :value next-argument)
273 (repeat :tag "For each recipient"
274 (choice :format "%[Type%] %v"
275 (const :tag "Start next argument." :value next-argument)
276 (const :tag "Insert recipient key ID here." :value recipient)
280 (defcustom gpg-command-passphrase-env
282 "Environment variable to set when a passphrase is required, or nil.
283 If an operation is invoked which requires a passphrase, this
284 environment variable is set before calling the external program to
285 indicate that it should read the passphrase from standard input."
286 :tag "Passphrase environment"
288 (const :tag "Disabled" :value nil)
290 (string :tag "Variable")
291 (string :tag "Value")))
294 ;;; Customization: Variables: GnuPG Commands:
296 (defcustom gpg-command-verify
297 '(gpg . ("--batch" "--verbose" "--verify" signature-file message-file))
298 "Command to verify a detached signature.
299 The invoked program has to read the signed message and the signature
300 from the given files. It should write human-readable information to
301 standard output and/or standard error. The program shall not convert
302 charsets or line endings; the input data shall be treated as binary."
303 :tag "Verify Command"
309 :format "%[Type%] %v"
310 (const :tag "Insert name of file containing the message here."
312 (const :tag "Insert name of file containing the signature here."
313 :value signature-file)
314 (string :format "%v"))))
315 :group 'gpg-commands)
317 (defcustom gpg-command-verify-cleartext
318 '(gpg . ("--batch" "--verbose" "--verify" message-file))
319 "Command to verify a message.
320 The invoked program has to read the signed message from the given
321 file. It should write human-readable information to standard output
322 and/or standard error. The program shall not convert charsets or line
323 endings; the input data shall be treated as binary."
324 :tag "Cleartext Verify Command"
330 :format "%[Type%] %v"
331 (const :tag "Insert name of file containing the message here."
333 (string :format "%v"))))
334 :group 'gpg-commands)
336 (defcustom gpg-command-decrypt
337 '(gpg . ("--decrypt" "--batch" "--passphrase-fd=0"))
338 "Command to decrypt a message.
339 The invoked program has to read the passphrase from standard
340 input, followed by the encrypted message. It writes the decrypted
341 message to standard output, and human-readable diagnostic messages to
343 :tag "Decrypt Command"
349 :format "%[Type%] %v"
350 (const :tag "Insert name of file containing the message here."
352 (string :format "%v"))))
353 :group 'gpg-commands)
355 (defcustom gpg-command-sign-cleartext
356 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
357 armor textmode "--clearsign"
359 "Command to create a create a \"clearsign\" text file.
360 The invoked program has to read the passphrase from standard input,
361 followed by the message to sign. It should write the ASCII-amored
362 signed text message to standard output, and diagnostic messages to
364 :tag "Clearsign Command"
365 :type 'gpg-command-sign-options
366 :group 'gpg-commands)
368 (defcustom gpg-command-sign-detached
369 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
370 armor textmode "--detach-sign"
372 "Command to create a create a detached signature.
373 The invoked program has to read the passphrase from standard input,
374 followed by the message to sign. It should write the ASCII-amored
375 detached signature to standard output, and diagnostic messages to
376 standard error. The program shall not convert charsets or line
377 endings; the input data shall be treated as binary."
378 :tag "Sign Detached Command"
379 :type 'gpg-command-sign-options
380 :group 'gpg-commands)
382 (defcustom gpg-command-sign-encrypt
383 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
384 armor textmode "--always-trust" sign-with-key recipients
385 "--sign" "--encrypt" plaintext-file))
386 "Command to sign and encrypt a file.
387 The invoked program has to read the passphrase from standard input,
388 followed by the message to sign and encrypt if there is no
389 `plaintext-file' placeholder. It should write the ASCII-amored
390 encrypted message to standard output, and diagnostic messages to
392 :tag "Sign And Encrypt Command"
398 :format "%[Type%] %v"
399 (const :tag "Insert the `sign with key' option here if necessary."
400 :value sign-with-key)
401 (const :tag "Insert list of recipients here."
403 (const :tag "Insert here name of file with plaintext."
404 :value plaintext-file)
405 (string :format "%v"))))
406 :group 'gpg-commands)
408 (defcustom gpg-command-encrypt
409 '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust"
410 "--encrypt" recipients plaintext-file))
411 "Command to encrypt a file.
412 The invoked program has to read the message to encrypt from standard
413 input or from the plaintext file (if the `plaintext-file' placeholder
414 is present). It should write the ASCII-amored encrypted message to
415 standard output, and diagnostic messages to standard error."
421 :format "%[Type%] %v"
422 (const :tag "Insert list of recipients here."
424 (const :tag "Insert here name of file with plaintext."
425 :value plaintext-file)
426 (string :format "%v"))))
427 :group 'gpg-commands)
429 ;;; Customization: Variables: Key Management Commands:
431 (defcustom gpg-command-key-import
432 '(gpg . ("--import" "--verbose" message-file))
433 "Command to import a public key from a file."
434 :tag "Import Command"
440 :format "%[Type%] %v"
441 (const :tag "Insert name of file containing the key here."
443 (string :format "%v"))))
444 :group 'gpg-commands-key)
446 (defcustom gpg-command-key-export
447 '(gpg . ("--no-verbose" "--armor" "--export" key-id))
448 "Command to export a public key from the key ring.
449 The key should be written to standard output using ASCII armor."
450 :tag "Export Command"
451 :type 'gpg-command-key-options
452 :group 'gpg-commands-key)
454 (defcustom gpg-command-key-verify
455 '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
456 "Command to verify a public key."
457 :tag "Verification Command"
458 :type 'gpg-command-key-options
459 :group 'gpg-commands-key)
461 (defcustom gpg-command-key-public-ring
462 '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
463 "Command to list the contents of the public key ring."
464 :tag "List Public Key Ring Command"
465 :type 'gpg-command-key-options
466 :group 'gpg-commands-key)
468 (defcustom gpg-command-key-secret-ring
469 '(gpg . ("--no-verbose" "--batch" "--with-colons"
470 "--list-secret-keys" key-id))
471 "Command to list the contents of the secret key ring."
472 :tag "List Secret Key Ring Command"
473 :type 'gpg-command-key-options
474 :group 'gpg-commands-key)
476 (defcustom gpg-command-key-retrieve
477 '(gpg . ("--batch" "--recv-keys" key-id))
478 "Command to retrieve public keys."
479 :tag "Retrieve Keys Command"
480 :type 'gpg-command-key-options
481 :group 'gpg-commands-key)
484 ;;;; Helper functions for GnuPG invocation:
486 ;;; Build the GnuPG command line:
488 (defun gpg-build-argument (template substitutions &optional pass-start)
489 "Build command line argument(s) by substituting placeholders.
490 TEMPLATE is a list of strings and symbols. The placeholder symbols in
491 it are replaced by SUBSTITUTIONS, the elements between
492 `next-argument' symbols are concatenated without spaces and are
495 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
496 a string (which is inserted literally), a list of strings (which are
497 inserted as well), or nil, which means to insert nothing.
499 If PASS-START is t, `next-argument' is also inserted into the result,
500 and symbols without a proper substitution are retained in the output,
501 otherwise, an untranslated symbol results in an error.
503 This function does not handle empty arguments reliably."
504 (let ((current-arg "")
507 (let* ((templ (pop template))
508 (repl (assoc templ substitutions))
509 (new (if repl (cdr repl) templ)))
511 ((eq templ 'next-argument)
512 ;; If the current argument is not empty, start a new one.
513 (unless (equal current-arg "")
514 (setq arglist (nconc arglist
516 (list current-arg 'next-argument)
517 (list current-arg))))
518 (setq current-arg "")))
519 ((null new) nil) ; Drop it.
520 ((and (not (stringp templ)) (null repl))
521 ;; Retain an untranslated symbol in the output if
522 ;; `pass-start' is true.
524 (error "No replacement for `%s'" templ))
525 (setq arglist (nconc arglist (list current-arg templ)))
526 (setq current-arg ""))
529 (setq new (list new)))
530 (setq current-arg (concat current-arg
531 (apply 'concat new)))))))
532 (unless (equal current-arg "")
533 (setq arglist (nconc arglist (list current-arg))))
536 (defun gpg-build-arg-list (template substitutions)
537 "Build command line by substituting placeholders.
538 TEMPLATE is a list of strings and symbols. The placeholder symbols in
539 it are replaced by SUBSTITUTIONS.
541 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
542 string (which is inserted literally), a list of strings (which are
543 inserted as well), or nil, which means to insert nothing."
546 (let* ((templ (pop template))
547 (repl (assoc templ substitutions))
548 (new (if repl (cdr repl) templ)))
550 ((and (symbolp templ) (null repl))
551 (error "No replacement for `%s'" templ))
552 ((null new) nil) ; Drop it.
555 (setq new (list new)))
556 (setq arglist (nconc arglist new))))))
559 (defun gpg-build-flag-recipients-one (recipient)
560 "Build argument for one RECIPIENT."
561 (gpg-build-argument (cdr gpg-command-flag-recipient)
562 `((recipient . ,recipient)) t))
564 (defun gpg-build-flag-recipients (recipients)
565 "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
567 (apply 'append (car gpg-command-flag-recipient)
568 (mapcar 'gpg-build-flag-recipients-one
572 (defun gpg-read-recipients ()
573 "Query the user for several recipients."
577 (setq r (read-string "Enter recipient ID [RET when no more]: "))
580 (setq recipients (nconc recipients (list r)))))
583 (defun gpg-build-flag-sign-with-key (key)
584 "Build sign with key flag using `gpg-command-flag-sign-with-key'."
586 (if gpg-default-key-id gpg-default-key-id
589 (gpg-build-argument gpg-command-flag-sign-with-key
590 (list (cons 'sign-with-key k)))
593 (defmacro gpg-with-passphrase-env (&rest body)
594 "Adjust the process environment and evaluate BODY.
595 During the evaluation of the body forms, the process environment is
596 adjust according to `gpg-command-passphrase-env'."
597 (let ((env-value (make-symbol "env-value")))
601 (when gpg-command-passphrase-env
602 (setq ,env-value (getenv (car gpg-command-passphrase-env)))
603 (setenv (car gpg-command-passphrase-env)
604 (cdr gpg-command-passphrase-env)))
606 (when gpg-command-passphrase-env
607 ;; This will clear the variable if it wasn't set before.
608 (setenv (car gpg-command-passphrase-env) ,env-value))))))
609 (put 'gpg-with-passphrase-env 'lisp-indent-function 0)
610 (put 'gpg-with-passphrase-env 'edebug-form-spec '(body))
614 (defun gpg-make-temp-file ()
615 "Create a temporary file in a safe way"
616 (let ((name ;; User may use "~/"
617 (expand-file-name "gnupg" gpg-temp-directory)))
618 (if (fboundp 'make-temp-file)
619 ;; If we've got make-temp-file, we are on the save side.
620 (make-temp-file name)
621 ;; make-temp-name doesn't create the file, and an ordinary
622 ;; write-file operation is prone to nasty symlink attacks if the
623 ;; temporary file resides in a world-writable directory.
624 (unless (or (memq system-type '(windows-nt cygwin32 win32 w32 mswindows))
625 (eq (file-modes gpg-temp-directory) 448)) ; mode 0700
626 (error "Directory for temporary files must have mode 0700."))
627 (setq name (make-temp-name name))
628 (let ((mode (default-file-modes)))
631 (set-default-file-modes 384) ; mode 0600
632 (with-temp-file name))
633 (set-default-file-modes mode)))
636 (defvar gpg-temp-files nil
637 "List of temporary files used by the GnuPG interface.
638 Do not set this variable. Call `gpg-with-temp-files' if you need
641 (defun gpg-with-temp-files-create (count)
642 "Do not call this function. Used internally by `gpg-with-temp-files'."
644 (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
645 (setq count (1- count))))
647 (defun gpg-with-temp-files-delete ()
648 "Do not call this function. Used internally by `gpg-with-temp-files'."
649 (while gpg-temp-files
650 (let ((file (pop gpg-temp-files)))
655 (defmacro gpg-with-temp-files (count &rest body)
656 "Create COUNT temporary files, USE them, and delete them.
657 The function USE is called with the names of all temporary files as
659 `(let ((gpg-temp-files))
662 ;; Create the temporary files.
663 (gpg-with-temp-files-create ,count)
665 (gpg-with-temp-files-delete))))
666 (put 'gpg-with-temp-files 'lisp-indent-function 1)
667 (put 'gpg-with-temp-files 'edebug-form-spec '(body))
669 ;;; Making subprocesses:
671 (defun gpg-exec-path (option)
672 "Return the program name for OPTION.
673 OPTION is of the form (PROGRAM . ARGLIST). This functions returns
674 PROGRAM, but takes default values into account."
675 (let* ((prg (car option))
676 (path (assq prg gpg-command-default-alist)))
678 (path (if (null (cdr path))
679 (error "Command `%s' is not available" prg)
681 ((null prg) (error "Command is disabled"))
684 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
685 "Invoke external program CMD with ARGS on buffer STDIN.
686 Standard output is insert before point in STDOUT, standard error in
687 STDERR. If PASSPHRASE is given, send it before STDIN. PASSPHRASE
688 should not end with a line feed (\"\\n\").
690 If `stdin-file' is present in ARGS, it is replaced by the name of a
691 temporary file. Before invoking CMD, the contents of STDIN is written
693 (gpg-with-temp-files 2
694 (let* ((coding-system-for-read 'no-conversion)
695 (coding-system-for-write 'no-conversion)
696 (have-stdin-file (memq 'stdin-file args))
697 (stdin-file (nth 0 gpg-temp-files))
698 (stderr-file (nth 1 gpg-temp-files))
701 (,stdout ,stderr-file)
703 ;; Replace `stdin-file'.
704 ,@(gpg-build-arg-list
705 args (list (cons 'stdin-file stdin-file)))))
707 (when have-stdin-file
708 (with-temp-file stdin-file
709 (buffer-disable-undo)
710 (insert-buffer-substring stdin)))
714 (buffer-disable-undo)
715 (insert passphrase "\n")
716 (unless have-stdin-file
717 (apply 'insert-buffer-substring
718 (if (listp stdin) stdin (list stdin))))
719 (apply 'call-process-region (point-min) (point-max) cpr-args)
720 ;; Wipe out passphrase.
721 (goto-char (point-min))
722 (translate-region (point) (gpg-point-at-eol)
723 (make-string 256 ? )))
725 (with-current-buffer (car stdin)
726 (apply 'call-process-region
728 (if have-stdin-file (cadr stdin) (caddr stdin))
730 (with-current-buffer stdin
731 (apply 'call-process-region
733 (if have-stdin-file (point-min) (point-max))
735 (with-current-buffer stderr
736 (insert-file-contents-literally stderr-file))
737 (if (or (stringp res) (> res 0))
738 ;; Signal or abnormal exit.
739 (with-current-buffer stderr
740 (goto-char (point-max))
741 (insert (format "\nCommand exit status: %s\n" res))
745 (defvar gpg-result-buffer nil
746 "The result of a GnuPG operation is stored in this buffer.
747 Never set this variable directly, use `gpg-show-result' instead.")
749 (defun gpg-show-result-buffer (always-show result)
750 "Called by `gpg-show-results' to actually show the buffer."
751 (with-current-buffer gpg-result-buffer
752 ;; Only proceed if the buffer is non-empty.
753 (when (and (/= (point-min) (point-max))
754 (or always-show (not result)))
755 (save-window-excursion
756 (display-buffer (current-buffer))
757 (unless (y-or-n-p "Continue? ")
758 (error "GnuPG operation aborted."))))))
760 (defmacro gpg-show-result (always-show &rest body)
761 "Show GnuPG result to user for confirmation.
762 This macro binds `gpg-result-buffer' to a temporary buffer and
763 evaluates BODY, like `progn'. If BODY evaluates to `nil' (or
764 `always-show' is not nil), the user is asked for confirmation."
765 `(let ((gpg-result-buffer (get-buffer-create
766 (generate-new-buffer-name "*GnuPG Output*"))))
768 (gpg-show-result-buffer ,always-show (progn ,@body))
769 (kill-buffer gpg-result-buffer))))
770 (put 'gpg-show-result 'lisp-indent-function 1)
771 (put 'gpg-show-result 'edebug-form-spec '(body))
773 ;;; Passphrase handling:
775 (defvar gpg-passphrase-timer
777 "This timer will clear the passphrase cache periodically.")
779 (defvar gpg-passphrase
781 "The (unencrypted) passphrase cache.")
783 (defun gpg-passphrase-clear-string (str)
784 "Erases STR by overwriting all characters."
792 (defun gpg-passphrase-forget ()
793 "Forget stored passphrase."
795 (cancel-timer gpg-passphrase-timer)
796 (gpg-passphrase-clear-string gpg-passphrase)
797 (setq gpg-passphrase nil))
799 (defun gpg-passphrase-store (passphrase)
800 "Store PASSPHRASE in cache.
801 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
802 (unless (equal gpg-passphrase-timeout 0)
803 (timer-set-time gpg-passphrase-timer
804 (timer-relative-time (current-time)
805 gpg-passphrase-timeout))
806 (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
807 (unless (and (fboundp 'itimer-live-p)
808 (itimer-live-p gpg-passphrase-timer))
809 (timer-activate gpg-passphrase-timer))
810 (setq gpg-passphrase passphrase))
813 (defun gpg-passphrase-read ()
814 "Read a passphrase and remember it for some time."
817 ;; This reinitializes the timer.
818 (gpg-passphrase-store gpg-passphrase)
819 (let ((pp (read-passwd "Enter passphrase: ")))
820 (gpg-passphrase-store pp))))
823 ;;;; Main operations:
826 (defun gpg-verify (message signature result)
827 "Verify buffer MESSAGE against detached SIGNATURE buffer.
828 Returns t if everything worked out well, nil otherwise. Consult
829 buffer RESULT for details."
830 (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
831 (gpg-with-temp-files 2
832 (let* ((sig-file (nth 0 gpg-temp-files))
833 (msg-file (nth 1 gpg-temp-files))
834 (cmd (gpg-exec-path gpg-command-verify))
835 (args (gpg-build-arg-list (cdr gpg-command-verify)
836 `((signature-file . ,sig-file)
837 (message-file . ,msg-file))))
839 (with-temp-file sig-file
840 (buffer-disable-undo)
841 (apply 'insert-buffer-substring (if (listp signature)
844 (with-temp-file msg-file
845 (buffer-disable-undo)
846 (apply 'insert-buffer-substring (if (listp message)
849 (setq res (apply 'call-process-region
850 (point-min) (point-min) ; no data
856 (if (or (stringp res) (> res 0))
857 ;; Signal or abnormal exit.
858 (with-current-buffer result
859 (insert (format "\nCommand exit status: %s\n" res))
864 (defun gpg-verify-cleartext (message result)
865 "Verify message in buffer MESSAGE.
866 Returns t if everything worked out well, nil otherwise. Consult
867 buffer RESULT for details.
869 NOTE: Use of this function is deprecated."
870 (interactive "bBuffer containing message: \nbBuffor for result: ")
871 (gpg-with-temp-files 1
872 (let* ((msg-file (nth 0 gpg-temp-files))
873 (cmd (gpg-exec-path gpg-command-verify-cleartext))
874 (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext)
875 `((message-file . ,msg-file))))
877 (with-temp-file msg-file
878 (buffer-disable-undo)
879 (apply 'insert-buffer-substring (if (listp message)
882 (setq res (apply 'call-process-region
883 (point-min) (point-min) ; no data
889 (if (or (stringp res) (> res 0))
890 ;; Signal or abnormal exit.
891 (with-current-buffer result
892 (insert (format "\nCommand exit status: %s\n" res))
897 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
898 "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
899 Returns t if everything worked out well, nil otherwise. Consult
900 buffer RESULT for details. Reads a missing PASSPHRASE using
901 `gpg-passphrase-read'."
902 (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
903 (gpg-call-process (gpg-exec-path gpg-command-decrypt)
904 (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
905 ciphertext plaintext result
906 (if passphrase passphrase (gpg-passphrase-read)))
908 (gpg-passphrase-clear-string passphrase)))
911 (defun gpg-sign-cleartext
912 (plaintext signed-text result &optional passphrase sign-with-key)
913 "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
915 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
916 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
917 everything worked out well, nil otherwise. Consult buffer RESULT for
920 NOTE: Use of this function is deprecated."
921 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
922 (let ((subst (list (cons 'sign-with-key
923 (gpg-build-flag-sign-with-key sign-with-key))
924 (cons 'armor gpg-command-flag-armor)
925 (cons 'textmode gpg-command-flag-textmode))))
926 (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
927 (gpg-build-arg-list (cdr gpg-command-sign-cleartext)
929 plaintext signed-text result
930 (if passphrase passphrase (gpg-passphrase-read))))
932 (gpg-passphrase-clear-string passphrase)))
935 (defun gpg-sign-detached
936 (plaintext signature result &optional passphrase sign-with-key
938 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
939 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
940 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
941 everything worked out well, nil otherwise. Consult buffer RESULT for
942 details. ARMOR the result and activate canonical TEXTMODE if
944 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
945 (let ((subst (list (cons 'sign-with-key
946 (gpg-build-flag-sign-with-key sign-with-key))
947 (cons 'armor (if armor gpg-command-flag-armor))
948 (cons 'textmode (if armor gpg-command-flag-textmode)))))
949 (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
950 (gpg-build-arg-list (cdr gpg-command-sign-detached)
952 plaintext signature result
953 (if passphrase passphrase (gpg-passphrase-read))))
955 (gpg-passphrase-clear-string passphrase)))
959 (defun gpg-sign-encrypt
960 (plaintext ciphertext result recipients &optional passphrase sign-with-key
962 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
963 RECIPIENTS is a list of key IDs used for encryption. This function
964 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
965 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
966 ID. Returns t if everything worked out well, nil otherwise. Consult
967 buffer RESULT for details. ARMOR the result and activate canonical
968 TEXTMODE if requested."
970 (read-buffer "Buffer containing plaintext: " nil t)
971 (read-buffer "Buffer for ciphertext: " nil t)
972 (read-buffer "Buffer for status informationt: " nil t)
973 (gpg-read-recipients)))
974 (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key
976 (plaintext-file . stdin-file)
977 (recipients . ,(gpg-build-flag-recipients recipients))
978 (armor ,(if armor gpg-command-flag-armor))
979 (textmode ,(if armor gpg-command-flag-textmode)))))
980 (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
981 (gpg-build-arg-list (cdr gpg-command-sign-encrypt)
983 plaintext ciphertext result
984 (if passphrase passphrase (gpg-passphrase-read))))
986 (gpg-passphrase-clear-string passphrase)))
991 (plaintext ciphertext result recipients &optional passphrase armor textmode)
992 "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
993 RECIPIENTS is a list of key IDs used for encryption. Returns t if
994 everything worked out well, nil otherwise. Consult buffer RESULT for
995 details. ARMOR the result and activate canonical
996 TEXTMODE if requested."
998 (read-buffer "Buffer containing plaintext: " nil t)
999 (read-buffer "Buffer for ciphertext: " nil t)
1000 (read-buffer "Buffer for status informationt: " nil t)
1001 (gpg-read-recipients)))
1002 (let ((subst `((plaintext-file . stdin-file)
1003 (recipients . ,(gpg-build-flag-recipients recipients))
1004 (armor ,(if armor gpg-command-flag-armor))
1005 (textmode ,(if armor gpg-command-flag-textmode)))))
1006 (gpg-call-process (gpg-exec-path gpg-command-encrypt)
1007 (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
1008 plaintext ciphertext result nil))
1010 (gpg-passphrase-clear-string passphrase)))
1015 ;;; ADT: OpenPGP Key
1017 (defun gpg-key-make (user-id key-id unique-id length algorithm
1018 creation-date expire-date validity trust)
1019 "Create a new key object (for internal use only)."
1022 user-id key-id unique-id length algorithm
1024 creation-date expire-date validity trust))
1027 (defun gpg-key-p (key)
1028 "Return t if KEY is a key specification."
1029 (and (arrayp key) (equal (length key) 9) key))
1031 (defmacro gpg-key-primary-user-id (key)
1032 "The primary user ID for KEY (human-readable).
1033 DO NOT USE this ID for selecting recipients. It is probably not
1035 (list 'car (list 'aref key 0)))
1037 (defmacro gpg-key-user-ids (key)
1038 "A list of additional user IDs for KEY (human-readable).
1039 DO NOT USE these IDs for selecting recipients. They are probably not
1041 (list 'cdr (list 'aref key 0)))
1043 (defmacro gpg-key-id (key)
1045 DO NOT USE this ID for selecting recipients. It is not guaranteed to
1049 (defun gpg-short-key-id (key)
1050 "The short key ID of KEY."
1051 (let* ((id (gpg-key-id key))
1054 (substring id (- len 8))
1057 (defmacro gpg-key-unique-id (key)
1058 "A non-standard ID of KEY which is only valid locally.
1059 This ID can be used to specify recipients in a safe manner. Note,
1060 even this ID might not be unique unless GnuPG is used."
1063 (defmacro gpg-key-unique-id-list (key-list)
1064 "Like `gpg-key-unique-id', but operate on a list."
1065 `(mapcar (lambda (key) (gpg-key-unique-id key))
1068 (defmacro gpg-key-length (key)
1069 "Returns the key length."
1072 (defmacro gpg-key-algorithm (key)
1073 "The encryption algorithm used by KEY.
1074 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1075 `elgamal-encrypt', `dsa'."
1078 (defmacro gpg-key-creation-date (key)
1079 "A string with the creation date of KEY in ISO format."
1082 (defmacro gpg-key-expire-date (key)
1083 "A string with the expiration date of KEY in ISO format."
1086 (defmacro gpg-key-validity (key)
1087 "The calculated validity of KEY.
1088 One of the symbols `not-known', `disabled', `revoked', `expired',
1089 `undefined', `trust-none', `trust-marginal', `trust-full',
1090 `trust-ultimate' (see the GnuPG documentation for details)."
1093 (defmacro gpg-key-trust (key)
1094 "The assigned trust for KEY.
1095 One of the symbols `not-known', `undefined', `trust-none',
1096 `trust-marginal', `trust-full' (see the GnuPG
1097 documentation for details)."
1100 (defun gpg-key-lessp (a b)
1101 "Returns t if primary user ID of A is less than B."
1102 (string-lessp (gpg-key-primary-user-id a) (gpg-key-primary-user-id b) ))
1104 ;;; Accessing the key database:
1106 ;; Internal functions:
1108 (defmacro gpg-key-list-keys-skip-field ()
1109 '(search-forward ":" eol 'move))
1111 (defmacro gpg-key-list-keys-get-field ()
1112 '(buffer-substring (point) (if (gpg-key-list-keys-skip-field)
1115 (defmacro gpg-key-list-keys-string-field ()
1116 '(gpg-key-list-keys-get-field))
1118 (defmacro gpg-key-list-keys-read-field ()
1119 (let ((field (make-symbol "field")))
1120 `(let ((,field (gpg-key-list-keys-get-field)))
1121 (if (equal (length ,field) 0)
1125 (defun gpg-key-list-keys-parse-line ()
1126 "Parse the line in the current buffer and return a vector of fields."
1127 (let* ((eol (gpg-point-at-eol))
1131 (gpg-key-list-keys-read-field) ; type
1132 (gpg-key-list-keys-get-field) ; trust
1133 (gpg-key-list-keys-read-field) ; key length
1134 (gpg-key-list-keys-read-field) ; algorithm
1135 (gpg-key-list-keys-get-field) ; key ID
1136 (gpg-key-list-keys-get-field) ; creation data
1137 (gpg-key-list-keys-get-field) ; expire
1138 (gpg-key-list-keys-get-field) ; unique (local) ID
1139 (gpg-key-list-keys-get-field) ; ownertrust
1140 (gpg-key-list-keys-string-field) ; user ID
1145 (error "Too many fields in GnuPG key database"))
1148 (defconst gpg-pubkey-algo-alist
1150 (2 . rsa-encrypt-only)
1152 (16 . elgamal-encrypt-only)
1155 "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1157 (defconst gpg-trust-alist
1163 (?q . trust-undefined)
1165 (?m . trust-marginal)
1167 (?u . trust-ultimate))
1168 "Alist mapping GnuPG trust value short forms to long symbols.")
1170 (defmacro gpg-key-list-keys-in-buffer-store ()
1171 '(when primary-user-id
1172 (sort user-id 'string-lessp)
1173 (push (gpg-key-make (cons primary-user-id user-id)
1174 key-id unique-id key-length
1175 algorithm creation-date
1176 expire-date validity trust)
1179 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1180 "Return a list of keys for BUFFER.
1181 If BUFFER is omitted, use current buffer."
1182 (with-current-buffer (if buffer buffer (current-buffer))
1183 (goto-char (point-min))
1184 ;; Skip key ring filename written by GnuPG.
1185 (search-forward "\n---------------------------\n" nil t)
1186 ;; Loop over all lines in buffer and analyze them.
1187 (let (primary-user-id user-id key-id unique-id ; current key components
1188 key-length algorithm creation-date expire-date validity trust
1189 line ; fields in current line
1190 key-list) ; keys gather so far
1192 (while (setq line (gpg-key-list-keys-parse-line))
1194 ;; Public or secret key.
1195 ((memq (aref line 0) '(pub sec))
1196 ;; Store previous key, if any.
1197 (gpg-key-list-keys-in-buffer-store)
1198 ;; Record field values.
1199 (setq primary-user-id (aref line 9))
1201 (setq key-id (aref line 4))
1202 ;; We use the key ID if no unique ID is available.
1203 (setq unique-id (if (> (length (aref line 7)) 0)
1204 (concat "#" (aref line 7))
1205 (concat "0x" key-id)))
1206 (setq key-length (aref line 2))
1207 (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1209 (setq algorithm (cdr algorithm))
1210 (error "Unknown algorithm %s" (aref line 3)))
1211 (setq creation-date (if (> (length (aref line 5)) 0)
1213 (setq expire-date (if (> (length (aref line 6)) 0)
1215 (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1217 (setq validity (cdr validity))
1218 (error "Unknown validity specification %S" (aref line 1)))
1219 (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1221 (setq trust (cdr trust))
1222 (error "Unknown trust specification %S" (aref line 8))))
1224 ;; Additional user ID
1225 ((eq 'uid (aref line 0))
1226 (setq user-id (cons (aref line 9) user-id)))
1228 ;; Subkeys are ignored for now.
1229 ((memq (aref line 0) '(sub ssb))
1231 (t (error "Unknown record type %S" (aref line 0)))))
1233 ;; Store the key retrieved last.
1234 (gpg-key-list-keys-in-buffer-store)
1235 ;; Sort the keys according to the primary user ID.
1236 (sort key-list 'gpg-key-lessp))))
1238 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1239 "Insert the output of COMMAND before point in current buffer."
1240 (let* ((cmd (gpg-exec-path command))
1241 (key (if (equal keyspec "") nil keyspec))
1242 (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1245 (apply 'call-process-region
1246 (point-min) (point-min) ; no data
1249 (if stderr t '(t nil))
1252 (unless (or ignore-error (equal exit-status 0))
1253 (error "GnuPG command exited unsuccessfully"))))
1256 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1257 "Return a list of keys matching KEYSPEC.
1258 COMMAND is used to obtain the key list. The usual substring search
1259 for keys is performed."
1261 (buffer-disable-undo)
1262 (gpg-key-list-keyspec command keyspec)
1263 (gpg-key-list-keys-in-buffer)))
1266 (defun gpg-key-list-keys (&optional keyspec)
1267 "A list of public keys matching KEYSPEC.
1268 The usual substring search for keys is performed."
1269 (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1272 (defun gpg-key-list-secret-keys (&optional keyspec)
1273 "A list of secret keys matching KEYSPEC.
1274 The usual substring search for keys is performed."
1275 (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1278 (defun gpg-key-insert-public-key (key)
1279 "Inserts the public key(s) matching KEYSPEC.
1280 The ASCII-armored key is inserted before point into current buffer."
1281 (gpg-key-list-keyspec gpg-command-key-export key))
1284 (defun gpg-key-insert-information (key)
1285 "Insert human-readable information (including fingerprint) on KEY.
1286 Insertion takes place in current buffer before point."
1287 (gpg-key-list-keyspec gpg-command-key-verify key))
1290 (defun gpg-key-retrieve (key)
1291 "Fetch KEY from default key server.
1292 KEY is a key ID or a list of key IDs. Status information about this
1293 operation is inserted into the current buffer before point."
1294 (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1297 (defun gpg-key-add-to-ring (key result)
1298 "Adds key in buffer KEY to the GnuPG key ring.
1299 Human-readable information on the RESULT is stored in buffer RESULT
1304 ;;; gpg.el ends here