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., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, 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).
109 (if (featurep 'xemacs
)
110 (require 'timer-funcs
)
112 (eval-when-compile (require 'cl
))
115 (defalias 'gpg-point-at-eol
116 (if (fboundp 'point-at-eol
)
118 'line-end-position
)))
120 ;; itimer/timer compatibility
122 (if (featurep 'xemacs
)
124 (defalias 'gpg-cancel-timer
'delete-itimer
)
125 (defalias 'gpg-timer-activate
'activate-itimer
)
126 (defalias 'gpg-timer-create
'make-itimer
)
127 (defalias 'gpg-timer-set-function
'set-itimer-function
)
128 (defalias 'gpg-timer-set-time
'set-itimer-value
))
129 (defalias 'gpg-cancel-timer
'cancel-timer
)
130 (defalias 'gpg-timer-activate
'timer-activate
)
131 (defalias 'gpg-timer-create
'timer-create
)
132 (defalias 'gpg-timer-set-function
'timer-set-function
)
133 (defalias 'gpg-timer-set-time
'timer-set-time
)))
137 ;;; Customization: Groups:
140 "GNU Privacy Guard interface."
144 (defgroup gpg-options nil
145 "Controlling GnuPG invocation."
149 (defgroup gpg-commands nil
150 "Primary GnuPG Operations."
151 :tag
"GnuPG Commands"
154 (defgroup gpg-commands-key nil
155 "Commands for GnuPG key management."
156 :tag
"GnuPG Key Commands"
157 :group
'gpg-commands
)
159 ;;; Customization: Widgets:
161 (if (get 'alist
'widget-type
)
162 (define-widget 'gpg-command-alist
'alist
163 "An association list for GnuPG command names."
164 :key-type
'(symbol :tag
"Abbreviation")
165 :value-type
'(string :tag
"Program name")
166 :convert-widget
'widget-alist-convert-widget
168 (define-widget 'gpg-command-alist
'repeat
169 "An association list for GnuPG command names."
170 :args
'((cons :format
"%v"
171 (symbol :tag
"Abbreviation")
172 (string :tag
"Program name")))
175 (define-widget 'gpg-command-program
'choice
176 "Widget for entering the name of a program (mostly the GnuPG binary)."
178 :args
'((const :tag
"Default GnuPG program."
180 (const :tag
"GnuPG compatibility wrapper."
182 (const :tag
"Disabled"
184 (string :tag
"Custom program" :format
"%v")))
186 (define-widget 'gpg-command-sign-options
'cons
187 "Widget for entering signing options."
188 :args
'(gpg-command-program
192 :format
"%[Type%] %v"
193 (const :tag
"Insert armor option here if necessary."
195 (const :tag
"Insert text mode option here if necessary."
197 (const :tag
"Insert the sign with key option here if necessary."
198 :value sign-with-key
)
199 (string :format
"%v")))))
201 (define-widget 'gpg-command-key-options
'cons
202 "Widget for entering key command options."
203 :args
'(gpg-command-program
207 :format
"%[Type%] %v"
208 (const :tag
"Insert key ID here."
210 (string :format
"%v")))))
212 ;;; Customization: Variables:
214 ;;; Customization: Variables: Paths and Flags:
216 (defcustom gpg-passphrase-timeout
218 "Timeout (in seconds) for the passphrase cache.
219 The passphrase cache is cleared after is hasn't been used for this
220 many seconds. The values 0 means that the passphrase is not cached at
222 :tag
"Passphrase Timeout"
226 (defcustom gpg-default-key-id
228 "Default key/user ID used for signatures."
229 :tag
"Default Key ID"
231 (const :tag
"Use GnuPG default." :value nil
)
235 (defcustom gpg-temp-directory
236 (expand-file-name "~/tmp")
237 "Directory for temporary files.
238 If you are running Emacs 20, this directory must have mode 0700."
239 :tag
"Temp directory"
243 (defcustom gpg-command-default-alist
246 "Default paths for some GnuPG-related programs.
247 Modify this variable if you have to change the paths to the
248 executables required by the GnuPG interface. You can enter \"gpg-2comp\"
249 for `gpg-2comp' if you have obtained this script, in order to gain
250 PGP 2.6.x compatibility."
251 :tag
"GnuPG programs"
252 :type
'gpg-command-alist
255 (defcustom gpg-command-all-arglist
257 "List of arguments to add to all GPG commands."
258 :tag
"All command args"
261 (defcustom gpg-command-flag-textmode
"--textmode"
262 "The flag to indicate canonical text mode to GnuPG."
263 :tag
"Text mode flag"
267 (defcustom gpg-command-flag-armor
"--armor"
268 "The flag to request ASCII-armoring output from GnuPG."
273 (defcustom gpg-command-flag-sign-with-key
'("--local-user=" sign-with-key
)
274 "String to include to specify the signing key ID.
275 The elements are concatenated (without spaces) to form a command line
277 :tag
"Sign with key flag"
278 :type
'(repeat :tag
"Argument parts"
279 (choice :format
"%[Type%] %v"
280 (const :tag
"Start next argument." :value next-argument
)
281 (const :tag
"Insert signing key ID here." :value sign-with-key
)
285 (defcustom gpg-command-flag-recipient
286 '(nil .
("-r" next-argument recipient next-argument
))
287 "Format of a recipient specification.
288 The elements are concatenated (without spaces) to form a command line
289 option. The second part is repeated for each recipient."
290 :tag
"Recipients Flag"
292 (repeat :tag
"Common prefix"
293 (choice :format
"%[Type%] %v"
294 (const :tag
"Start next argument." :value next-argument
)
296 (repeat :tag
"For each recipient"
297 (choice :format
"%[Type%] %v"
298 (const :tag
"Start next argument." :value next-argument
)
299 (const :tag
"Insert recipient key ID here." :value recipient
)
303 (defcustom gpg-command-passphrase-env
305 "Environment variable to set when a passphrase is required, or nil.
306 If an operation is invoked which requires a passphrase, this
307 environment variable is set before calling the external program to
308 indicate that it should read the passphrase from standard input."
309 :tag
"Passphrase environment"
311 (const :tag
"Disabled" :value nil
)
313 (string :tag
"Variable")
314 (string :tag
"Value")))
317 ;;; Customization: Variables: GnuPG Commands:
319 (defcustom gpg-command-verify
320 '(gpg .
("--status-fd" "1" "--batch" "--verbose" "--verify" signature-file message-file
))
321 "Command to verify a detached signature.
322 The invoked program has to read the signed message and the signature
323 from the given files. It should write human-readable information to
324 standard output and/or standard error. The program shall not convert
325 charsets or line endings; the input data shall be treated as binary."
326 :tag
"Verify Command"
332 :format
"%[Type%] %v"
333 (const :tag
"Insert name of file containing the message here."
335 (const :tag
"Insert name of file containing the signature here."
336 :value signature-file
)
337 (string :format
"%v"))))
338 :group
'gpg-commands
)
340 (defcustom gpg-command-verify-cleartext
341 '(gpg .
("--status-fd" "1" "--batch" "--verbose" "--verify" message-file
))
342 "Command to verify a message.
343 The invoked program has to read the signed message from the given
344 file. It should write human-readable information to standard output
345 and/or standard error. The program shall not convert charsets or line
346 endings; the input data shall be treated as binary."
347 :tag
"Cleartext Verify Command"
353 :format
"%[Type%] %v"
354 (const :tag
"Insert name of file containing the message here."
356 (string :format
"%v"))))
357 :group
'gpg-commands
)
359 (defcustom gpg-command-decrypt
360 '(gpg .
("--status-fd" "2" "--decrypt" "--batch" "--passphrase-fd=0"))
361 "Command to decrypt a message.
362 The invoked program has to read the passphrase from standard
363 input, followed by the encrypted message. It writes the decrypted
364 message to standard output, and human-readable diagnostic messages to
366 :tag
"Decrypt Command"
372 :format
"%[Type%] %v"
373 (const :tag
"Insert name of file containing the message here."
375 (string :format
"%v"))))
376 :group
'gpg-commands
)
378 (defcustom gpg-command-sign-cleartext
379 '(gpg-2comp .
("--batch" "--passphrase-fd=0" "--output=-"
380 armor textmode
"--clearsign"
382 "Command to create a \"clearsign\" text file.
383 The invoked program has to read the passphrase from standard input,
384 followed by the message to sign. It should write the ASCII-amored
385 signed text message to standard output, and diagnostic messages to
387 :tag
"Clearsign Command"
388 :type
'gpg-command-sign-options
389 :group
'gpg-commands
)
391 (defcustom gpg-command-sign-detached
392 '(gpg-2comp .
("--batch" "--passphrase-fd=0" "--output=-"
393 armor textmode
"--detach-sign"
395 "Command to create a detached signature.
396 The invoked program has to read the passphrase from standard input,
397 followed by the message to sign. It should write the ASCII-amored
398 detached signature to standard output, and diagnostic messages to
399 standard error. The program shall not convert charsets or line
400 endings; the input data shall be treated as binary."
401 :tag
"Sign Detached Command"
402 :type
'gpg-command-sign-options
403 :group
'gpg-commands
)
405 (defcustom gpg-command-sign-encrypt
406 '(gpg-2comp .
("--batch" "--passphrase-fd=0" "--output=-"
407 armor textmode
"--always-trust" sign-with-key recipients
408 "--sign" "--encrypt" plaintext-file
))
409 "Command to sign and encrypt a file.
410 The invoked program has to read the passphrase from standard input,
411 followed by the message to sign and encrypt if there is no
412 `plaintext-file' placeholder. It should write the ASCII-amored
413 encrypted message to standard output, and diagnostic messages to
415 :tag
"Sign And Encrypt Command"
421 :format
"%[Type%] %v"
422 (const :tag
"Insert the `sign with key' option here if necessary."
423 :value sign-with-key
)
424 (const :tag
"Insert list of recipients here."
426 (const :tag
"Insert here name of file with plaintext."
427 :value plaintext-file
)
428 (string :format
"%v"))))
429 :group
'gpg-commands
)
431 (defcustom gpg-command-encrypt
432 '(gpg-2comp .
("--batch" "--output=-" armor textmode
"--always-trust"
433 "--encrypt" recipients plaintext-file
))
434 "Command to encrypt a file.
435 The invoked program has to read the message to encrypt from standard
436 input or from the plaintext file (if the `plaintext-file' placeholder
437 is present). It should write the ASCII-amored encrypted message to
438 standard output, and diagnostic messages to standard error."
444 :format
"%[Type%] %v"
445 (const :tag
"Insert list of recipients here."
447 (const :tag
"Insert here name of file with plaintext."
448 :value plaintext-file
)
449 (string :format
"%v"))))
450 :group
'gpg-commands
)
452 ;;; Customization: Variables: Key Management Commands:
454 (defcustom gpg-command-key-import
455 '(gpg .
("--import" "--verbose" message-file
))
456 "Command to import a public key from a file."
457 :tag
"Import Command"
463 :format
"%[Type%] %v"
464 (const :tag
"Insert name of file containing the key here."
466 (string :format
"%v"))))
467 :group
'gpg-commands-key
)
469 (defcustom gpg-command-key-export
470 '(gpg .
("--no-verbose" "--armor" "--export" key-id
))
471 "Command to export a public key from the key ring.
472 The key should be written to standard output using ASCII armor."
473 :tag
"Export Command"
474 :type
'gpg-command-key-options
475 :group
'gpg-commands-key
)
477 (defcustom gpg-command-key-verify
478 '(gpg .
("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id
))
479 "Command to verify a public key."
480 :tag
"Verification Command"
481 :type
'gpg-command-key-options
482 :group
'gpg-commands-key
)
484 (defcustom gpg-command-key-public-ring
485 '(gpg .
("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id
))
486 "Command to list the contents of the public key ring."
487 :tag
"List Public Key Ring Command"
488 :type
'gpg-command-key-options
489 :group
'gpg-commands-key
)
491 (defcustom gpg-command-key-secret-ring
492 '(gpg .
("--no-verbose" "--batch" "--with-colons"
493 "--list-secret-keys" key-id
))
494 "Command to list the contents of the secret key ring."
495 :tag
"List Secret Key Ring Command"
496 :type
'gpg-command-key-options
497 :group
'gpg-commands-key
)
499 (defcustom gpg-command-key-retrieve
500 '(gpg .
("--batch" "--recv-keys" key-id
))
501 "Command to retrieve public keys."
502 :tag
"Retrieve Keys Command"
503 :type
'gpg-command-key-options
504 :group
'gpg-commands-key
)
507 ;;;; Helper functions for GnuPG invocation:
509 ;;; Build the GnuPG command line:
511 (defun gpg-build-argument (template substitutions
&optional pass-start
)
512 "Build command line argument(s) by substituting placeholders.
513 TEMPLATE is a list of strings and symbols. The placeholder symbols in
514 it are replaced by SUBSTITUTIONS, the elements between
515 `next-argument' symbols are concatenated without spaces and are
518 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
519 a string (which is inserted literally), a list of strings (which are
520 inserted as well), or nil, which means to insert nothing.
522 If PASS-START is t, `next-argument' is also inserted into the result,
523 and symbols without a proper substitution are retained in the output,
524 otherwise, an untranslated symbol results in an error.
526 This function does not handle empty arguments reliably."
527 (let ((current-arg "")
530 (let* ((templ (pop template
))
531 (repl (assoc templ substitutions
))
532 (new (if repl
(cdr repl
) templ
)))
534 ((eq templ
'next-argument
)
535 ;; If the current argument is not empty, start a new one.
536 (unless (equal current-arg
"")
537 (setq arglist
(nconc arglist
539 (list current-arg
'next-argument
)
540 (list current-arg
))))
541 (setq current-arg
"")))
542 ((null new
) nil
) ; Drop it.
543 ((and (not (stringp templ
)) (null repl
))
544 ;; Retain an untranslated symbol in the output if
545 ;; `pass-start' is true.
547 (error "No replacement for `%s'" templ
))
548 (setq arglist
(nconc arglist
(list current-arg templ
)))
549 (setq current-arg
""))
552 (setq new
(list new
)))
553 (setq current-arg
(concat current-arg
554 (apply 'concat new
)))))))
555 (unless (equal current-arg
"")
556 (setq arglist
(nconc arglist
(list current-arg
))))
559 (defun gpg-build-arg-list (template substitutions
)
560 "Build command line by substituting placeholders.
561 TEMPLATE is a list of strings and symbols. The placeholder symbols in
562 it are replaced by SUBSTITUTIONS.
564 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
565 string (which is inserted literally), a list of strings (which are
566 inserted as well), or nil, which means to insert nothing."
567 (let ((arglist (copy-sequence gpg-command-all-arglist
)))
569 (let* ((templ (pop template
))
570 (repl (assoc templ substitutions
))
571 (new (if repl
(cdr repl
) templ
)))
573 ((and (symbolp templ
) (null repl
))
574 (error "No replacement for `%s'" templ
))
575 ((null new
) nil
) ; Drop it.
578 (setq new
(list new
)))
579 (setq arglist
(nconc arglist new
))))))
582 (defun gpg-build-flag-recipients-one (recipient)
583 "Build argument for one RECIPIENT."
584 (gpg-build-argument (cdr gpg-command-flag-recipient
)
585 `((recipient .
,recipient
)) t
))
587 (defun gpg-build-flag-recipients (recipients)
588 "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
590 (apply 'append
(car gpg-command-flag-recipient
)
591 (mapcar 'gpg-build-flag-recipients-one
595 (defun gpg-read-recipients ()
596 "Query the user for several recipients."
600 (setq r
(read-string "Enter recipient ID [RET when no more]: "))
603 (setq recipients
(nconc recipients
(list r
)))))
606 (defun gpg-build-flag-sign-with-key (key)
607 "Build sign with key flag using `gpg-command-flag-sign-with-key'."
609 (if gpg-default-key-id gpg-default-key-id
612 (gpg-build-argument gpg-command-flag-sign-with-key
613 (list (cons 'sign-with-key k
)))
616 (defmacro gpg-with-passphrase-env
(&rest body
)
617 "Adjust the process environment and evaluate BODY.
618 During the evaluation of the body forms, the process environment is
619 adjust according to `gpg-command-passphrase-env'."
620 (let ((env-value (make-symbol "env-value")))
624 (when gpg-command-passphrase-env
625 (setq ,env-value
(getenv (car gpg-command-passphrase-env
)))
626 (setenv (car gpg-command-passphrase-env
)
627 (cdr gpg-command-passphrase-env
)))
629 (when gpg-command-passphrase-env
630 ;; This will clear the variable if it wasn't set before.
631 (setenv (car gpg-command-passphrase-env
) ,env-value
))))))
632 (put 'gpg-with-passphrase-env
'lisp-indent-function
0)
633 (put 'gpg-with-passphrase-env
'edebug-form-spec
'(body))
637 (defun gpg-make-temp-file ()
638 "Create a temporary file in a safe way"
639 (let ((name ;; User may use "~/"
640 (expand-file-name "gnupg" gpg-temp-directory
)))
641 (if (fboundp 'make-temp-file
)
642 ;; If we've got make-temp-file, we are on the save side.
643 (make-temp-file name
)
644 ;; make-temp-name doesn't create the file, and an ordinary
645 ;; write-file operation is prone to nasty symlink attacks if the
646 ;; temporary file resides in a world-writable directory.
647 (unless (or (memq system-type
'(windows-nt cygwin32 win32 w32 mswindows
))
648 (eq (file-modes gpg-temp-directory
) 448)) ; mode 0700
649 (error "Directory for temporary files (%s) must have mode 0700" gpg-temp-directory
))
650 (setq name
(make-temp-name name
))
651 (let ((mode (default-file-modes)))
654 (set-default-file-modes 384) ; mode 0600
655 (with-temp-file name
))
656 (set-default-file-modes mode
)))
659 (defvar gpg-temp-files nil
660 "List of temporary files used by the GnuPG interface.
661 Do not set this variable. Call `gpg-with-temp-files' if you need
664 (defun gpg-with-temp-files-create (count)
665 "Do not call this function. Used internally by `gpg-with-temp-files'."
667 (setq gpg-temp-files
(cons (gpg-make-temp-file) gpg-temp-files
))
668 (setq count
(1- count
))))
670 (defun gpg-with-temp-files-delete ()
671 "Do not call this function. Used internally by `gpg-with-temp-files'."
672 (while gpg-temp-files
673 (let ((file (pop gpg-temp-files
)))
678 (defmacro gpg-with-temp-files
(count &rest body
)
679 "Create COUNT temporary files, USE them, and delete them.
680 The function USE is called with the names of all temporary files as
682 `(let ((gpg-temp-files))
685 ;; Create the temporary files.
686 (gpg-with-temp-files-create ,count
)
688 (gpg-with-temp-files-delete))))
689 (put 'gpg-with-temp-files
'lisp-indent-function
1)
690 (put 'gpg-with-temp-files
'edebug-form-spec
'(body))
692 ;;; Making subprocesses:
694 (defun gpg-exec-path (option)
695 "Return the program name for OPTION.
696 OPTION is of the form (PROGRAM . ARGLIST). This functions returns
697 PROGRAM, but takes default values into account."
698 (let* ((prg (car option
))
699 (path (assq prg gpg-command-default-alist
)))
701 (path (if (null (cdr path
))
702 (error "Command `%s' is not available" prg
)
704 ((null prg
) (error "Command is disabled"))
707 (defun gpg-call-process (cmd args stdin stdout stderr
&optional passphrase
)
708 "Invoke external program CMD with ARGS on buffer STDIN.
709 Standard output is insert before point in STDOUT, standard error in
710 STDERR. If PASSPHRASE is given, send it before STDIN. PASSPHRASE
711 should not end with a line feed (\"\\n\").
713 If `stdin-file' is present in ARGS, it is replaced by the name of a
714 temporary file. Before invoking CMD, the contents of STDIN is written
716 (gpg-with-temp-files 2
717 (let* ((coding-system-for-read 'no-conversion
)
718 (coding-system-for-write 'no-conversion
)
719 (have-stdin-file (memq 'stdin-file args
))
720 (stdin-file (nth 0 gpg-temp-files
))
721 (stderr-file (nth 1 gpg-temp-files
))
724 (,stdout
,stderr-file
)
726 ;; Replace `stdin-file'.
727 ,@(gpg-build-arg-list
728 args
(list (cons 'stdin-file stdin-file
)))))
730 (when have-stdin-file
731 (with-temp-file stdin-file
732 (buffer-disable-undo)
733 (insert-buffer-substring stdin
)))
737 (buffer-disable-undo)
738 (insert passphrase
"\n")
739 (unless have-stdin-file
740 (apply 'insert-buffer-substring
741 (if (listp stdin
) stdin
(list stdin
))))
742 (apply 'call-process-region
(point-min) (point-max) cpr-args
)
743 ;; Wipe out passphrase.
744 (goto-char (point-min))
745 (translate-region (point) (gpg-point-at-eol)
746 (make-string 256 ?
)))
748 (with-current-buffer (car stdin
)
749 (apply 'call-process-region
751 (if have-stdin-file
(cadr stdin
) (caddr stdin
))
753 (with-current-buffer stdin
754 (apply 'call-process-region
756 (if have-stdin-file
(point-min) (point-max))
758 (with-current-buffer stderr
759 (insert-file-contents-literally stderr-file
))
760 (if (or (stringp res
) (> res
0))
761 ;; Signal or abnormal exit.
762 (with-current-buffer stderr
763 (goto-char (point-max))
764 (insert (format "\nCommand exit status: %s\n" res
))
768 (defvar gpg-result-buffer nil
769 "The result of a GnuPG operation is stored in this buffer.
770 Never set this variable directly, use `gpg-show-result' instead.")
772 (defun gpg-show-result-buffer (always-show result
)
773 "Called by `gpg-show-results' to actually show the buffer."
774 (with-current-buffer gpg-result-buffer
775 ;; Only proceed if the buffer is non-empty.
776 (when (and (/= (point-min) (point-max))
777 (or always-show
(not result
)))
778 (save-window-excursion
779 (display-buffer (current-buffer))
780 (unless (y-or-n-p "Continue? ")
781 (error "GnuPG operation aborted"))))))
783 (defmacro gpg-show-result
(always-show &rest body
)
784 "Show GnuPG result to user for confirmation.
785 This macro binds `gpg-result-buffer' to a temporary buffer and
786 evaluates BODY, like `progn'. If BODY evaluates to `nil' (or
787 `always-show' is not nil), the user is asked for confirmation."
788 `(let ((gpg-result-buffer (get-buffer-create
789 (generate-new-buffer-name "*GnuPG Output*"))))
791 (gpg-show-result-buffer ,always-show
(progn ,@body
))
792 (kill-buffer gpg-result-buffer
))))
793 (put 'gpg-show-result
'lisp-indent-function
1)
794 (put 'gpg-show-result
'edebug-form-spec
'(body))
796 ;;; Passphrase handling:
798 (defvar gpg-passphrase-timer
800 "This timer will clear the passphrase cache periodically.")
802 (defvar gpg-passphrase
804 "The (unencrypted) passphrase cache.")
806 (defun gpg-passphrase-clear-string (str)
807 "Erases STR by overwriting all characters."
815 (defun gpg-passphrase-forget ()
816 "Forget stored passphrase."
819 (gpg-cancel-timer gpg-passphrase-timer
)
820 (setq gpg-passphrase-timer nil
)
821 (gpg-passphrase-clear-string gpg-passphrase
)
822 (setq gpg-passphrase nil
)))
824 (defun gpg-passphrase-store (passphrase)
825 "Store PASSPHRASE in cache.
826 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
827 (unless (equal gpg-passphrase-timeout
0)
828 (if (null gpg-passphrase-timer
)
829 (setq gpg-passphrase-timer
(gpg-timer-create)))
830 (gpg-timer-set-time gpg-passphrase-timer
831 (timer-relative-time (current-time)
832 gpg-passphrase-timeout
))
833 (gpg-timer-set-function gpg-passphrase-timer
'gpg-passphrase-forget
)
834 (unless (and (fboundp 'itimer-live-p
)
835 (itimer-live-p gpg-passphrase-timer
))
836 (gpg-timer-activate gpg-passphrase-timer
))
837 (setq gpg-passphrase passphrase
))
840 (defun gpg-passphrase-read ()
841 "Read a passphrase and remember it for some time."
844 ;; This reinitializes the timer.
845 (gpg-passphrase-store gpg-passphrase
)
846 (let ((pp (read-passwd "Enter passphrase: ")))
847 (gpg-passphrase-store pp
))))
850 ;;;; Main operations:
853 (defun gpg-verify (message signature result
)
854 "Verify buffer MESSAGE against detached SIGNATURE buffer.
855 Returns t if everything worked out well, nil otherwise. Consult
856 buffer RESULT for details."
857 (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
858 (gpg-with-temp-files 2
859 (let* ((sig-file (nth 0 gpg-temp-files
))
860 (msg-file (nth 1 gpg-temp-files
))
861 (cmd (gpg-exec-path gpg-command-verify
))
862 (args (gpg-build-arg-list (cdr gpg-command-verify
)
863 `((signature-file .
,sig-file
)
864 (message-file .
,msg-file
))))
866 (with-temp-file sig-file
867 (buffer-disable-undo)
868 (apply 'insert-buffer-substring
(if (listp signature
)
871 (with-temp-file msg-file
872 (buffer-disable-undo)
873 (apply 'insert-buffer-substring
(if (listp message
)
876 (setq res
(apply 'call-process-region
877 (point-min) (point-min) ; no data
883 (if (or (stringp res
) (> res
0))
884 ;; Signal or abnormal exit.
885 (with-current-buffer result
886 (insert (format "\nCommand exit status: %s\n" res
))
891 (defun gpg-verify-cleartext (message result
)
892 "Verify message in buffer MESSAGE.
893 Returns t if everything worked out well, nil otherwise. Consult
894 buffer RESULT for details.
896 NOTE: Use of this function is deprecated."
897 (interactive "bBuffer containing message: \nbBuffor for result: ")
898 (gpg-with-temp-files 1
899 (let* ((msg-file (nth 0 gpg-temp-files
))
900 (cmd (gpg-exec-path gpg-command-verify-cleartext
))
901 (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext
)
902 `((message-file .
,msg-file
))))
904 (with-temp-file msg-file
905 (buffer-disable-undo)
906 (apply 'insert-buffer-substring
(if (listp message
)
909 (setq res
(apply 'call-process-region
910 (point-min) (point-min) ; no data
916 (if (or (stringp res
) (> res
0))
917 ;; Signal or abnormal exit.
918 (with-current-buffer result
919 (insert (format "\nCommand exit status: %s\n" res
))
924 (defun gpg-decrypt (ciphertext plaintext result
&optional passphrase
)
925 "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
926 Returns t if everything worked out well, nil otherwise. Consult
927 buffer RESULT for details. Reads a missing PASSPHRASE using
928 `gpg-passphrase-read'."
929 (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
930 (gpg-call-process (gpg-exec-path gpg-command-decrypt
)
931 (gpg-build-arg-list (cdr gpg-command-decrypt
) nil
)
932 ciphertext plaintext result
933 (if passphrase passphrase
(gpg-passphrase-read)))
935 (gpg-passphrase-clear-string passphrase
)))
938 (defun gpg-sign-cleartext
939 (plaintext signed-text result
&optional passphrase sign-with-key
)
940 "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
942 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
943 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
944 everything worked out well, nil otherwise. Consult buffer RESULT for
947 NOTE: Use of this function is deprecated."
948 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
949 (let ((subst (list (cons 'sign-with-key
950 (gpg-build-flag-sign-with-key sign-with-key
))
951 (cons 'armor gpg-command-flag-armor
)
952 (cons 'textmode gpg-command-flag-textmode
))))
953 (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext
)
954 (gpg-build-arg-list (cdr gpg-command-sign-cleartext
)
956 plaintext signed-text result
957 (if passphrase passphrase
(gpg-passphrase-read))))
959 (gpg-passphrase-clear-string passphrase
)))
962 (defun gpg-sign-detached
963 (plaintext signature result
&optional passphrase sign-with-key
965 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
966 Reads a missing PASSPHRASE using `gpg-passphrase-read'. Uses key ID
967 SIGN-WITH-KEY if given, otherwise the default key ID. Returns t if
968 everything worked out well, nil otherwise. Consult buffer RESULT for
969 details. ARMOR the result and activate canonical TEXTMODE if
971 (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
972 (let ((subst (list (cons 'sign-with-key
973 (gpg-build-flag-sign-with-key sign-with-key
))
974 (cons 'armor
(if armor gpg-command-flag-armor
))
975 (cons 'textmode
(if armor gpg-command-flag-textmode
)))))
976 (gpg-call-process (gpg-exec-path gpg-command-sign-detached
)
977 (gpg-build-arg-list (cdr gpg-command-sign-detached
)
979 plaintext signature result
980 (if passphrase passphrase
(gpg-passphrase-read))))
982 (gpg-passphrase-clear-string passphrase
)))
986 (defun gpg-sign-encrypt
987 (plaintext ciphertext result recipients
&optional passphrase sign-with-key
989 "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
990 RECIPIENTS is a list of key IDs used for encryption. This function
991 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
992 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
993 ID. Returns t if everything worked out well, nil otherwise. Consult
994 buffer RESULT for details. ARMOR the result and activate canonical
995 TEXTMODE if requested."
997 (read-buffer "Buffer containing plaintext: " nil t
)
998 (read-buffer "Buffer for ciphertext: " nil t
)
999 (read-buffer "Buffer for status informationt: " nil t
)
1000 (gpg-read-recipients)))
1001 (let ((subst `((sign-with-key .
,(gpg-build-flag-sign-with-key
1003 (plaintext-file . stdin-file
)
1004 (recipients .
,(gpg-build-flag-recipients recipients
))
1005 (armor ,(if armor gpg-command-flag-armor
))
1006 (textmode ,(if armor gpg-command-flag-textmode
)))))
1007 (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt
)
1008 (gpg-build-arg-list (cdr gpg-command-sign-encrypt
)
1010 plaintext ciphertext result
1011 (if passphrase passphrase
(gpg-passphrase-read))))
1013 (gpg-passphrase-clear-string passphrase
)))
1018 (plaintext ciphertext result recipients
&optional passphrase armor textmode
)
1019 "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
1020 RECIPIENTS is a list of key IDs used for encryption. Returns t if
1021 everything worked out well, nil otherwise. Consult buffer RESULT for
1022 details. ARMOR the result and activate canonical
1023 TEXTMODE if requested."
1025 (read-buffer "Buffer containing plaintext: " nil t
)
1026 (read-buffer "Buffer for ciphertext: " nil t
)
1027 (read-buffer "Buffer for status informationt: " nil t
)
1028 (gpg-read-recipients)))
1029 (let ((subst `((plaintext-file . stdin-file
)
1030 (recipients .
,(gpg-build-flag-recipients recipients
))
1031 (armor ,(if armor gpg-command-flag-armor
))
1032 (textmode ,(if armor gpg-command-flag-textmode
)))))
1033 (gpg-call-process (gpg-exec-path gpg-command-encrypt
)
1034 (gpg-build-arg-list (cdr gpg-command-encrypt
) subst
)
1035 plaintext ciphertext result nil
))
1037 (gpg-passphrase-clear-string passphrase
)))
1042 ;;; ADT: OpenPGP Key
1044 (defun gpg-key-make (user-id key-id unique-id length algorithm
1045 creation-date expire-date validity trust
)
1046 "Create a new key object (for internal use only)."
1049 user-id key-id unique-id length algorithm
1051 creation-date expire-date validity trust
))
1054 (defun gpg-key-p (key)
1055 "Return t if KEY is a key specification."
1056 (and (arrayp key
) (equal (length key
) 9) key
))
1058 (defmacro gpg-key-primary-user-id
(key)
1059 "The primary user ID for KEY (human-readable).
1060 DO NOT USE this ID for selecting recipients. It is probably not
1062 (list 'car
(list 'aref key
0)))
1064 (defmacro gpg-key-user-ids
(key)
1065 "A list of additional user IDs for KEY (human-readable).
1066 DO NOT USE these IDs for selecting recipients. They are probably not
1068 (list 'cdr
(list 'aref key
0)))
1070 (defmacro gpg-key-id
(key)
1072 DO NOT USE this ID for selecting recipients. It is not guaranteed to
1076 (defun gpg-short-key-id (key)
1077 "The short key ID of KEY."
1078 (let* ((id (gpg-key-id key
))
1081 (substring id
(- len
8))
1084 (defmacro gpg-key-unique-id
(key)
1085 "A non-standard ID of KEY which is only valid locally.
1086 This ID can be used to specify recipients in a safe manner. Note,
1087 even this ID might not be unique unless GnuPG is used."
1090 (defmacro gpg-key-unique-id-list
(key-list)
1091 "Like `gpg-key-unique-id', but operate on a list."
1092 `(mapcar (lambda (key) (gpg-key-unique-id key
))
1095 (defmacro gpg-key-length
(key)
1096 "Returns the key length."
1099 (defmacro gpg-key-algorithm
(key)
1100 "The encryption algorithm used by KEY.
1101 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1102 `elgamal-encrypt', `dsa'."
1105 (defmacro gpg-key-creation-date
(key)
1106 "A string with the creation date of KEY in ISO format."
1109 (defmacro gpg-key-expire-date
(key)
1110 "A string with the expiration date of KEY in ISO format."
1113 (defmacro gpg-key-validity
(key)
1114 "The calculated validity of KEY.
1115 One of the symbols `not-known', `disabled', `revoked', `expired',
1116 `undefined', `trust-none', `trust-marginal', `trust-full',
1117 `trust-ultimate' (see the GnuPG documentation for details)."
1120 (defmacro gpg-key-trust
(key)
1121 "The assigned trust for KEY.
1122 One of the symbols `not-known', `undefined', `trust-none',
1123 `trust-marginal', `trust-full' (see the GnuPG
1124 documentation for details)."
1127 (defun gpg-key-lessp (a b
)
1128 "Returns t if primary user ID of A is less than B."
1129 (string-lessp (gpg-key-primary-user-id a
) (gpg-key-primary-user-id b
) ))
1131 ;;; Accessing the key database:
1133 ;; Internal functions:
1135 (defmacro gpg-key-list-keys-skip-field
()
1136 '(search-forward ":" eol
'move
))
1138 (defmacro gpg-key-list-keys-get-field
()
1139 '(buffer-substring (point) (if (gpg-key-list-keys-skip-field)
1142 (defmacro gpg-key-list-keys-string-field
()
1143 '(gpg-key-list-keys-get-field))
1145 (defmacro gpg-key-list-keys-read-field
()
1146 (let ((field (make-symbol "field")))
1147 `(let ((,field
(gpg-key-list-keys-get-field)))
1148 (if (equal (length ,field
) 0)
1152 (defun gpg-key-list-keys-parse-line ()
1153 "Parse the line in the current buffer and return a vector of fields."
1154 (let* ((eol (gpg-point-at-eol))
1158 (gpg-key-list-keys-read-field) ; type
1159 (gpg-key-list-keys-get-field) ; trust
1160 (gpg-key-list-keys-read-field) ; key length
1161 (gpg-key-list-keys-read-field) ; algorithm
1162 (gpg-key-list-keys-get-field) ; key ID
1163 (gpg-key-list-keys-get-field) ; creation data
1164 (gpg-key-list-keys-get-field) ; expire
1165 (gpg-key-list-keys-get-field) ; unique (local) ID
1166 (gpg-key-list-keys-get-field) ; ownertrust
1167 (gpg-key-list-keys-string-field) ; user ID
1172 (error "Too many fields in GnuPG key database"))
1175 (defconst gpg-pubkey-algo-alist
1177 (2 . rsa-encrypt-only
)
1179 (16 . elgamal-encrypt-only
)
1182 "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1184 (defconst gpg-trust-alist
1190 (?q . trust-undefined
)
1192 (?m . trust-marginal
)
1194 (?u . trust-ultimate
))
1195 "Alist mapping GnuPG trust value short forms to long symbols.")
1197 (defconst gpg-unabbrev-trust-alist
1198 '(("TRUST_UNDEFINED" . trust-undefined
)
1199 ("TRUST_NEVER" . trust-none
)
1200 ("TRUST_MARGINAL" . trust-marginal
)
1201 ("TRUST_FULLY" . trust-full
)
1202 ("TRUST_ULTIMATE" . trust-ultimate
))
1203 "Alist mapping capitalized GnuPG trust values to long symbols.")
1205 (defmacro gpg-key-list-keys-in-buffer-store
()
1206 '(when primary-user-id
1207 (sort user-id
'string-lessp
)
1208 (push (gpg-key-make (cons primary-user-id user-id
)
1209 key-id unique-id key-length
1210 algorithm creation-date
1211 expire-date validity trust
)
1214 (defun gpg-key-list-keys-in-buffer (&optional buffer
)
1215 "Return a list of keys for BUFFER.
1216 If BUFFER is omitted, use current buffer."
1217 (with-current-buffer (if buffer buffer
(current-buffer))
1218 (goto-char (point-min))
1219 ;; Skip key ring filename written by GnuPG.
1220 (search-forward "\n---------------------------\n" nil t
)
1221 ;; Loop over all lines in buffer and analyze them.
1222 (let (primary-user-id user-id key-id unique-id
; current key components
1223 key-length algorithm creation-date expire-date validity trust
1224 line
; fields in current line
1225 key-list
) ; keys gather so far
1227 (while (setq line
(gpg-key-list-keys-parse-line))
1229 ;; Public or secret key.
1230 ((memq (aref line
0) '(pub sec
))
1231 ;; Store previous key, if any.
1232 (gpg-key-list-keys-in-buffer-store)
1233 ;; Record field values.
1234 (setq primary-user-id
(aref line
9))
1236 (setq key-id
(aref line
4))
1237 ;; We use the key ID if no unique ID is available.
1238 (setq unique-id
(if (> (length (aref line
7)) 0)
1239 (concat "#" (aref line
7))
1240 (concat "0x" key-id
)))
1241 (setq key-length
(aref line
2))
1242 (setq algorithm
(assq (aref line
3) gpg-pubkey-algo-alist
))
1244 (setq algorithm
(cdr algorithm
))
1245 (error "Unknown algorithm %s" (aref line
3)))
1246 (setq creation-date
(if (> (length (aref line
5)) 0)
1248 (setq expire-date
(if (> (length (aref line
6)) 0)
1250 (setq validity
(assq (aref (aref line
1) 0) gpg-trust-alist
))
1252 (setq validity
(cdr validity
))
1253 (error "Unknown validity specification %S" (aref line
1)))
1254 (setq trust
(assq (aref (aref line
8) 0) gpg-trust-alist
))
1256 (setq trust
(cdr trust
))
1257 (error "Unknown trust specification %S" (aref line
8))))
1259 ;; Additional user ID
1260 ((eq 'uid
(aref line
0))
1261 (setq user-id
(cons (aref line
9) user-id
)))
1263 ;; Subkeys are ignored for now.
1264 ((memq (aref line
0) '(sub ssb
))
1266 (t (error "Unknown record type %S" (aref line
0)))))
1268 ;; Store the key retrieved last.
1269 (gpg-key-list-keys-in-buffer-store)
1270 ;; Sort the keys according to the primary user ID.
1271 (sort key-list
'gpg-key-lessp
))))
1273 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error
)
1274 "Insert the output of COMMAND before point in current buffer."
1275 (let* ((cmd (gpg-exec-path command
))
1276 (key (if (equal keyspec
"") nil keyspec
))
1277 (args (gpg-build-arg-list (cdr command
) `((key-id .
,key
))))
1280 (apply 'call-process-region
1281 (point-min) (point-min) ; no data
1284 (if stderr t
'(t nil
))
1287 (unless (or ignore-error
(equal exit-status
0))
1288 (error "GnuPG command exited unsuccessfully"))))
1291 (defun gpg-key-list-keyspec-parse (command &optional keyspec
)
1292 "Return a list of keys matching KEYSPEC.
1293 COMMAND is used to obtain the key list. The usual substring search
1294 for keys is performed."
1296 (buffer-disable-undo)
1297 (gpg-key-list-keyspec command keyspec
)
1298 (gpg-key-list-keys-in-buffer)))
1301 (defun gpg-key-list-keys (&optional keyspec
)
1302 "A list of public keys matching KEYSPEC.
1303 The usual substring search for keys is performed."
1304 (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec
))
1307 (defun gpg-key-list-secret-keys (&optional keyspec
)
1308 "A list of secret keys matching KEYSPEC.
1309 The usual substring search for keys is performed."
1310 (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec
))
1313 (defun gpg-key-insert-public-key (key)
1314 "Inserts the public key(s) matching KEYSPEC.
1315 The ASCII-armored key is inserted before point into current buffer."
1316 (gpg-key-list-keyspec gpg-command-key-export key
))
1319 (defun gpg-key-insert-information (key)
1320 "Insert human-readable information (including fingerprint) on KEY.
1321 Insertion takes place in current buffer before point."
1322 (gpg-key-list-keyspec gpg-command-key-verify key
))
1325 (defun gpg-key-retrieve (key)
1326 "Fetch KEY from default key server.
1327 KEY is a key ID or a list of key IDs. Status information about this
1328 operation is inserted into the current buffer before point."
1329 (gpg-key-list-keyspec gpg-command-key-retrieve key t t
))
1332 (defun gpg-key-add-to-ring (key result
)
1333 "Adds key in buffer KEY to the GnuPG key ring.
1334 Human-readable information on the RESULT is stored in buffer RESULT
1339 ;;; arch-tag: c972455d-9bc5-4de1-9dc7-4f494d63053b
1340 ;;; gpg.el ends here