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).
114 (defalias 'gpg-point-at-eol
115 (if (fboundp 'point-at-eol)
117 'line-end-position)))
121 ;;; Customization: Groups:
124 "GNU Privacy Guard interface."
128 (defgroup gpg-options nil
129 "Controlling GnuPG invocation."
133 (defgroup gpg-commands nil
134 "Primary GnuPG Operations."
135 :tag "GnuPG Commands"
138 (defgroup gpg-commands-key nil
139 "Commands for GnuPG key management."
140 :tag "GnuPG Key Commands"
141 :group 'gpg-commands)
143 ;;; Customization: Widgets:
145 (if (get 'alist 'widget-type)
146 (define-widget 'gpg-command-alist 'alist
147 "An association list for GnuPG command names."
148 :key-type '(symbol :tag "Abbreviation")
149 :value-type '(string :tag "Program name")
150 :convert-widget 'widget-alist-convert-widget
152 (define-widget 'gpg-command-alist 'repeat
153 "An association list for GnuPG command names."
154 :args '((cons :format "%v"
155 (symbol :tag "Abbreviation")
156 (string :tag "Program name")))
159 (define-widget 'gpg-command-program 'choice
160 "Widget for entering the name of a program (mostly the GnuPG binary)."
162 :args '((const :tag "Default GnuPG program."
164 (const :tag "GnuPG compatibility wrapper."
166 (const :tag "Disabled"
168 (string :tag "Custom program" :format "%v")))
170 (define-widget 'gpg-command-sign-options 'cons
171 "Widget for entering signing options."
172 :args '(gpg-command-program
176 :format "%[Type%] %v"
177 (const :tag "Insert armor option here if necessary."
179 (const :tag "Insert text mode option here if necessary."
181 (const :tag "Insert the sign with key option here if necessary."
182 :value sign-with-key)
183 (string :format "%v")))))
185 (define-widget 'gpg-command-key-options 'cons
186 "Widget for entering key command options."
187 :args '(gpg-command-program
191 :format "%[Type%] %v"
192 (const :tag "Insert key ID here."
194 (string :format "%v")))))
196 ;;; Customization: Variables:
198 ;;; Customization: Variables: Paths and Flags:
200 (defcustom gpg-passphrase-timeout
202 "Timeout (in seconds) for the passphrase cache.
203 The passphrase cache is cleared after is hasn't been used for this
204 many seconds. The values 0 means that the passphrase is not cached at
206 :tag "Passphrase Timeout"
210 (defcustom gpg-default-key-id
212 "Default key/user ID used for signatures."
213 :tag "Default Key ID"
215 (const :tag "Use GnuPG default." :value nil)
219 (defcustom gpg-temp-directory
220 (expand-file-name "~/tmp")
221 "Directory for temporary files.
222 If you are running Emacs 20, this directory must have mode 0700."
223 :tag "Temp directory"
227 (defcustom gpg-command-default-alist
229 (gpg-2comp . "gpg-2comp"))
230 "Default paths for some GnuPG-related programs.
231 Modify this variable if you have to change the paths to the
232 executables required by the GnuPG interface. You can enter \"gpg\"
233 for `gpg-2comp' if you don't have this script, but you'll lose PGP
234 2.6.x compatibility."
235 :tag "GnuPG programs"
236 :type 'gpg-command-alist
239 (defcustom gpg-command-all-arglist
241 "List of arguments to add to all GPG commands."
242 :tag "All command args"
245 (defcustom gpg-command-flag-textmode "--textmode"
246 "The flag to indicate canonical text mode to GnuPG."
247 :tag "Text mode flag"
251 (defcustom gpg-command-flag-armor "--armor"
252 "The flag to request ASCII-armoring output from GnuPG."
257 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
258 "String to include to specify the signing key ID.
259 The elements are concatenated (without spaces) to form a command line
261 :tag "Sign with key flag"
262 :type '(repeat :tag "Argument parts"
263 (choice :format "%[Type%] %v"
264 (const :tag "Start next argument." :value next-argument)
265 (const :tag "Insert signing key ID here." :value sign-with-key)
269 (defcustom gpg-command-flag-recipient
270 '(nil . ("-r" next-argument recipient next-argument))
271 "Format of a recipient specification.
272 The elements are concatenated (without spaces) to form a command line
273 option. The second part is repeated for each recipient."
274 :tag "Recipients Flag"
276 (repeat :tag "Common prefix"
277 (choice :format "%[Type%] %v"
278 (const :tag "Start next argument." :value next-argument)
280 (repeat :tag "For each recipient"
281 (choice :format "%[Type%] %v"
282 (const :tag "Start next argument." :value next-argument)
283 (const :tag "Insert recipient key ID here." :value recipient)
287 (defcustom gpg-command-passphrase-env
289 "Environment variable to set when a passphrase is required, or nil.
290 If an operation is invoked which requires a passphrase, this
291 environment variable is set before calling the external program to
292 indicate that it should read the passphrase from standard input."
293 :tag "Passphrase environment"
295 (const :tag "Disabled" :value nil)
297 (string :tag "Variable")
298 (string :tag "Value")))
301 ;;; Customization: Variables: GnuPG Commands:
303 (defcustom gpg-command-verify
304 '(gpg . ("--batch" "--verbose" "--verify" signature-file message-file))
305 "Command to verify a detached signature.
306 The invoked program has to read the signed message and the signature
307 from the given files. It should write human-readable information to
308 standard output and/or standard error. The program shall not convert
309 charsets or line endings; the input data shall be treated as binary."
310 :tag "Verify Command"
316 :format "%[Type%] %v"
317 (const :tag "Insert name of file containing the message here."
319 (const :tag "Insert name of file containing the signature here."
320 :value signature-file)
321 (string :format "%v"))))
322 :group 'gpg-commands)
324 (defcustom gpg-command-verify-cleartext
325 '(gpg . ("--batch" "--verbose" "--verify" message-file))
326 "Command to verify a message.
327 The invoked program has to read the signed message from the given
328 file. It should write human-readable information to standard output
329 and/or standard error. The program shall not convert charsets or line
330 endings; the input data shall be treated as binary."
331 :tag "Cleartext Verify Command"
337 :format "%[Type%] %v"
338 (const :tag "Insert name of file containing the message here."
340 (string :format "%v"))))
341 :group 'gpg-commands)
343 (defcustom gpg-command-decrypt
344 '(gpg . ("--decrypt" "--batch" "--passphrase-fd=0"))
345 "Command to decrypt a message.
346 The invoked program has to read the passphrase from standard
347 input, followed by the encrypted message. It writes the decrypted
348 message to standard output, and human-readable diagnostic messages to
350 :tag "Decrypt Command"
356 :format "%[Type%] %v"
357 (const :tag "Insert name of file containing the message here."
359 (string :format "%v"))))
360 :group 'gpg-commands)
362 (defcustom gpg-command-sign-cleartext
363 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
364 armor textmode "--clearsign"
366 "Command to create a create a \"clearsign\" text file.
367 The invoked program has to read the passphrase from standard input,
368 followed by the message to sign. It should write the ASCII-amored
369 signed text message to standard output, and diagnostic messages to
371 :tag "Clearsign Command"
372 :type 'gpg-command-sign-options
373 :group 'gpg-commands)
375 (defcustom gpg-command-sign-detached
376 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
377 armor textmode "--detach-sign"
379 "Command to create a create a detached signature.
380 The invoked program has to read the passphrase from standard input,
381 followed by the message to sign. It should write the ASCII-amored
382 detached signature to standard output, and diagnostic messages to
383 standard error. The program shall not convert charsets or line
384 endings; the input data shall be treated as binary."
385 :tag "Sign Detached Command"
386 :type 'gpg-command-sign-options
387 :group 'gpg-commands)
389 (defcustom gpg-command-sign-encrypt
390 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
391 armor textmode "--always-trust" sign-with-key recipients
392 "--sign" "--encrypt" plaintext-file))
393 "Command to sign and encrypt a file.
394 The invoked program has to read the passphrase from standard input,
395 followed by the message to sign and encrypt if there is no
396 `plaintext-file' placeholder. It should write the ASCII-amored
397 encrypted message to standard output, and diagnostic messages to
399 :tag "Sign And Encrypt Command"
405 :format "%[Type%] %v"
406 (const :tag "Insert the `sign with key' option here if necessary."
407 :value sign-with-key)
408 (const :tag "Insert list of recipients here."
410 (const :tag "Insert here name of file with plaintext."
411 :value plaintext-file)
412 (string :format "%v"))))
413 :group 'gpg-commands)
415 (defcustom gpg-command-encrypt
416 '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust"
417 "--encrypt" recipients plaintext-file))
418 "Command to encrypt a file.
419 The invoked program has to read the message to encrypt from standard
420 input or from the plaintext file (if the `plaintext-file' placeholder
421 is present). It should write the ASCII-amored encrypted message to
422 standard output, and diagnostic messages to standard error."
428 :format "%[Type%] %v"
429 (const :tag "Insert list of recipients here."
431 (const :tag "Insert here name of file with plaintext."
432 :value plaintext-file)
433 (string :format "%v"))))
434 :group 'gpg-commands)
436 ;;; Customization: Variables: Key Management Commands:
438 (defcustom gpg-command-key-import
439 '(gpg . ("--import" "--verbose" message-file))
440 "Command to import a public key from a file."
441 :tag "Import Command"
447 :format "%[Type%] %v"
448 (const :tag "Insert name of file containing the key here."
450 (string :format "%v"))))
451 :group 'gpg-commands-key)
453 (defcustom gpg-command-key-export
454 '(gpg . ("--no-verbose" "--armor" "--export" key-id))
455 "Command to export a public key from the key ring.
456 The key should be written to standard output using ASCII armor."
457 :tag "Export Command"
458 :type 'gpg-command-key-options
459 :group 'gpg-commands-key)
461 (defcustom gpg-command-key-verify
462 '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
463 "Command to verify a public key."
464 :tag "Verification Command"
465 :type 'gpg-command-key-options
466 :group 'gpg-commands-key)
468 (defcustom gpg-command-key-public-ring
469 '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
470 "Command to list the contents of the public key ring."
471 :tag "List Public Key Ring Command"
472 :type 'gpg-command-key-options
473 :group 'gpg-commands-key)
475 (defcustom gpg-command-key-secret-ring
476 '(gpg . ("--no-verbose" "--batch" "--with-colons"
477 "--list-secret-keys" key-id))
478 "Command to list the contents of the secret key ring."
479 :tag "List Secret Key Ring Command"
480 :type 'gpg-command-key-options
481 :group 'gpg-commands-key)
483 (defcustom gpg-command-key-retrieve
484 '(gpg . ("--batch" "--recv-keys" key-id))
485 "Command to retrieve public keys."
486 :tag "Retrieve Keys Command"
487 :type 'gpg-command-key-options
488 :group 'gpg-commands-key)
491 ;;;; Helper functions for GnuPG invocation:
493 ;;; Build the GnuPG command line:
495 (defun gpg-build-argument (template substitutions &optional pass-start)
496 "Build command line argument(s) by substituting placeholders.
497 TEMPLATE is a list of strings and symbols. The placeholder symbols in
498 it are replaced by SUBSTITUTIONS, the elements between
499 `next-argument' symbols are concatenated without spaces and are
502 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
503 a string (which is inserted literally), a list of strings (which are
504 inserted as well), or nil, which means to insert nothing.
506 If PASS-START is t, `next-argument' is also inserted into the result,
507 and symbols without a proper substitution are retained in the output,
508 otherwise, an untranslated symbol results in an error.
510 This function does not handle empty arguments reliably."
511 (let ((current-arg "")
514 (let* ((templ (pop template))
515 (repl (assoc templ substitutions))
516 (new (if repl (cdr repl) templ)))
518 ((eq templ 'next-argument)
519 ;; If the current argument is not empty, start a new one.
520 (unless (equal current-arg "")
521 (setq arglist (nconc arglist
523 (list current-arg 'next-argument)
524 (list current-arg))))
525 (setq current-arg "")))
526 ((null new) nil) ; Drop it.
527 ((and (not (stringp templ)) (null repl))
528 ;; Retain an untranslated symbol in the output if
529 ;; `pass-start' is true.
531 (error "No replacement for `%s'" templ))
532 (setq arglist (nconc arglist (list current-arg templ)))
533 (setq current-arg ""))
536 (setq new (list new)))
537 (setq current-arg (concat current-arg
538 (apply 'concat new)))))))
539 (unless (equal current-arg "")
540 (setq arglist (nconc arglist (list current-arg))))
543 (defun gpg-build-arg-list (template substitutions)
544 "Build command line by substituting placeholders.
545 TEMPLATE is a list of strings and symbols. The placeholder symbols in
546 it are replaced by SUBSTITUTIONS.
548 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
549 string (which is inserted literally), a list of strings (which are
550 inserted as well), or nil, which means to insert nothing."
551 (let ((arglist (copy-sequence gpg-command-all-arglist)))
553 (let* ((templ (pop template))
554 (repl (assoc templ substitutions))
555 (new (if repl (cdr repl) templ)))
557 ((and (symbolp templ) (null repl))
558 (error "No replacement for `%s'" templ))
559 ((null new) nil) ; Drop it.
562 (setq new (list new)))
563 (setq arglist (nconc arglist new))))))
566 (defun gpg-build-flag-recipients-one (recipient)
567 "Build argument for one RECIPIENT."
568 (gpg-build-argument (cdr gpg-command-flag-recipient)
569 `((recipient . ,recipient)) t))
571 (defun gpg-build-flag-recipients (recipients)
572 "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
574 (apply 'append (car gpg-command-flag-recipient)
575 (mapcar 'gpg-build-flag-recipients-one
579 (defun gpg-read-recipients ()
580 "Query the user for several recipients."
584 (setq r (read-string "Enter recipient ID [RET when no more]: "))
587 (setq recipients (nconc recipients (list r)))))
590 (defun gpg-build-flag-sign-with-key (key)
591 "Build sign with key flag using `gpg-command-flag-sign-with-key'."
593 (if gpg-default-key-id gpg-default-key-id
596 (gpg-build-argument gpg-command-flag-sign-with-key
597 (list (cons 'sign-with-key k)))
600 (defmacro gpg-with-passphrase-env (&rest body)
601 "Adjust the process environment and evaluate BODY.
602 During the evaluation of the body forms, the process environment is
603 adjust according to `gpg-command-passphrase-env'."
604 (let ((env-value (make-symbol "env-value")))
608 (when gpg-command-passphrase-env
609 (setq ,env-value (getenv (car gpg-command-passphrase-env)))
610 (setenv (car gpg-command-passphrase-env)
611 (cdr gpg-command-passphrase-env)))
613 (when gpg-command-passphrase-env
614 ;; This will clear the variable if it wasn't set before.
615 (setenv (car gpg-command-passphrase-env) ,env-value))))))
616 (put 'gpg-with-passphrase-env 'lisp-indent-function 0)
617 (put 'gpg-with-passphrase-env 'edebug-form-spec '(body))
621 (defun gpg-make-temp-file ()
622 "Create a temporary file in a safe way"
623 (let ((name ;; User may use "~/"
624 (expand-file-name "gnupg" gpg-temp-directory)))
625 (if (fboundp 'make-temp-file)
626 ;; If we've got make-temp-file, we are on the save side.
627 (make-temp-file name)
628 ;; make-temp-name doesn't create the file, and an ordinary
629 ;; write-file operation is prone to nasty symlink attacks if the
630 ;; temporary file resides in a world-writable directory.
631 (unless (or (memq system-type '(windows-nt cygwin32 win32 w32 mswindows))
632 (eq (file-modes gpg-temp-directory) 448)) ; mode 0700
633 (error "Directory for temporary files (%s) must have mode 0700." gpg-temp-directory))
634 (setq name (make-temp-name name))
635 (let ((mode (default-file-modes)))
638 (set-default-file-modes 384) ; mode 0600
639 (with-temp-file name))
640 (set-default-file-modes mode)))
643 (defvar gpg-temp-files nil
644 "List of temporary files used by the GnuPG interface.
645 Do not set this variable. Call `gpg-with-temp-files' if you need
648 (defun gpg-with-temp-files-create (count)
649 "Do not call this function. Used internally by `gpg-with-temp-files'."
651 (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
652 (setq count (1- count))))
654 (defun gpg-with-temp-files-delete ()
655 "Do not call this function. Used internally by `gpg-with-temp-files'."
656 (while gpg-temp-files
657 (let ((file (pop gpg-temp-files)))
662 (defmacro gpg-with-temp-files (count &rest body)
663 "Create COUNT temporary files, USE them, and delete them.
664 The function USE is called with the names of all temporary files as
666 `(let ((gpg-temp-files))
669 ;; Create the temporary files.
670 (gpg-with-temp-files-create ,count)
672 (gpg-with-temp-files-delete))))
673 (put 'gpg-with-temp-files 'lisp-indent-function 1)
674 (put 'gpg-with-temp-files 'edebug-form-spec '(body))
676 ;;; Making subprocesses:
678 (defun gpg-exec-path (option)
679 "Return the program name for OPTION.
680 OPTION is of the form (PROGRAM . ARGLIST). This functions returns
681 PROGRAM, but takes default values into account."
682 (let* ((prg (car option))
683 (path (assq prg gpg-command-default-alist)))
685 (path (if (null (cdr path))
686 (error "Command `%s' is not available" prg)
688 ((null prg) (error "Command is disabled"))
691 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
692 "Invoke external program CMD with ARGS on buffer STDIN.
693 Standard output is insert before point in STDOUT, standard error in
694 STDERR. If PASSPHRASE is given, send it before STDIN. PASSPHRASE
695 should not end with a line feed (\"\\n\").
697 If `stdin-file' is present in ARGS, it is replaced by the name of a
698 temporary file. Before invoking CMD, the contents of STDIN is written
700 (gpg-with-temp-files 2
701 (let* ((coding-system-for-read 'no-conversion)
702 (coding-system-for-write 'no-conversion)
703 (have-stdin-file (memq 'stdin-file args))
704 (stdin-file (nth 0 gpg-temp-files))
705 (stderr-file (nth 1 gpg-temp-files))
708 (,stdout ,stderr-file)
710 ;; Replace `stdin-file'.
711 ,@(gpg-build-arg-list
712 args (list (cons 'stdin-file stdin-file)))))
714 (when have-stdin-file
715 (with-temp-file stdin-file
716 (buffer-disable-undo)
717 (insert-buffer-substring stdin)))
721 (buffer-disable-undo)
722 (insert passphrase "\n")
723 (unless have-stdin-file
724 (apply 'insert-buffer-substring
725 (if (listp stdin) stdin (list stdin))))
726 (apply 'call-process-region (point-min) (point-max) cpr-args)
727 ;; Wipe out passphrase.
728 (goto-char (point-min))
729 (translate-region (point) (gpg-point-at-eol)
730 (make-string 256 ? )))
732 (with-current-buffer (car stdin)
733 (apply 'call-process-region
735 (if have-stdin-file (cadr stdin) (caddr stdin))
737 (with-current-buffer stdin
738 (apply 'call-process-region
740 (if have-stdin-file (point-min) (point-max))
742 (with-current-buffer stderr
743 (insert-file-contents-literally stderr-file))
744 (if (or (stringp res) (> res 0))
745 ;; Signal or abnormal exit.
746 (with-current-buffer stderr
747 (goto-char (point-max))
748 (insert (format "\nCommand exit status: %s\n" res))
752 (defvar gpg-result-buffer nil
753 "The result of a GnuPG operation is stored in this buffer.
754 Never set this variable directly, use `gpg-show-result' instead.")
756 (defun gpg-show-result-buffer (always-show result)
757 "Called by `gpg-show-results' to actually show the buffer."
758 (with-current-buffer gpg-result-buffer
759 ;; Only proceed if the buffer is non-empty.
760 (when (and (/= (point-min) (point-max))
761 (or always-show (not result)))
762 (save-window-excursion
763 (display-buffer (current-buffer))
764 (unless (y-or-n-p "Continue? ")
765 (error "GnuPG operation aborted."))))))
767 (defmacro gpg-show-result (always-show &rest body)
768 "Show GnuPG result to user for confirmation.
769 This macro binds `gpg-result-buffer' to a temporary buffer and
770 evaluates BODY, like `progn'. If BODY evaluates to `nil' (or
771 `always-show' is not nil), the user is asked for confirmation."
772 `(let ((gpg-result-buffer (get-buffer-create
773 (generate-new-buffer-name "*GnuPG Output*"))))
775 (gpg-show-result-buffer ,always-show (progn ,@body))
776 (kill-buffer gpg-result-buffer))))
777 (put 'gpg-show-result 'lisp-indent-function 1)
778 (put 'gpg-show-result 'edebug-form-spec '(body))
780 ;;; Passphrase handling:
782 (defvar gpg-passphrase-timer
784 "This timer will clear the passphrase cache periodically.")
786 (defvar gpg-passphrase
788 "The (unencrypted) passphrase cache.")
790 (defun gpg-passphrase-clear-string (str)
791 "Erases STR by overwriting all characters."
799 (defun gpg-passphrase-forget ()
800 "Forget stored passphrase."
802 (cancel-timer gpg-passphrase-timer)
803 (gpg-passphrase-clear-string gpg-passphrase)
804 (setq gpg-passphrase nil))
806 (defun gpg-passphrase-store (passphrase)
807 "Store PASSPHRASE in cache.
808 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
809 (unless (equal gpg-passphrase-timeout 0)
810 (timer-set-time gpg-passphrase-timer
811 (timer-relative-time (current-time)
812 gpg-passphrase-timeout))
813 (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
814 (unless (and (fboundp 'itimer-live-p)
815 (itimer-live-p gpg-passphrase-timer))
816 (timer-activate gpg-passphrase-timer))
817 (setq gpg-passphrase passphrase))
820 (defun gpg-passphrase-read ()
821 "Read a passphrase and remember it for some time."
824 ;; This reinitializes the timer.
825 (gpg-passphrase-store gpg-passphrase)
826 (let ((pp (read-passwd "Enter passphrase: ")))
827 (gpg-passphrase-store pp))))
830 ;;;; Main operations:
833 (defun gpg-verify (message signature result)
834 "Verify buffer MESSAGE against detached SIGNATURE buffer.
835 Returns t if everything worked out well, nil otherwise. Consult
836 buffer RESULT for details."
837 (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
838 (gpg-with-temp-files 2
839 (let* ((sig-file (nth 0 gpg-temp-files))
840 (msg-file (nth 1 gpg-temp-files))
841 (cmd (gpg-exec-path gpg-command-verify))
842 (args (gpg-build-arg-list (cdr gpg-command-verify)
843 `((signature-file . ,sig-file)
844 (message-file . ,msg-file))))
846 (with-temp-file sig-file
847 (buffer-disable-undo)
848 (apply 'insert-buffer-substring (if (listp signature)
851 (with-temp-file msg-file
852 (buffer-disable-undo)
853 (apply 'insert-buffer-substring (if (listp message)
856 (setq res (apply 'call-process-region
857 (point-min) (point-min) ; no data
863 (if (or (stringp res) (> res 0))
864 ;; Signal or abnormal exit.
865 (with-current-buffer result
866 (insert (format "\nCommand exit status: %s\n" res))
871 (defun gpg-verify-cleartext (message result)
872 "Verify message in buffer MESSAGE.
873 Returns t if everything worked out well, nil otherwise. Consult
874 buffer RESULT for details.
876 NOTE: Use of this function is deprecated."
877 (interactive "bBuffer containing message: \nbBuffor for result: ")
878 (gpg-with-temp-files 1
879 (let* ((msg-file (nth 0 gpg-temp-files))
880 (cmd (gpg-exec-path gpg-command-verify-cleartext))
881 (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext)
882 `((message-file . ,msg-file))))
884 (with-temp-file msg-file
885 (buffer-disable-undo)
886 (apply 'insert-buffer-substring (if (listp message)
889 (setq res (apply 'call-process-region
890 (point-min) (point-min) ; no data
896 (if (or (stringp res) (> res 0))
897 ;; Signal or abnormal exit.
898 (with-current-buffer result
899 (insert (format "\nCommand exit status: %s\n" res))
904 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
905 "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
906 Returns t if everything worked out well, nil otherwise. Consult
907 buffer RESULT for details. Reads a missing PASSPHRASE using
908 `gpg-passphrase-read'."
909 (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
910 (gpg-call-process (gpg-exec-path gpg-command-decrypt)
911 (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
912 ciphertext plaintext result
913 (if passphrase passphrase (gpg-passphrase-read)))
915 (gpg-passphrase-clear-string passphrase)))
918 (defun gpg-sign-cleartext
919 (plaintext signed-text result &optional passphrase sign-with-key)
920 "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
922 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
923 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
924 everything worked out well, nil otherwise. Consult buffer RESULT for
927 NOTE: Use of this function is deprecated."
928 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
929 (let ((subst (list (cons 'sign-with-key
930 (gpg-build-flag-sign-with-key sign-with-key))
931 (cons 'armor gpg-command-flag-armor)
932 (cons 'textmode gpg-command-flag-textmode))))
933 (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
934 (gpg-build-arg-list (cdr gpg-command-sign-cleartext)
936 plaintext signed-text result
937 (if passphrase passphrase (gpg-passphrase-read))))
939 (gpg-passphrase-clear-string passphrase)))
942 (defun gpg-sign-detached
943 (plaintext signature result &optional passphrase sign-with-key
945 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
946 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
947 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
948 everything worked out well, nil otherwise. Consult buffer RESULT for
949 details. ARMOR the result and activate canonical TEXTMODE if
951 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
952 (let ((subst (list (cons 'sign-with-key
953 (gpg-build-flag-sign-with-key sign-with-key))
954 (cons 'armor (if armor gpg-command-flag-armor))
955 (cons 'textmode (if armor gpg-command-flag-textmode)))))
956 (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
957 (gpg-build-arg-list (cdr gpg-command-sign-detached)
959 plaintext signature result
960 (if passphrase passphrase (gpg-passphrase-read))))
962 (gpg-passphrase-clear-string passphrase)))
966 (defun gpg-sign-encrypt
967 (plaintext ciphertext result recipients &optional passphrase sign-with-key
969 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
970 RECIPIENTS is a list of key IDs used for encryption. This function
971 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
972 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
973 ID. Returns t if everything worked out well, nil otherwise. Consult
974 buffer RESULT for details. ARMOR the result and activate canonical
975 TEXTMODE if requested."
977 (read-buffer "Buffer containing plaintext: " nil t)
978 (read-buffer "Buffer for ciphertext: " nil t)
979 (read-buffer "Buffer for status informationt: " nil t)
980 (gpg-read-recipients)))
981 (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key
983 (plaintext-file . stdin-file)
984 (recipients . ,(gpg-build-flag-recipients recipients))
985 (armor ,(if armor gpg-command-flag-armor))
986 (textmode ,(if armor gpg-command-flag-textmode)))))
987 (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
988 (gpg-build-arg-list (cdr gpg-command-sign-encrypt)
990 plaintext ciphertext result
991 (if passphrase passphrase (gpg-passphrase-read))))
993 (gpg-passphrase-clear-string passphrase)))
998 (plaintext ciphertext result recipients &optional passphrase armor textmode)
999 "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
1000 RECIPIENTS is a list of key IDs used for encryption. Returns t if
1001 everything worked out well, nil otherwise. Consult buffer RESULT for
1002 details. ARMOR the result and activate canonical
1003 TEXTMODE if requested."
1005 (read-buffer "Buffer containing plaintext: " nil t)
1006 (read-buffer "Buffer for ciphertext: " nil t)
1007 (read-buffer "Buffer for status informationt: " nil t)
1008 (gpg-read-recipients)))
1009 (let ((subst `((plaintext-file . stdin-file)
1010 (recipients . ,(gpg-build-flag-recipients recipients))
1011 (armor ,(if armor gpg-command-flag-armor))
1012 (textmode ,(if armor gpg-command-flag-textmode)))))
1013 (gpg-call-process (gpg-exec-path gpg-command-encrypt)
1014 (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
1015 plaintext ciphertext result nil))
1017 (gpg-passphrase-clear-string passphrase)))
1022 ;;; ADT: OpenPGP Key
1024 (defun gpg-key-make (user-id key-id unique-id length algorithm
1025 creation-date expire-date validity trust)
1026 "Create a new key object (for internal use only)."
1029 user-id key-id unique-id length algorithm
1031 creation-date expire-date validity trust))
1034 (defun gpg-key-p (key)
1035 "Return t if KEY is a key specification."
1036 (and (arrayp key) (equal (length key) 9) key))
1038 (defmacro gpg-key-primary-user-id (key)
1039 "The primary user ID for KEY (human-readable).
1040 DO NOT USE this ID for selecting recipients. It is probably not
1042 (list 'car (list 'aref key 0)))
1044 (defmacro gpg-key-user-ids (key)
1045 "A list of additional user IDs for KEY (human-readable).
1046 DO NOT USE these IDs for selecting recipients. They are probably not
1048 (list 'cdr (list 'aref key 0)))
1050 (defmacro gpg-key-id (key)
1052 DO NOT USE this ID for selecting recipients. It is not guaranteed to
1056 (defun gpg-short-key-id (key)
1057 "The short key ID of KEY."
1058 (let* ((id (gpg-key-id key))
1061 (substring id (- len 8))
1064 (defmacro gpg-key-unique-id (key)
1065 "A non-standard ID of KEY which is only valid locally.
1066 This ID can be used to specify recipients in a safe manner. Note,
1067 even this ID might not be unique unless GnuPG is used."
1070 (defmacro gpg-key-unique-id-list (key-list)
1071 "Like `gpg-key-unique-id', but operate on a list."
1072 `(mapcar (lambda (key) (gpg-key-unique-id key))
1075 (defmacro gpg-key-length (key)
1076 "Returns the key length."
1079 (defmacro gpg-key-algorithm (key)
1080 "The encryption algorithm used by KEY.
1081 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1082 `elgamal-encrypt', `dsa'."
1085 (defmacro gpg-key-creation-date (key)
1086 "A string with the creation date of KEY in ISO format."
1089 (defmacro gpg-key-expire-date (key)
1090 "A string with the expiration date of KEY in ISO format."
1093 (defmacro gpg-key-validity (key)
1094 "The calculated validity of KEY.
1095 One of the symbols `not-known', `disabled', `revoked', `expired',
1096 `undefined', `trust-none', `trust-marginal', `trust-full',
1097 `trust-ultimate' (see the GnuPG documentation for details)."
1100 (defmacro gpg-key-trust (key)
1101 "The assigned trust for KEY.
1102 One of the symbols `not-known', `undefined', `trust-none',
1103 `trust-marginal', `trust-full' (see the GnuPG
1104 documentation for details)."
1107 (defun gpg-key-lessp (a b)
1108 "Returns t if primary user ID of A is less than B."
1109 (string-lessp (gpg-key-primary-user-id a) (gpg-key-primary-user-id b) ))
1111 ;;; Accessing the key database:
1113 ;; Internal functions:
1115 (defmacro gpg-key-list-keys-skip-field ()
1116 '(search-forward ":" eol 'move))
1118 (defmacro gpg-key-list-keys-get-field ()
1119 '(buffer-substring (point) (if (gpg-key-list-keys-skip-field)
1122 (defmacro gpg-key-list-keys-string-field ()
1123 '(gpg-key-list-keys-get-field))
1125 (defmacro gpg-key-list-keys-read-field ()
1126 (let ((field (make-symbol "field")))
1127 `(let ((,field (gpg-key-list-keys-get-field)))
1128 (if (equal (length ,field) 0)
1132 (defun gpg-key-list-keys-parse-line ()
1133 "Parse the line in the current buffer and return a vector of fields."
1134 (let* ((eol (gpg-point-at-eol))
1138 (gpg-key-list-keys-read-field) ; type
1139 (gpg-key-list-keys-get-field) ; trust
1140 (gpg-key-list-keys-read-field) ; key length
1141 (gpg-key-list-keys-read-field) ; algorithm
1142 (gpg-key-list-keys-get-field) ; key ID
1143 (gpg-key-list-keys-get-field) ; creation data
1144 (gpg-key-list-keys-get-field) ; expire
1145 (gpg-key-list-keys-get-field) ; unique (local) ID
1146 (gpg-key-list-keys-get-field) ; ownertrust
1147 (gpg-key-list-keys-string-field) ; user ID
1152 (error "Too many fields in GnuPG key database"))
1155 (defconst gpg-pubkey-algo-alist
1157 (2 . rsa-encrypt-only)
1159 (16 . elgamal-encrypt-only)
1162 "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1164 (defconst gpg-trust-alist
1170 (?q . trust-undefined)
1172 (?m . trust-marginal)
1174 (?u . trust-ultimate))
1175 "Alist mapping GnuPG trust value short forms to long symbols.")
1177 (defmacro gpg-key-list-keys-in-buffer-store ()
1178 '(when primary-user-id
1179 (sort user-id 'string-lessp)
1180 (push (gpg-key-make (cons primary-user-id user-id)
1181 key-id unique-id key-length
1182 algorithm creation-date
1183 expire-date validity trust)
1186 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1187 "Return a list of keys for BUFFER.
1188 If BUFFER is omitted, use current buffer."
1189 (with-current-buffer (if buffer buffer (current-buffer))
1190 (goto-char (point-min))
1191 ;; Skip key ring filename written by GnuPG.
1192 (search-forward "\n---------------------------\n" nil t)
1193 ;; Loop over all lines in buffer and analyze them.
1194 (let (primary-user-id user-id key-id unique-id ; current key components
1195 key-length algorithm creation-date expire-date validity trust
1196 line ; fields in current line
1197 key-list) ; keys gather so far
1199 (while (setq line (gpg-key-list-keys-parse-line))
1201 ;; Public or secret key.
1202 ((memq (aref line 0) '(pub sec))
1203 ;; Store previous key, if any.
1204 (gpg-key-list-keys-in-buffer-store)
1205 ;; Record field values.
1206 (setq primary-user-id (aref line 9))
1208 (setq key-id (aref line 4))
1209 ;; We use the key ID if no unique ID is available.
1210 (setq unique-id (if (> (length (aref line 7)) 0)
1211 (concat "#" (aref line 7))
1212 (concat "0x" key-id)))
1213 (setq key-length (aref line 2))
1214 (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1216 (setq algorithm (cdr algorithm))
1217 (error "Unknown algorithm %s" (aref line 3)))
1218 (setq creation-date (if (> (length (aref line 5)) 0)
1220 (setq expire-date (if (> (length (aref line 6)) 0)
1222 (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1224 (setq validity (cdr validity))
1225 (error "Unknown validity specification %S" (aref line 1)))
1226 (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1228 (setq trust (cdr trust))
1229 (error "Unknown trust specification %S" (aref line 8))))
1231 ;; Additional user ID
1232 ((eq 'uid (aref line 0))
1233 (setq user-id (cons (aref line 9) user-id)))
1235 ;; Subkeys are ignored for now.
1236 ((memq (aref line 0) '(sub ssb))
1238 (t (error "Unknown record type %S" (aref line 0)))))
1240 ;; Store the key retrieved last.
1241 (gpg-key-list-keys-in-buffer-store)
1242 ;; Sort the keys according to the primary user ID.
1243 (sort key-list 'gpg-key-lessp))))
1245 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1246 "Insert the output of COMMAND before point in current buffer."
1247 (let* ((cmd (gpg-exec-path command))
1248 (key (if (equal keyspec "") nil keyspec))
1249 (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1252 (apply 'call-process-region
1253 (point-min) (point-min) ; no data
1256 (if stderr t '(t nil))
1259 (unless (or ignore-error (equal exit-status 0))
1260 (error "GnuPG command exited unsuccessfully"))))
1263 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1264 "Return a list of keys matching KEYSPEC.
1265 COMMAND is used to obtain the key list. The usual substring search
1266 for keys is performed."
1268 (buffer-disable-undo)
1269 (gpg-key-list-keyspec command keyspec)
1270 (gpg-key-list-keys-in-buffer)))
1273 (defun gpg-key-list-keys (&optional keyspec)
1274 "A list of public keys matching KEYSPEC.
1275 The usual substring search for keys is performed."
1276 (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1279 (defun gpg-key-list-secret-keys (&optional keyspec)
1280 "A list of secret keys matching KEYSPEC.
1281 The usual substring search for keys is performed."
1282 (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1285 (defun gpg-key-insert-public-key (key)
1286 "Inserts the public key(s) matching KEYSPEC.
1287 The ASCII-armored key is inserted before point into current buffer."
1288 (gpg-key-list-keyspec gpg-command-key-export key))
1291 (defun gpg-key-insert-information (key)
1292 "Insert human-readable information (including fingerprint) on KEY.
1293 Insertion takes place in current buffer before point."
1294 (gpg-key-list-keyspec gpg-command-key-verify key))
1297 (defun gpg-key-retrieve (key)
1298 "Fetch KEY from default key server.
1299 KEY is a key ID or a list of key IDs. Status information about this
1300 operation is inserted into the current buffer before point."
1301 (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1304 (defun gpg-key-add-to-ring (key result)
1305 "Adds key in buffer KEY to the GnuPG key ring.
1306 Human-readable information on the RESULT is stored in buffer RESULT
1311 ;;; gpg.el ends here