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 ;; * Optionally, Gero Treuner's gpg-2comp script is supported,
43 ;; to generate data which is compatible with PGP 2.6.3.
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).
110 (eval-when-compile (require 'cl))
113 (defalias 'gpg-point-at-eol
114 (if (fboundp 'point-at-eol)
116 'line-end-position)))
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
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-2comp\"
232 for `gpg-2comp' if you have obtained this script, in order to gain
233 PGP 2.6.x compatibility."
234 :tag "GnuPG programs"
235 :type 'gpg-command-alist
238 (defcustom gpg-command-all-arglist
240 "List of arguments to add to all GPG commands."
241 :tag "All command args"
244 (defcustom gpg-command-flag-textmode "--textmode"
245 "The flag to indicate canonical text mode to GnuPG."
246 :tag "Text mode flag"
250 (defcustom gpg-command-flag-armor "--armor"
251 "The flag to request ASCII-armoring output from GnuPG."
256 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
257 "String to include to specify the signing key ID.
258 The elements are concatenated (without spaces) to form a command line
260 :tag "Sign with key flag"
261 :type '(repeat :tag "Argument parts"
262 (choice :format "%[Type%] %v"
263 (const :tag "Start next argument." :value next-argument)
264 (const :tag "Insert signing key ID here." :value sign-with-key)
268 (defcustom gpg-command-flag-recipient
269 '(nil . ("-r" next-argument recipient next-argument))
270 "Format of a recipient specification.
271 The elements are concatenated (without spaces) to form a command line
272 option. The second part is repeated for each recipient."
273 :tag "Recipients Flag"
275 (repeat :tag "Common prefix"
276 (choice :format "%[Type%] %v"
277 (const :tag "Start next argument." :value next-argument)
279 (repeat :tag "For each recipient"
280 (choice :format "%[Type%] %v"
281 (const :tag "Start next argument." :value next-argument)
282 (const :tag "Insert recipient key ID here." :value recipient)
286 (defcustom gpg-command-passphrase-env
288 "Environment variable to set when a passphrase is required, or nil.
289 If an operation is invoked which requires a passphrase, this
290 environment variable is set before calling the external program to
291 indicate that it should read the passphrase from standard input."
292 :tag "Passphrase environment"
294 (const :tag "Disabled" :value nil)
296 (string :tag "Variable")
297 (string :tag "Value")))
300 ;;; Customization: Variables: GnuPG Commands:
302 (defcustom gpg-command-verify
303 '(gpg . ("--status-fd" "1" "--batch" "--verbose" "--verify" signature-file message-file))
304 "Command to verify a detached signature.
305 The invoked program has to read the signed message and the signature
306 from the given files. It should write human-readable information to
307 standard output and/or standard error. The program shall not convert
308 charsets or line endings; the input data shall be treated as binary."
309 :tag "Verify Command"
315 :format "%[Type%] %v"
316 (const :tag "Insert name of file containing the message here."
318 (const :tag "Insert name of file containing the signature here."
319 :value signature-file)
320 (string :format "%v"))))
321 :group 'gpg-commands)
323 (defcustom gpg-command-verify-cleartext
324 '(gpg . ("--status-fd" "1" "--batch" "--verbose" "--verify" message-file))
325 "Command to verify a message.
326 The invoked program has to read the signed message from the given
327 file. It should write human-readable information to standard output
328 and/or standard error. The program shall not convert charsets or line
329 endings; the input data shall be treated as binary."
330 :tag "Cleartext Verify Command"
336 :format "%[Type%] %v"
337 (const :tag "Insert name of file containing the message here."
339 (string :format "%v"))))
340 :group 'gpg-commands)
342 (defcustom gpg-command-decrypt
343 '(gpg . ("--status-fd" "2" "--decrypt" "--batch" "--passphrase-fd=0"))
344 "Command to decrypt a message.
345 The invoked program has to read the passphrase from standard
346 input, followed by the encrypted message. It writes the decrypted
347 message to standard output, and human-readable diagnostic messages to
349 :tag "Decrypt Command"
355 :format "%[Type%] %v"
356 (const :tag "Insert name of file containing the message here."
358 (string :format "%v"))))
359 :group 'gpg-commands)
361 (defcustom gpg-command-sign-cleartext
362 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
363 armor textmode "--clearsign"
365 "Command to create a \"clearsign\" text file.
366 The invoked program has to read the passphrase from standard input,
367 followed by the message to sign. It should write the ASCII-amored
368 signed text message to standard output, and diagnostic messages to
370 :tag "Clearsign Command"
371 :type 'gpg-command-sign-options
372 :group 'gpg-commands)
374 (defcustom gpg-command-sign-detached
375 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
376 armor textmode "--detach-sign"
378 "Command to create a detached signature.
379 The invoked program has to read the passphrase from standard input,
380 followed by the message to sign. It should write the ASCII-amored
381 detached signature to standard output, and diagnostic messages to
382 standard error. The program shall not convert charsets or line
383 endings; the input data shall be treated as binary."
384 :tag "Sign Detached Command"
385 :type 'gpg-command-sign-options
386 :group 'gpg-commands)
388 (defcustom gpg-command-sign-encrypt
389 '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
390 armor textmode "--always-trust" sign-with-key recipients
391 "--sign" "--encrypt" plaintext-file))
392 "Command to sign and encrypt a file.
393 The invoked program has to read the passphrase from standard input,
394 followed by the message to sign and encrypt if there is no
395 `plaintext-file' placeholder. It should write the ASCII-amored
396 encrypted message to standard output, and diagnostic messages to
398 :tag "Sign And Encrypt Command"
404 :format "%[Type%] %v"
405 (const :tag "Insert the `sign with key' option here if necessary."
406 :value sign-with-key)
407 (const :tag "Insert list of recipients here."
409 (const :tag "Insert here name of file with plaintext."
410 :value plaintext-file)
411 (string :format "%v"))))
412 :group 'gpg-commands)
414 (defcustom gpg-command-encrypt
415 '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust"
416 "--encrypt" recipients plaintext-file))
417 "Command to encrypt a file.
418 The invoked program has to read the message to encrypt from standard
419 input or from the plaintext file (if the `plaintext-file' placeholder
420 is present). It should write the ASCII-amored encrypted message to
421 standard output, and diagnostic messages to standard error."
427 :format "%[Type%] %v"
428 (const :tag "Insert list of recipients here."
430 (const :tag "Insert here name of file with plaintext."
431 :value plaintext-file)
432 (string :format "%v"))))
433 :group 'gpg-commands)
435 ;;; Customization: Variables: Key Management Commands:
437 (defcustom gpg-command-key-import
438 '(gpg . ("--import" "--verbose" message-file))
439 "Command to import a public key from a file."
440 :tag "Import Command"
446 :format "%[Type%] %v"
447 (const :tag "Insert name of file containing the key here."
449 (string :format "%v"))))
450 :group 'gpg-commands-key)
452 (defcustom gpg-command-key-export
453 '(gpg . ("--no-verbose" "--armor" "--export" key-id))
454 "Command to export a public key from the key ring.
455 The key should be written to standard output using ASCII armor."
456 :tag "Export Command"
457 :type 'gpg-command-key-options
458 :group 'gpg-commands-key)
460 (defcustom gpg-command-key-verify
461 '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
462 "Command to verify a public key."
463 :tag "Verification Command"
464 :type 'gpg-command-key-options
465 :group 'gpg-commands-key)
467 (defcustom gpg-command-key-public-ring
468 '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
469 "Command to list the contents of the public key ring."
470 :tag "List Public Key Ring Command"
471 :type 'gpg-command-key-options
472 :group 'gpg-commands-key)
474 (defcustom gpg-command-key-secret-ring
475 '(gpg . ("--no-verbose" "--batch" "--with-colons"
476 "--list-secret-keys" key-id))
477 "Command to list the contents of the secret key ring."
478 :tag "List Secret Key Ring Command"
479 :type 'gpg-command-key-options
480 :group 'gpg-commands-key)
482 (defcustom gpg-command-key-retrieve
483 '(gpg . ("--batch" "--recv-keys" key-id))
484 "Command to retrieve public keys."
485 :tag "Retrieve Keys Command"
486 :type 'gpg-command-key-options
487 :group 'gpg-commands-key)
490 ;;;; Helper functions for GnuPG invocation:
492 ;;; Build the GnuPG command line:
494 (defun gpg-build-argument (template substitutions &optional pass-start)
495 "Build command line argument(s) by substituting placeholders.
496 TEMPLATE is a list of strings and symbols. The placeholder symbols in
497 it are replaced by SUBSTITUTIONS, the elements between
498 `next-argument' symbols are concatenated without spaces and are
501 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
502 a string (which is inserted literally), a list of strings (which are
503 inserted as well), or nil, which means to insert nothing.
505 If PASS-START is t, `next-argument' is also inserted into the result,
506 and symbols without a proper substitution are retained in the output,
507 otherwise, an untranslated symbol results in an error.
509 This function does not handle empty arguments reliably."
510 (let ((current-arg "")
513 (let* ((templ (pop template))
514 (repl (assoc templ substitutions))
515 (new (if repl (cdr repl) templ)))
517 ((eq templ 'next-argument)
518 ;; If the current argument is not empty, start a new one.
519 (unless (equal current-arg "")
520 (setq arglist (nconc arglist
522 (list current-arg 'next-argument)
523 (list current-arg))))
524 (setq current-arg "")))
525 ((null new) nil) ; Drop it.
526 ((and (not (stringp templ)) (null repl))
527 ;; Retain an untranslated symbol in the output if
528 ;; `pass-start' is true.
530 (error "No replacement for `%s'" templ))
531 (setq arglist (nconc arglist (list current-arg templ)))
532 (setq current-arg ""))
535 (setq new (list new)))
536 (setq current-arg (concat current-arg
537 (apply 'concat new)))))))
538 (unless (equal current-arg "")
539 (setq arglist (nconc arglist (list current-arg))))
542 (defun gpg-build-arg-list (template substitutions)
543 "Build command line by substituting placeholders.
544 TEMPLATE is a list of strings and symbols. The placeholder symbols in
545 it are replaced by SUBSTITUTIONS.
547 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
548 string (which is inserted literally), a list of strings (which are
549 inserted as well), or nil, which means to insert nothing."
550 (let ((arglist (copy-sequence gpg-command-all-arglist)))
552 (let* ((templ (pop template))
553 (repl (assoc templ substitutions))
554 (new (if repl (cdr repl) templ)))
556 ((and (symbolp templ) (null repl))
557 (error "No replacement for `%s'" templ))
558 ((null new) nil) ; Drop it.
561 (setq new (list new)))
562 (setq arglist (nconc arglist new))))))
565 (defun gpg-build-flag-recipients-one (recipient)
566 "Build argument for one RECIPIENT."
567 (gpg-build-argument (cdr gpg-command-flag-recipient)
568 `((recipient . ,recipient)) t))
570 (defun gpg-build-flag-recipients (recipients)
571 "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
573 (apply 'append (car gpg-command-flag-recipient)
574 (mapcar 'gpg-build-flag-recipients-one
578 (defun gpg-read-recipients ()
579 "Query the user for several recipients."
583 (setq r (read-string "Enter recipient ID [RET when no more]: "))
586 (setq recipients (nconc recipients (list r)))))
589 (defun gpg-build-flag-sign-with-key (key)
590 "Build sign with key flag using `gpg-command-flag-sign-with-key'."
592 (if gpg-default-key-id gpg-default-key-id
595 (gpg-build-argument gpg-command-flag-sign-with-key
596 (list (cons 'sign-with-key k)))
599 (defmacro gpg-with-passphrase-env (&rest body)
600 "Adjust the process environment and evaluate BODY.
601 During the evaluation of the body forms, the process environment is
602 adjust according to `gpg-command-passphrase-env'."
603 (let ((env-value (make-symbol "env-value")))
607 (when gpg-command-passphrase-env
608 (setq ,env-value (getenv (car gpg-command-passphrase-env)))
609 (setenv (car gpg-command-passphrase-env)
610 (cdr gpg-command-passphrase-env)))
612 (when gpg-command-passphrase-env
613 ;; This will clear the variable if it wasn't set before.
614 (setenv (car gpg-command-passphrase-env) ,env-value))))))
615 (put 'gpg-with-passphrase-env 'lisp-indent-function 0)
616 (put 'gpg-with-passphrase-env 'edebug-form-spec '(body))
620 (defun gpg-make-temp-file ()
621 "Create a temporary file in a safe way"
622 (let ((name ;; User may use "~/"
623 (expand-file-name "gnupg" gpg-temp-directory)))
624 (if (fboundp 'make-temp-file)
625 ;; If we've got make-temp-file, we are on the save side.
626 (make-temp-file name)
627 ;; make-temp-name doesn't create the file, and an ordinary
628 ;; write-file operation is prone to nasty symlink attacks if the
629 ;; temporary file resides in a world-writable directory.
630 (unless (or (memq system-type '(windows-nt cygwin32 win32 w32 mswindows))
631 (eq (file-modes gpg-temp-directory) 448)) ; mode 0700
632 (error "Directory for temporary files (%s) must have mode 0700" gpg-temp-directory))
633 (setq name (make-temp-name name))
634 (let ((mode (default-file-modes)))
637 (set-default-file-modes 384) ; mode 0600
638 (with-temp-file name))
639 (set-default-file-modes mode)))
642 (defvar gpg-temp-files nil
643 "List of temporary files used by the GnuPG interface.
644 Do not set this variable. Call `gpg-with-temp-files' if you need
647 (defun gpg-with-temp-files-create (count)
648 "Do not call this function. Used internally by `gpg-with-temp-files'."
650 (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
651 (setq count (1- count))))
653 (defun gpg-with-temp-files-delete ()
654 "Do not call this function. Used internally by `gpg-with-temp-files'."
655 (while gpg-temp-files
656 (let ((file (pop gpg-temp-files)))
661 (defmacro gpg-with-temp-files (count &rest body)
662 "Create COUNT temporary files, USE them, and delete them.
663 The function USE is called with the names of all temporary files as
665 `(let ((gpg-temp-files))
668 ;; Create the temporary files.
669 (gpg-with-temp-files-create ,count)
671 (gpg-with-temp-files-delete))))
672 (put 'gpg-with-temp-files 'lisp-indent-function 1)
673 (put 'gpg-with-temp-files 'edebug-form-spec '(body))
675 ;;; Making subprocesses:
677 (defun gpg-exec-path (option)
678 "Return the program name for OPTION.
679 OPTION is of the form (PROGRAM . ARGLIST). This functions returns
680 PROGRAM, but takes default values into account."
681 (let* ((prg (car option))
682 (path (assq prg gpg-command-default-alist)))
684 (path (if (null (cdr path))
685 (error "Command `%s' is not available" prg)
687 ((null prg) (error "Command is disabled"))
690 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
691 "Invoke external program CMD with ARGS on buffer STDIN.
692 Standard output is insert before point in STDOUT, standard error in
693 STDERR. If PASSPHRASE is given, send it before STDIN. PASSPHRASE
694 should not end with a line feed (\"\\n\").
696 If `stdin-file' is present in ARGS, it is replaced by the name of a
697 temporary file. Before invoking CMD, the contents of STDIN is written
699 (gpg-with-temp-files 2
700 (let* ((coding-system-for-read 'no-conversion)
701 (coding-system-for-write 'no-conversion)
702 (have-stdin-file (memq 'stdin-file args))
703 (stdin-file (nth 0 gpg-temp-files))
704 (stderr-file (nth 1 gpg-temp-files))
707 (,stdout ,stderr-file)
709 ;; Replace `stdin-file'.
710 ,@(gpg-build-arg-list
711 args (list (cons 'stdin-file stdin-file)))))
713 (when have-stdin-file
714 (with-temp-file stdin-file
715 (buffer-disable-undo)
716 (insert-buffer-substring stdin)))
720 (buffer-disable-undo)
721 (insert passphrase "\n")
722 (unless have-stdin-file
723 (apply 'insert-buffer-substring
724 (if (listp stdin) stdin (list stdin))))
725 (apply 'call-process-region (point-min) (point-max) cpr-args)
726 ;; Wipe out passphrase.
727 (goto-char (point-min))
728 (translate-region (point) (gpg-point-at-eol)
729 (make-string 256 ? )))
731 (with-current-buffer (car stdin)
732 (apply 'call-process-region
734 (if have-stdin-file (cadr stdin) (caddr stdin))
736 (with-current-buffer stdin
737 (apply 'call-process-region
739 (if have-stdin-file (point-min) (point-max))
741 (with-current-buffer stderr
742 (insert-file-contents-literally stderr-file))
743 (if (or (stringp res) (> res 0))
744 ;; Signal or abnormal exit.
745 (with-current-buffer stderr
746 (goto-char (point-max))
747 (insert (format "\nCommand exit status: %s\n" res))
751 (defvar gpg-result-buffer nil
752 "The result of a GnuPG operation is stored in this buffer.
753 Never set this variable directly, use `gpg-show-result' instead.")
755 (defun gpg-show-result-buffer (always-show result)
756 "Called by `gpg-show-results' to actually show the buffer."
757 (with-current-buffer gpg-result-buffer
758 ;; Only proceed if the buffer is non-empty.
759 (when (and (/= (point-min) (point-max))
760 (or always-show (not result)))
761 (save-window-excursion
762 (display-buffer (current-buffer))
763 (unless (y-or-n-p "Continue? ")
764 (error "GnuPG operation aborted"))))))
766 (defmacro gpg-show-result (always-show &rest body)
767 "Show GnuPG result to user for confirmation.
768 This macro binds `gpg-result-buffer' to a temporary buffer and
769 evaluates BODY, like `progn'. If BODY evaluates to `nil' (or
770 `always-show' is not nil), the user is asked for confirmation."
771 `(let ((gpg-result-buffer (get-buffer-create
772 (generate-new-buffer-name "*GnuPG Output*"))))
774 (gpg-show-result-buffer ,always-show (progn ,@body))
775 (kill-buffer gpg-result-buffer))))
776 (put 'gpg-show-result 'lisp-indent-function 1)
777 (put 'gpg-show-result 'edebug-form-spec '(body))
779 ;;; Passphrase handling:
781 (defvar gpg-passphrase-timer
783 "This timer will clear the passphrase cache periodically.")
785 (defvar gpg-passphrase
787 "The (unencrypted) passphrase cache.")
789 (defun gpg-passphrase-clear-string (str)
790 "Erases STR by overwriting all characters."
798 (defun gpg-passphrase-forget ()
799 "Forget stored passphrase."
802 (cancel-timer gpg-passphrase-timer)
803 (setq gpg-passphrase-timer nil)
804 (gpg-passphrase-clear-string gpg-passphrase)
805 (setq gpg-passphrase nil)))
807 (defun gpg-passphrase-store (passphrase)
808 "Store PASSPHRASE in cache.
809 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
810 (unless (equal gpg-passphrase-timeout 0)
811 (if (null gpg-passphrase-timer)
812 (setq gpg-passphrase-timer (timer-create)))
813 (timer-set-time gpg-passphrase-timer
814 (timer-relative-time (current-time)
815 gpg-passphrase-timeout))
816 (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
817 (unless (and (fboundp 'itimer-live-p)
818 (itimer-live-p gpg-passphrase-timer))
819 (timer-activate gpg-passphrase-timer))
820 (setq gpg-passphrase passphrase))
823 (defun gpg-passphrase-read ()
824 "Read a passphrase and remember it for some time."
827 ;; This reinitializes the timer.
828 (gpg-passphrase-store gpg-passphrase)
829 (let ((pp (read-passwd "Enter passphrase: ")))
830 (gpg-passphrase-store pp))))
833 ;;;; Main operations:
836 (defun gpg-verify (message signature result)
837 "Verify buffer MESSAGE against detached SIGNATURE buffer.
838 Returns t if everything worked out well, nil otherwise. Consult
839 buffer RESULT for details."
840 (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
841 (gpg-with-temp-files 2
842 (let* ((sig-file (nth 0 gpg-temp-files))
843 (msg-file (nth 1 gpg-temp-files))
844 (cmd (gpg-exec-path gpg-command-verify))
845 (args (gpg-build-arg-list (cdr gpg-command-verify)
846 `((signature-file . ,sig-file)
847 (message-file . ,msg-file))))
849 (with-temp-file sig-file
850 (buffer-disable-undo)
851 (apply 'insert-buffer-substring (if (listp signature)
854 (with-temp-file msg-file
855 (buffer-disable-undo)
856 (apply 'insert-buffer-substring (if (listp message)
859 (setq res (apply 'call-process-region
860 (point-min) (point-min) ; no data
866 (if (or (stringp res) (> res 0))
867 ;; Signal or abnormal exit.
868 (with-current-buffer result
869 (insert (format "\nCommand exit status: %s\n" res))
874 (defun gpg-verify-cleartext (message result)
875 "Verify message in buffer MESSAGE.
876 Returns t if everything worked out well, nil otherwise. Consult
877 buffer RESULT for details.
879 NOTE: Use of this function is deprecated."
880 (interactive "bBuffer containing message: \nbBuffor for result: ")
881 (gpg-with-temp-files 1
882 (let* ((msg-file (nth 0 gpg-temp-files))
883 (cmd (gpg-exec-path gpg-command-verify-cleartext))
884 (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext)
885 `((message-file . ,msg-file))))
887 (with-temp-file msg-file
888 (buffer-disable-undo)
889 (apply 'insert-buffer-substring (if (listp message)
892 (setq res (apply 'call-process-region
893 (point-min) (point-min) ; no data
899 (if (or (stringp res) (> res 0))
900 ;; Signal or abnormal exit.
901 (with-current-buffer result
902 (insert (format "\nCommand exit status: %s\n" res))
907 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
908 "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
909 Returns t if everything worked out well, nil otherwise. Consult
910 buffer RESULT for details. Reads a missing PASSPHRASE using
911 `gpg-passphrase-read'."
912 (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
913 (gpg-call-process (gpg-exec-path gpg-command-decrypt)
914 (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
915 ciphertext plaintext result
916 (if passphrase passphrase (gpg-passphrase-read)))
918 (gpg-passphrase-clear-string passphrase)))
921 (defun gpg-sign-cleartext
922 (plaintext signed-text result &optional passphrase sign-with-key)
923 "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
925 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
926 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
927 everything worked out well, nil otherwise. Consult buffer RESULT for
930 NOTE: Use of this function is deprecated."
931 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
932 (let ((subst (list (cons 'sign-with-key
933 (gpg-build-flag-sign-with-key sign-with-key))
934 (cons 'armor gpg-command-flag-armor)
935 (cons 'textmode gpg-command-flag-textmode))))
936 (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
937 (gpg-build-arg-list (cdr gpg-command-sign-cleartext)
939 plaintext signed-text result
940 (if passphrase passphrase (gpg-passphrase-read))))
942 (gpg-passphrase-clear-string passphrase)))
945 (defun gpg-sign-detached
946 (plaintext signature result &optional passphrase sign-with-key
948 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
949 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
950 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
951 everything worked out well, nil otherwise. Consult buffer RESULT for
952 details. ARMOR the result and activate canonical TEXTMODE if
954 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
955 (let ((subst (list (cons 'sign-with-key
956 (gpg-build-flag-sign-with-key sign-with-key))
957 (cons 'armor (if armor gpg-command-flag-armor))
958 (cons 'textmode (if armor gpg-command-flag-textmode)))))
959 (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
960 (gpg-build-arg-list (cdr gpg-command-sign-detached)
962 plaintext signature result
963 (if passphrase passphrase (gpg-passphrase-read))))
965 (gpg-passphrase-clear-string passphrase)))
969 (defun gpg-sign-encrypt
970 (plaintext ciphertext result recipients &optional passphrase sign-with-key
972 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
973 RECIPIENTS is a list of key IDs used for encryption. This function
974 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
975 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
976 ID. Returns t if everything worked out well, nil otherwise. Consult
977 buffer RESULT for details. ARMOR the result and activate canonical
978 TEXTMODE if requested."
980 (read-buffer "Buffer containing plaintext: " nil t)
981 (read-buffer "Buffer for ciphertext: " nil t)
982 (read-buffer "Buffer for status informationt: " nil t)
983 (gpg-read-recipients)))
984 (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key
986 (plaintext-file . stdin-file)
987 (recipients . ,(gpg-build-flag-recipients recipients))
988 (armor ,(if armor gpg-command-flag-armor))
989 (textmode ,(if armor gpg-command-flag-textmode)))))
990 (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
991 (gpg-build-arg-list (cdr gpg-command-sign-encrypt)
993 plaintext ciphertext result
994 (if passphrase passphrase (gpg-passphrase-read))))
996 (gpg-passphrase-clear-string passphrase)))
1001 (plaintext ciphertext result recipients &optional passphrase armor textmode)
1002 "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
1003 RECIPIENTS is a list of key IDs used for encryption. Returns t if
1004 everything worked out well, nil otherwise. Consult buffer RESULT for
1005 details. ARMOR the result and activate canonical
1006 TEXTMODE if requested."
1008 (read-buffer "Buffer containing plaintext: " nil t)
1009 (read-buffer "Buffer for ciphertext: " nil t)
1010 (read-buffer "Buffer for status informationt: " nil t)
1011 (gpg-read-recipients)))
1012 (let ((subst `((plaintext-file . stdin-file)
1013 (recipients . ,(gpg-build-flag-recipients recipients))
1014 (armor ,(if armor gpg-command-flag-armor))
1015 (textmode ,(if armor gpg-command-flag-textmode)))))
1016 (gpg-call-process (gpg-exec-path gpg-command-encrypt)
1017 (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
1018 plaintext ciphertext result nil))
1020 (gpg-passphrase-clear-string passphrase)))
1025 ;;; ADT: OpenPGP Key
1027 (defun gpg-key-make (user-id key-id unique-id length algorithm
1028 creation-date expire-date validity trust)
1029 "Create a new key object (for internal use only)."
1032 user-id key-id unique-id length algorithm
1034 creation-date expire-date validity trust))
1037 (defun gpg-key-p (key)
1038 "Return t if KEY is a key specification."
1039 (and (arrayp key) (equal (length key) 9) key))
1041 (defmacro gpg-key-primary-user-id (key)
1042 "The primary user ID for KEY (human-readable).
1043 DO NOT USE this ID for selecting recipients. It is probably not
1045 (list 'car (list 'aref key 0)))
1047 (defmacro gpg-key-user-ids (key)
1048 "A list of additional user IDs for KEY (human-readable).
1049 DO NOT USE these IDs for selecting recipients. They are probably not
1051 (list 'cdr (list 'aref key 0)))
1053 (defmacro gpg-key-id (key)
1055 DO NOT USE this ID for selecting recipients. It is not guaranteed to
1059 (defun gpg-short-key-id (key)
1060 "The short key ID of KEY."
1061 (let* ((id (gpg-key-id key))
1064 (substring id (- len 8))
1067 (defmacro gpg-key-unique-id (key)
1068 "A non-standard ID of KEY which is only valid locally.
1069 This ID can be used to specify recipients in a safe manner. Note,
1070 even this ID might not be unique unless GnuPG is used."
1073 (defmacro gpg-key-unique-id-list (key-list)
1074 "Like `gpg-key-unique-id', but operate on a list."
1075 `(mapcar (lambda (key) (gpg-key-unique-id key))
1078 (defmacro gpg-key-length (key)
1079 "Returns the key length."
1082 (defmacro gpg-key-algorithm (key)
1083 "The encryption algorithm used by KEY.
1084 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1085 `elgamal-encrypt', `dsa'."
1088 (defmacro gpg-key-creation-date (key)
1089 "A string with the creation date of KEY in ISO format."
1092 (defmacro gpg-key-expire-date (key)
1093 "A string with the expiration date of KEY in ISO format."
1096 (defmacro gpg-key-validity (key)
1097 "The calculated validity of KEY.
1098 One of the symbols `not-known', `disabled', `revoked', `expired',
1099 `undefined', `trust-none', `trust-marginal', `trust-full',
1100 `trust-ultimate' (see the GnuPG documentation for details)."
1103 (defmacro gpg-key-trust (key)
1104 "The assigned trust for KEY.
1105 One of the symbols `not-known', `undefined', `trust-none',
1106 `trust-marginal', `trust-full' (see the GnuPG
1107 documentation for details)."
1110 (defun gpg-key-lessp (a b)
1111 "Returns t if primary user ID of A is less than B."
1112 (string-lessp (gpg-key-primary-user-id a) (gpg-key-primary-user-id b) ))
1114 ;;; Accessing the key database:
1116 ;; Internal functions:
1118 (defmacro gpg-key-list-keys-skip-field ()
1119 '(search-forward ":" eol 'move))
1121 (defmacro gpg-key-list-keys-get-field ()
1122 '(buffer-substring (point) (if (gpg-key-list-keys-skip-field)
1125 (defmacro gpg-key-list-keys-string-field ()
1126 '(gpg-key-list-keys-get-field))
1128 (defmacro gpg-key-list-keys-read-field ()
1129 (let ((field (make-symbol "field")))
1130 `(let ((,field (gpg-key-list-keys-get-field)))
1131 (if (equal (length ,field) 0)
1135 (defun gpg-key-list-keys-parse-line ()
1136 "Parse the line in the current buffer and return a vector of fields."
1137 (let* ((eol (gpg-point-at-eol))
1141 (gpg-key-list-keys-read-field) ; type
1142 (gpg-key-list-keys-get-field) ; trust
1143 (gpg-key-list-keys-read-field) ; key length
1144 (gpg-key-list-keys-read-field) ; algorithm
1145 (gpg-key-list-keys-get-field) ; key ID
1146 (gpg-key-list-keys-get-field) ; creation data
1147 (gpg-key-list-keys-get-field) ; expire
1148 (gpg-key-list-keys-get-field) ; unique (local) ID
1149 (gpg-key-list-keys-get-field) ; ownertrust
1150 (gpg-key-list-keys-string-field) ; user ID
1155 (error "Too many fields in GnuPG key database"))
1158 (defconst gpg-pubkey-algo-alist
1160 (2 . rsa-encrypt-only)
1162 (16 . elgamal-encrypt-only)
1165 "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1167 (defconst gpg-trust-alist
1173 (?q . trust-undefined)
1175 (?m . trust-marginal)
1177 (?u . trust-ultimate))
1178 "Alist mapping GnuPG trust value short forms to long symbols.")
1180 (defconst gpg-unabbrev-trust-alist
1181 '(("TRUST_UNDEFINED" . trust-undefined)
1182 ("TRUST_NEVER" . trust-none)
1183 ("TRUST_MARGINAL" . trust-marginal)
1184 ("TRUST_FULLY" . trust-full)
1185 ("TRUST_ULTIMATE" . trust-ultimate))
1186 "Alist mapping capitalized GnuPG trust values to long symbols.")
1188 (defmacro gpg-key-list-keys-in-buffer-store ()
1189 '(when primary-user-id
1190 (sort user-id 'string-lessp)
1191 (push (gpg-key-make (cons primary-user-id user-id)
1192 key-id unique-id key-length
1193 algorithm creation-date
1194 expire-date validity trust)
1197 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1198 "Return a list of keys for BUFFER.
1199 If BUFFER is omitted, use current buffer."
1200 (with-current-buffer (if buffer buffer (current-buffer))
1201 (goto-char (point-min))
1202 ;; Skip key ring filename written by GnuPG.
1203 (search-forward "\n---------------------------\n" nil t)
1204 ;; Loop over all lines in buffer and analyze them.
1205 (let (primary-user-id user-id key-id unique-id ; current key components
1206 key-length algorithm creation-date expire-date validity trust
1207 line ; fields in current line
1208 key-list) ; keys gather so far
1210 (while (setq line (gpg-key-list-keys-parse-line))
1212 ;; Public or secret key.
1213 ((memq (aref line 0) '(pub sec))
1214 ;; Store previous key, if any.
1215 (gpg-key-list-keys-in-buffer-store)
1216 ;; Record field values.
1217 (setq primary-user-id (aref line 9))
1219 (setq key-id (aref line 4))
1220 ;; We use the key ID if no unique ID is available.
1221 (setq unique-id (if (> (length (aref line 7)) 0)
1222 (concat "#" (aref line 7))
1223 (concat "0x" key-id)))
1224 (setq key-length (aref line 2))
1225 (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1227 (setq algorithm (cdr algorithm))
1228 (error "Unknown algorithm %s" (aref line 3)))
1229 (setq creation-date (if (> (length (aref line 5)) 0)
1231 (setq expire-date (if (> (length (aref line 6)) 0)
1233 (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1235 (setq validity (cdr validity))
1236 (error "Unknown validity specification %S" (aref line 1)))
1237 (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1239 (setq trust (cdr trust))
1240 (error "Unknown trust specification %S" (aref line 8))))
1242 ;; Additional user ID
1243 ((eq 'uid (aref line 0))
1244 (setq user-id (cons (aref line 9) user-id)))
1246 ;; Subkeys are ignored for now.
1247 ((memq (aref line 0) '(sub ssb))
1249 (t (error "Unknown record type %S" (aref line 0)))))
1251 ;; Store the key retrieved last.
1252 (gpg-key-list-keys-in-buffer-store)
1253 ;; Sort the keys according to the primary user ID.
1254 (sort key-list 'gpg-key-lessp))))
1256 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1257 "Insert the output of COMMAND before point in current buffer."
1258 (let* ((cmd (gpg-exec-path command))
1259 (key (if (equal keyspec "") nil keyspec))
1260 (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1263 (apply 'call-process-region
1264 (point-min) (point-min) ; no data
1267 (if stderr t '(t nil))
1270 (unless (or ignore-error (equal exit-status 0))
1271 (error "GnuPG command exited unsuccessfully"))))
1274 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1275 "Return a list of keys matching KEYSPEC.
1276 COMMAND is used to obtain the key list. The usual substring search
1277 for keys is performed."
1279 (buffer-disable-undo)
1280 (gpg-key-list-keyspec command keyspec)
1281 (gpg-key-list-keys-in-buffer)))
1284 (defun gpg-key-list-keys (&optional keyspec)
1285 "A list of public keys matching KEYSPEC.
1286 The usual substring search for keys is performed."
1287 (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1290 (defun gpg-key-list-secret-keys (&optional keyspec)
1291 "A list of secret keys matching KEYSPEC.
1292 The usual substring search for keys is performed."
1293 (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1296 (defun gpg-key-insert-public-key (key)
1297 "Inserts the public key(s) matching KEYSPEC.
1298 The ASCII-armored key is inserted before point into current buffer."
1299 (gpg-key-list-keyspec gpg-command-key-export key))
1302 (defun gpg-key-insert-information (key)
1303 "Insert human-readable information (including fingerprint) on KEY.
1304 Insertion takes place in current buffer before point."
1305 (gpg-key-list-keyspec gpg-command-key-verify key))
1308 (defun gpg-key-retrieve (key)
1309 "Fetch KEY from default key server.
1310 KEY is a key ID or a list of key IDs. Status information about this
1311 operation is inserted into the current buffer before point."
1312 (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1315 (defun gpg-key-add-to-ring (key result)
1316 "Adds key in buffer KEY to the GnuPG key ring.
1317 Human-readable information on the RESULT is stored in buffer RESULT
1322 ;;; gpg.el ends here