diff --git a/.gitignore b/.gitignore index de173b8f..e5bf69dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,55 +1,54 @@ # GnuPG exclusions /aclocal.m4 /autom4te.cache /config.h.in /configure /config.h /config.log /config.status /libtool Makefile.in Makefile stamp-h1 *.o *.lo # Hidden files *~ # Byte compiled Python *.py[cod] __pycache__ # C extensions *.so # Packages *.egg *.egg-info build eggs parts develop-eggs .installed.cfg # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Assorted Apple crap default.profraw .DS_Store ._.DS_Store -default.profraw \ No newline at end of file diff --git a/TODO b/TODO index 5f03fb61..a915ed7c 100644 --- a/TODO +++ b/TODO @@ -1,627 +1,706 @@ #+TITLE: TODO List Hey Emacs, this is -*- org -*- mode! * IMPORTANT! :PROPERTIES: :CUSTOM_ID: dev-gnupg-org :END: There was a nine year gap (2009 to 2018) between edits of this file, so it is likely that much of the old information in it is wrong or no longer applicable. Bugs, feature requests and other development related work will be tracked through the [[https://dev.gnupg.org/][dev.gnupg.org]] site. -* TODO Document all the new stuff. +* Documentation :PROPERTIES: - :CUSTOM_ID: more-docs-is-better + :CUSTOM_ID: documentation :END: -** STARTED Fix this TODO list. +** Document all the new stuff. :PROPERTIES: - :CUSTOM_ID: fix-todo + :CUSTOM_ID: more-docs-is-better :END: - - State "STARTED" from "TODO" [2018-03-09 Fri 08:31] - Clean up the current TODO list. Include properties as relevant (so - if someone does make a PDF or HTML version the TOC will work). - Also check ans see if some of these ancient things can be removed - (e.g. do we really need to fix things that were broken in GPG - 1.3.x? I'm thinking not so much). +*** TODO Fix this TODO list. + :PROPERTIES: + :CUSTOM_ID: fix-todo + :END: + + Clean up the current TODO list. Include properties as relevant (so + if someone does make a PDF or HTML version the TOC will work). + + Also check ans see if some of these ancient things can be removed + (e.g. do we really need to fix things that were broken in GPG + 1.3.x? I'm thinking not so much). + +**** DONE fix TODO items + CLOSED: [2018-03-04 Sun 08:55] + :PROPERTIES: + :CUSTOM_ID: fix-todo-items + :END: + + Adjust todo items so each can now be referenced by custom-id and + checked off as necessary. +** TODO Document validity and trust issues. + :PROPERTIES: + :CUSTOM_ID: valid-trust-issues + :END: + +** In gpgme.texi: Register callbacks under the right letter in the index. + :PROPERTIES: + :CUSTOM_ID: gpgme-texi + :END: * Fix the remaining UI Server problems: :PROPERTIES: :CUSTOM_ID: ui-server-fix :END: ** VERIFY --silent support. :PROPERTIES: :CUSTOM_ID: verify-silent :END: ** ENCRYPT/DECRYPT/VERIFY/SIGN reset the engine, shouldn't be done with UISERVER? :PROPERTIES: :CUSTOM_ID: reset-engine-not-ui :END: * IMPORTANT :PROPERTIES: :CUSTOM_ID: important-stuff-really :END: ** When using descriptor passing, we need to set the fd to blocking before :PROPERTIES: :CUSTOM_ID: set-fd-blocking :END: issueing simple commands, because we are mixing synchronous commands into potentially asynchronous operations. ** Might want to implement nonblock for w32 native backend! :PROPERTIES: :CUSTOM_ID: nonblock-win32 :END: Right now we block reading the next line with assuan. + * Before release: :PROPERTIES: :CUSTOM_ID: pre-release :END: + ** CANCELLED Some gpg tests fail with gpg 1.3.4-cvs (gpg/t-keylist-sig) CLOSED: [2018-03-09 Fri 08:16] :PROPERTIES: :CUSTOM_ID: gpg-1-3-4-really :END: - State "CANCELLED" from "TODO" [2018-03-09 Fri 08:16] \\ WON'T FIX — too old or no longer applies. The test is currently disabled there and in gpg/t-import. + ** When gpg supports it, write binary subpackets directly, :PROPERTIES: :CUSTOM_ID: binary-subpackets :END: and parse SUBPACKET status lines. + * ABI's to break: :PROPERTIES: :CUSTOM_ID: abi-breakage-apparently-on-purpose :END: + ** Old opassuan interface. :PROPERTIES: :CUSTOM_ID: old-opassuan :END: + ** Implementation: Remove support for old style error codes in :PROPERTIES: :CUSTOM_ID: remove-old-error-codes :END: conversion.c::_gpgme_map_gnupg_error. + ** gpgme_edit_cb_t: Add "processed" return argument :PROPERTIES: :CUSTOM_ID: add-processed-return :END: (see edit.c::command_handler). + ** I/O and User Data could be made extensible. But this can be done :PROPERTIES: :CUSTOM_ID: add-io-user-data :END: without breaking the ABI hopefully. + ** All enums should be replaced by ints and simple macros for :PROPERTIES: :CUSTOM_ID: enums-should-be-ints :END: maximum compatibility. + ** Compatibility interfaces that can be removed in future versions: :PROPERTIES: :CUSTOM_ID: compat-interfaces-to-go :END: + *** gpgme_data_new_from_filepart :PROPERTIES: :CUSTOM_ID: gpgme-data-new-from-filepart :END: + *** gpgme_data_new_from_file :PROPERTIES: :CUSTOM_ID: gpgme-data-new-from-file :END: + *** gpgme_data_new_with_read_cb :PROPERTIES: :CUSTOM_ID: gpgme-data-new-with-read-cb :END: + *** gpgme_data_rewind :PROPERTIES: :CUSTOM_ID: gpgme-data-rewind :END: + *** gpgme_op_import_ext :PROPERTIES: :CUSTOM_ID: gpgme-op-import-ext :END: + *** gpgme_get_sig_key :PROPERTIES: :CUSTOM_ID: gpgme-get-sig-key :END: + *** gpgme_get_sig_ulong_attr :PROPERTIES: :CUSTOM_ID: gpgme-get-sig-ulong-attr :END: + *** gpgme_get_sig_string_attr :PROPERTIES: :CUSTOM_ID: gpgme-get-sig-string-attr :END: + *** GPGME_SIG_STAT_* :PROPERTIES: :CUSTOM_ID: gpgme-sig-stat :END: + *** gpgme_get_sig_status :PROPERTIES: :CUSTOM_ID: gpgme-get-sig-status :END: + *** gpgme_trust_item_release :PROPERTIES: :CUSTOM_ID: gpgme-trust-item-release :END: + *** gpgme_trust_item_get_string_attr :PROPERTIES: :CUSTOM_ID: gpgme-trust-item-get-string-attr :END: + *** gpgme_trust_item_get_ulong_attr :PROPERTIES: :CUSTOM_ID: gpgme-trust-item-get-ulong-attr :END: + *** gpgme_attr_t :PROPERTIES: :CUSTOM_ID: gpgme-attr-t :END: + *** All Gpgme* typedefs. :PROPERTIES: :CUSTOM_ID: all-gpgme-typedefs :END: * Thread support: :PROPERTIES: :CUSTOM_ID: threads :END: + ** When GNU Pth supports sendmsg/recvmsg, wrap them properly. :PROPERTIES: :CUSTOM_ID: wrap-oth :END: + ** Without timegm (3) support our ISO time parser is not thread safe. :PROPERTIES: :CUSTOM_ID: time-threads :END: There is a configure time warning, though. + * New features: :PROPERTIES: :CUSTOM_ID: new-features :END: + ** Flow control for data objects. :PROPERTIES: :CUSTOM_ID: flow-control-is-not-a-euphemism-for-an-s-bend :END: Currently, gpgme_data_t objects are assumed to be blocking. To break this assumption, we need either (A) a way for an user I/O callback to store the current operation in a continuation that can be resumed later. While the continuation exists, file descriptors associated with this operation must be removed from their respective event loop. or (B) a way for gpgme data objects to be associated with a waitable object, that can be registered with the user event loop. Neither is particularly simple. + ** Extended notation support. When gpg supports arbitrary binary :PROPERTIES: :CUSTOM_ID: extended-notation :END: notation data, provide a user interface for that. + ** notification system :PROPERTIES: :CUSTOM_ID: notification-system :END: We need a simple notification system, probably a simple callback with a string and some optional arguments. This is for example required to notify an application of a changed smartcard, The application can then do whatever is required. There are other usages too. This notfication system should be independent of any contextes of course. Not sure whether this is still required. GPGME_PROTOCOL_ASSUAN is sufficient for this. ** --learn-code support :PROPERTIES: :CUSTOM_ID: learn-code :END: This might be integrated with import. we still need to work out how to learn a card when gpg and gpgsm have support for smartcards. In GPA we currently invoke gpg directly. ** Might need a stat() for data objects and use it for length param to gpg. :PROPERTIES: :CUSTOM_ID: stat-data :END: + ** Implement support for photo ids. :PROPERTIES: :CUSTOM_ID: photo-id :END: + ** Allow selection of subkeys :PROPERTIES: :CUSTOM_ID: subkey-selection :END: + ** Allow to return time stamps in ISO format :PROPERTIES: :CUSTOM_ID: iso-format-datetime :END: - This allows us to handle years later than 2037 properly. With the - time_t interface they are all mapped to 2037-12-31 + This allows us to handle years later than 2037 properly. With the + time_t interface they are all mapped to 2037-12-31 + ** New features requested by our dear users, but rejected or left for :PROPERTIES: :CUSTOM_ID: feature-requests :END: later consideration: + *** Allow to export secret keys. :PROPERTIES: :CUSTOM_ID: export-secret-keys :END: Rejected because this is conceptually flawed. Secret keys on a smart card can not be exported, for example. May eventually e supproted with a keywrapping system. + *** Selecting the key ring, setting the version or comment in output. :PROPERTIES: :CUSTOM_ID: select-keyring-version :END: Rejected because the naive implementation is engine specific, the configuration is part of the engine's configuration or readily worked around in a different way + *** Selecting the symmetric cipher. :PROPERTIES: :CUSTOM_ID: symmetric-cipher-selection :END: + *** Exchanging keys with key servers. :PROPERTIES: :CUSTOM_ID: key-server-exchange :END: -* Documentation - :PROPERTIES: - :CUSTOM_ID: documentation - :END: -** TODO Document validity and trust issues. - :PROPERTIES: - :CUSTOM_ID: valid-trust-issues - :END: -** In gpgme.texi: Register callbacks under the right letter in the index. - :PROPERTIES: - :CUSTOM_ID: gpgme-texi - :END: -** TODO Update TODO file - :PROPERTIES: - :CUSTOM_ID: todo-update - :END: - -*** DONE fix TODO items - CLOSED: [2018-03-04 Sun 08:55] - :PROPERTIES: - :CUSTOM_ID: fix-todo-items - :END: - - Adjust todo items so each can now be referenced by custom-id and - checked off as necessary. - * Engines :PROPERTIES: :CUSTOM_ID: engines :END: + ** Do not create/destroy engines, but create engine and then reset it. :PROPERTIES: :CUSTOM_ID: reset-engine-is-not-quite-just-ignition :END: Internally the reset operation still spawns a new engine process, but this can be replaced with a reset later. Also, be very sure to release everything properly at a reset and at an error. Think hard about where to guarantee what (ie, what happens if start fails, are the fds unregistered immediately - i think so?) Note that we need support in gpgsm to set include-certs to default as RESET does not reset it, also for no_encrypt_to and probably other options. + ** Optimize the case where a data object has an underlying fd we can pass :PROPERTIES: :CUSTOM_ID: optimus-data-cousin-of-optimus-prime :END: directly to the engine. This will be automatic with socket I/O and descriptor passing. + ** Move code common to all engines up from gpg to engine. :PROPERTIES: :CUSTOM_ID: move-code-common-to-engines-out-of-gpg :END: + ** engine operations can return General Error on unknown protocol :PROPERTIES: :CUSTOM_ID: general-error-looking-to-be-court-martialled :END: (it's an internal error, as select_protocol checks already). + ** When server mode is implemented properly, more care has to be taken to :PROPERTIES: :CUSTOM_ID: server-mode :END: release all resources on error (for example to free assuan_cmd). + ** op_import_keys and op_export_keys have a limit in the number of keys. :PROPERTIES: :CUSTOM_ID: import-export-problems :END: This is because we pass them in gpg via the command line and gpgsm via an assuan control line. We should pipe them instead and maybe change gpg/gpgsm to not put them in memory. * GPG breakage: :PROPERTIES: :CUSTOM_ID: gpg-breakage :END: + ** CANCELLED gpg 1.4.2 lacks error reporting if sign/encrypt with revoked key. CLOSED: [2018-03-09 Fri 08:19] :PROPERTIES: :CUSTOM_ID: gpg-classic-lacks-stuff :END: - State "CANCELLED" from "TODO" [2018-03-09 Fri 08:19] \\ WON'T FIX. + ** CANCELLED gpg 1.4.2 does crappy error reporting (namely none at all) when CLOSED: [2018-03-09 Fri 08:20] :PROPERTIES: :CUSTOM_ID: gpg-classic-problems-but-do-we-care :END: - State "CANCELLED" from "TODO" [2018-03-09 Fri 08:20] \\ WON'T FIX. smart card is missing for sign operation: [GNUPG:] CARDCTRL 4 gpg: selecting openpgp failed: ec=6.110 gpg: signing failed: general error [GNUPG:] BEGIN_ENCRYPTION 2 10 gpg: test: sign+encrypt failed: general error + ** DONE Without agent and with wrong passphrase, gpg 1.4.2 enters into an CLOSED: [2018-03-09 Fri 08:20] :PROPERTIES: :CUSTOM_ID: recursive-gpg-classic :END: - State "DONE" from "TODO" [2018-03-09 Fri 08:20] \\ Must have been fixed in a subsequent release. infinite loop. + ** CANCELLED Use correct argv[0] CLOSED: [2018-03-09 Fri 08:24] :PROPERTIES: :CUSTOM_ID: correct-argv :END: - State "CANCELLED" from "TODO" [2018-03-09 Fri 08:24] \\ WON'T FIX. Also, there is no rungpg.c file in GPGME (or in GPG or most, if not all of the rest of the libs and packages; I suspect there hasn't been for a very long time). In rungpg.c:build_argv we use argv[argc] = strdup ("gpg"); /* argv[0] */ This should be changed to take the real file name used in account. * Operations :PROPERTIES: :CUSTOM_ID: operations-are-not-surgical :END: + ** Include cert values -2, -1, 0 and 1 should be defined as macros. :PROPERTIES: :CUSTOM_ID: certified-macros :END: + ** If an operation failed, make sure that the result functions don't return :PROPERTIES: :CUSTOM_ID: operation-failure :END: corrupt partial information. !!! NOTE: The EOF status handler is not called in this case !!! + ** Verify must not fail on NODATA premature if auto-key-retrieval failed. :PROPERTIES: :CUSTOM_ID: autobot-key-retrieval :END: It should not fail silently if it knows there is an error. !!! + ** All operations: Better error reporting. !! :PROPERTIES: :CUSTOM_ID: better-reporting-not-like-fox-news :END: + ** Export status handler need much more work. !!! :PROPERTIES: :CUSTOM_ID: export-status-handler :END: + ** Import should return a useful error when one happened. :PROPERTIES: :CUSTOM_ID: import-useful-stuff-even-wrong-stuff :END: + *** Import does not take notice of NODATA status report. :PROPERTIES: :CUSTOM_ID: import-no-data :END: + *** When GPGSM does issue IMPORT_OK status reports, make sure to check for :PROPERTIES: :CUSTOM_ID: gpgsm-import-ok :END: them in tests/gpgs m/t-import.c. + ** Verify can include info about version/algo/class, but currently :PROPERTIES: :CUSTOM_ID: verify-class :END: this is only available for gpg, not gpgsm. + ** Return ENC_TO output in verify result. Again, this is not available :PROPERTIES: :CUSTOM_ID: return-to-enc :END: for gpgsm. + ** Genkey should return something more useful than General_Error. :PROPERTIES: :CUSTOM_ID: general-key-assumed-command-from-general-error :END: + ** If possible, use --file-setsize to set the file size for proper progress :PROPERTIES: :CUSTOM_ID: file-setsize :END: callback handling. Write data interface for file size. + ** Optimize the file descriptor list, so the number of open fds is :PROPERTIES: :CUSTOM_ID: optimus-descriptus-younger-brother-of-optimus-prime :END: always known easily. + ** Encryption: It should be verified that the behaviour for partially untrusted :PROPERTIES: :CUSTOM_ID: only-mostly-dead-means-partially-alive :END: recipients is correct. + ** When GPG issues INV_something for invalid signers, catch them. :PROPERTIES: :CUSTOM_ID: invalid-sig :END: * Error Values :PROPERTIES: :CUSTOM_ID: error-value :END: + ** Map ASSUAN/GpgSM ERR error values in a better way than is done now. !! :PROPERTIES: :CUSTOM_ID: map-ass-error :END: + ** Some error values should identify the source more correctly (mostly error :PROPERTIES: :CUSTOM_ID: source-errors :END: values derived from status messages). + ** In rungpg.c we need to check the version of the engine :PROPERTIES: :CUSTOM_ID: rungpg-c-engine-ver :END: This requires a way to get the cached version number from the engine layer. * Tests :PROPERTIES: :CUSTOM_ID: tests :END: + ** TODO Write a fake gpg-agent so that we can supply known passphrases to :PROPERTIES: :CUSTOM_ID: test-fake-gpg-agent :END: gpgsm and setup the configuration files to use the agent. Without this we are testing a currently running gpg-agent which is not a clever idea. ! + ** t-data :PROPERTIES: :CUSTOM_ID: test-data :END: + *** Test gpgme_data_release_and_get_mem. :PROPERTIES: :CUSTOM_ID: test-gpgme-data-release-mem :END: + *** Test gpgme_data_seek for invalid types. :PROPERTIES: :CUSTOM_ID: test-gpgme-data-seek :END: + ** t-keylist :PROPERTIES: :CUSTOM_ID: test-keylist :END: Write a test for ext_keylist. + ** Test reading key signatures. :PROPERTIES: :CUSTOM_ID: test-key-sig :END: * Debug :PROPERTIES: :CUSTOM_ID: debug :END: + ** Tracepoints should be added at: Every public interface enter/leave, :PROPERTIES: :CUSTOM_ID: tracepoint-pub-int :END: before and in every callback, at major decision points, at every internal data point which might easily be observed by the outside (system handles). We also trace handles and I/O support threads in the w32 implementation because that's fragile code. Files left to do: data-fd.c data-mem.c data-stream.c data-user.c debug.c rungpg.c engine.c engine-gpgsm.c funopen.c w32-glib-io.c wait.c wait-global.c wait-private.c wait-user.c op-support.c decrypt.c decrypt-verify.c delete.c edit.c encrypt.c encrypt-sign.c export.c genkey.c import.c key.c keylist.c passphrase.c progress.c signers.c sig-notation.c trust-item.c trustlist.c verify.c + ** TODO Handle malloc and vasprintf errors. But decide first if they should be :PROPERTIES: :CUSTOM_ID: malloc-vasprintf :END: ignored (and logged with 255?!), or really be assertions. ! * Build suite :PROPERTIES: :CUSTOM_ID: build-suite :END: + ** TODO Make sure everything is cleaned correctly (esp. test area). :PROPERTIES: :CUSTOM_ID: clean-tests :END: + ** TODO Enable AC_CONFIG_MACRO_DIR and bump up autoconf version requirement. :PROPERTIES: :CUSTOM_ID: autoconf-macros :END: (To fix "./autogen.sh; ./configure --enable-maintainer-mode; touch configure.ac; make"). Currently worked around with ACLOCAL_AMFLAGS??? * Error checking :PROPERTIES: :CUSTOM_ID: error-checking :END: + ** TODO engine-gpgsm, with-validation :PROPERTIES: :CUSTOM_ID: gpgsm-validation :END: Add error checking some time after releasing a new gpgsm. * Language bindings and related components :PROPERTIES: :CUSTOM_ID: language-bindings-and-related-stuff :END: ** TODO Emacs and elisp binding :PROPERTIES: :CUSTOM_ID: emacs-and-elisp :END: Currently GNU Emacs uses EPA and EPG to provide GnuPG support. EPG does this by calling the GPG executable and wrapping the commands with elisp functions. A more preferable solution would be to implement an epgme.el which integrated with GPGME, then if it could not to attempt calling the gpgme-tool and only if those failed to fall back to the current epg.el and calling the command line binaries. ** TODO API of an API :PROPERTIES: :CUSTOM_ID: api-squared :END: See the more detailed notes on this in the [[lang/python/docs/TODO.org][python TODO]]. ** TODO GPGME installation and package management guide :PROPERTIES: :CUSTOM_ID: package-management :END: Write a guide/best practices for maintainers of GPGME packages with third party package management systems. -Copyright 2004, 2005, 2018 g10 Code GmbH + +* Copyright 2004, 2005, 2018 g10 Code GmbH + :PROPERTIES: + :CUSTOM_ID: copyright-and-license + :END: This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/lang/python/docs/GPGMEpythonHOWTOen.org b/lang/python/docs/GPGMEpythonHOWTOen.org new file mode 100644 index 00000000..655209ac --- /dev/null +++ b/lang/python/docs/GPGMEpythonHOWTOen.org @@ -0,0 +1,1370 @@ +#+TITLE: GNU Privacy Guard (GnuPG) Made Easy Python Bindings HOWTO (English) +#+LATEX_COMPILER: xelatex +#+LATEX_CLASS: article +#+LATEX_CLASS_OPTIONS: [12pt] +#+LATEX_HEADER: \usepackage{xltxtra} +#+LATEX_HEADER: \usepackage[margin=1in]{geometry} +#+LATEX_HEADER: \setmainfont[Ligatures={Common}]{Times New Roman} +#+LATEX_HEADER: \author{Ben McGinnes } + + +* Introduction + :PROPERTIES: + :CUSTOM_ID: intro + :END: + + | Version: | 0.1.0-draft | + | Author: | Ben McGinnes | + | Author GPG Key: | DB4724E6FA4286C92B4E55C4321E4E2373590E5D | + | Language: | Australian English, British English | + | xml:lang: | en-AU, en-GB, en | + + This document provides basic instruction in how to use the GPGME + Python bindings to programmatically leverage the GPGME library. + + +** Python 2 versus Python 3 + :PROPERTIES: + :CUSTOM_ID: py2-vs-py3 + :END: + + Though the GPGME Python bindings themselves provide support for + both Python 2 and 3, the focus is unequivocally on Python 3 and + specifically from Python 3.4 and above. As a consequence all the + examples and instructions in this guide use Python 3 code. + + Much of it will work with Python 2, but much of it also deals with + Python 3 byte literals, particularly when reading and writing data. + Developers concentrating on Python 2.7, and possibly even 2.6, will + need to make the appropriate modifications to support the older + string and unicode types as opposed to bytes. + + There are multiple reasons for concentrating on Python 3; some of + which relate to the immediate integration of these bindings, some + of which relate to longer term plans for both GPGME and the python + bindings and some of which relate to the impending EOL period for + Python 2.7. Essentially, though, there is little value in tying + the bindings to a version of the language which is a dead end and + the advantages offered by Python 3 over Python 2 make handling the + data types with which GPGME deals considerably easier. + + +** Examples + :PROPERTIES: + :CUSTOM_ID: howto-python3-examples + :END: + + All of the examples found in this document can be found as Python 3 + scripts in the =lang/python/examples/howto= directory. + + +* GPGME Concepts + :PROPERTIES: + :CUSTOM_ID: gpgme-concepts + :END: + + +** A C API + :PROPERTIES: + :CUSTOM_ID: gpgme-c-api + :END: + + Unlike many modern APIs with which programmers will be more + familiar with these days, the GPGME API is a C API. The API is + intended for use by C coders who would be able to access its + features by including the =gpgme.h= header file with their own C + source code and then access its functions just as they would any + other C headers. + + This is a very effective method of gaining complete access to the + API and in the most efficient manner possible. It does, however, + have the drawback that it cannot be directly used by other + languages without some means of providing an interface to those + languages. This is where the need for bindings in various + languages stems. + + +** Python bindings + :PROPERTIES: + :CUSTOM_ID: gpgme-python-bindings + :END: + + The Python bindings for GPGME provide a higher level means of + accessing the complete feature set of GPGME itself. It also + provides a more pythonic means of calling these API functions. + + The bindings are generated dynamically with SWIG and the copy of + =gpgme.h= generated when GPGME is compiled. + + This means that a version of the Python bindings is fundamentally + tied to the exact same version of GPGME used to generate that copy + of =gpgme.h=. + + +** Difference between the Python bindings and other GnuPG Python packages + :PROPERTIES: + :CUSTOM_ID: gpgme-python-bindings-diffs + :END: + + There have been numerous attempts to add GnuPG support to Python + over the years. Some of the most well known are listed here, along + with what differentiates them. + + +*** The python-gnupg package maintained by Vinay Sajip + :PROPERTIES: + :CUSTOM_ID: diffs-python-gnupg + :END: + + This is arguably the most popular means of integrating GPG with + Python. The package utilises the =subprocess= module to implement + wrappers for the =gpg= and =gpg2= executables normally invoked on + the command line (=gpg.exe= and =gpg2.exe= on Windows). + + The popularity of this package stemmed from its ease of use and + capability in providing the most commonly required features. + + Unfortunately it has been beset by a number of security issues in + the past; most of which stemmed from using unsafe methods of + accessing the command line via the =subprocess= calls. While some + effort has been made over the last two to three years (as of 2018) + to mitigate this, particularly by no longer providing shell access + through those subprocess calls, the wrapper is still somewhat + limited in the scope of its GnuPG features coverage. + + The python-gnupg package is available under the MIT license. + + +*** The gnupg package created and maintained by Isis Lovecruft + :PROPERTIES: + :CUSTOM_ID: diffs-isis-gnupg + :END: + + In 2015 Isis Lovecruft from the Tor Project forked and then + re-implemented the python-gnupg package as just gnupg. This new + package also relied on subprocess to call the =gpg= or =gpg2= + binaries, but did so somewhat more securely. + + The naming and version numbering selected for this package, + however, resulted in conflicts with the original python-gnupg and + since its functions were called in a different manner to + python-gnupg, the release of this package also resulted in a great + deal of consternation when people installed what they thought was + an upgrade that subsequently broke the code relying on it. + + The gnupg package is available under the GNU General Public + License version 3.0 (or any later version). + + +*** The PyME package maintained by Martin Albrecht + :PROPERTIES: + :CUSTOM_ID: diffs-pyme + :END: + + This package is the origin of these bindings, though they are + somewhat different now. For details of when and how the PyME + package was folded back into GPGME itself see the /Short History/ + document[fn:1] in this Python bindings =docs= directory.[fn:2] + + The PyME package was first released in 2002 and was also the first + attempt to implement a low level binding to GPGME. In doing so it + provided access to considerably more functionality than either the + =python-gnupg= or =gnupg= packages. + + The PyME package is only available for Python 2.6 and 2.7. + + Porting the PyME package to Python 3.4 in 2015 is what resulted in + it being folded into the GPGME project and the current bindings + are the end result of that effort. + + The PyME package is available under the same dual licensing as + GPGME itself: the GNU General Public License version 2.0 (or any + later version) and the GNU Lesser General Public License version + 2.1 (or any later version). + + +* GPGME Python bindings installation + :PROPERTIES: + :CUSTOM_ID: gpgme-python-install + :END: + + +** No PyPI + :PROPERTIES: + :CUSTOM_ID: do-not-use-pypi + :END: + + Most third-party Python packages and modules are available and + distributed through the Python Package Installer, known as PyPI. + + Due to the nature of what these bindings are and how they work, it + is infeasible to install the GPGME Python bindings in the same way. + + This is because the bindings use SWIG to dynamically generate C + bindings against =gpgme.h= and =gpgme.h= is generated from + =gpgme.h.in= at compile time when GPGME is built from source. Thus + to include a package in PyPI which actually built correctly would + require either statically built libraries for every architecture + bundled with it or a full implementation of C for each + architecture. + + +** Requirements + :PROPERTIES: + :CUSTOM_ID: gpgme-python-requirements + :END: + + The GPGME Python bindings only have three requirements: + + 1. A suitable version of Python 2 or Python 3. With Python 2 that + means Python 2.7 and with Python 3 that means Python 3.4 or + higher. + 2. SWIG. + 3. GPGME itself. Which also means that all of GPGME's dependencies + must be installed too. + + +** Installation + :PROPERTIES: + :CUSTOM_ID: installation + :END: + + Installing the Python bindings is effectively achieved by compiling + and installing GPGME itself. + + Once SWIG is installed with Python and all the dependencies for + GPGME are installed you only need to confirm that the version(s) of + Python you want the bindings installed for are in your =$PATH=. + + By default GPGME will attempt to install the bindings for the most + recent or highest version number of Python 2 and Python 3 it + detects in =$PATH=. It specifically checks for the =python= and + =python3= executables first and then checks for specific version + numbers. + + For Python 2 it checks for these executables in this order: + =python=, =python2= and =python2.7=. + + For Python 3 it checks for these executables in this order: + =python3=, =python3.6=, =python3.5= and =python3.4=. + + +*** Installing GPGME + :PROPERTIES: + :CUSTOM_ID: install-gpgme + :END: + + See the GPGME =README= file for details of how to install GPGME from + source. + + +* Fundamentals + :PROPERTIES: + :CUSTOM_ID: howto-fund-a-mental + :END: + + Before we can get to the fun stuff, there are a few matters + regarding GPGME's design which hold true whether you're dealing with + the C code directly or these Python bindings. + + +** No REST + :PROPERTIES: + :CUSTOM_ID: no-rest-for-the-wicked + :END: + + The first part of which is or will be fairly blatantly obvious upon + viewing the first example, but it's worth reiterating anyway. That + being that this API is /*not*/ a REST API. Nor indeed could it + ever be one. + + Most, if not all, Python programmers (and not just Python + programmers) know how easy it is to work with a RESTful API. In + fact they've become so popular that many other APIs attempt to + emulate REST-like behaviour as much as they are able. Right down + to the use of JSON formatted output to facilitate the use of their + API without having to retrain developers. + + This API does not do that. It would not be able to do that and + also provide access to the entire C API on which it's built. It + does, however, provide a very pythonic interface on top of the + direct bindings and it's this pythonic layer with which this HOWTO + deals with. + + +** Context + :PROPERTIES: + :CUSTOM_ID: howto-get-context + :END: + + One of the reasons which prevents this API from being RESTful is + that most operations require more than one instruction to the API + to perform the task. Sure, there are certain functions which can + be performed simultaneously, particularly if the result known or + strongly anticipated (e.g. selecting and encrypting to a key known + to be in the public keybox). + + There are many more, however, which cannot be manipulated so + readily: they must be performed in a specific sequence and the + result of one operation has a direct bearing on the outcome of + subsequent operations. Not merely by generating an error either. + + When dealing with this type of persistent state on the web, full of + both the RESTful and REST-like, it's most commonly referred to as a + session. In GPGME, however, it is called a context and every + operation type has one. + + +* Working with keys + :PROPERTIES: + :CUSTOM_ID: howto-keys + :END: + + +** Key selection + :PROPERTIES: + :CUSTOM_ID: howto-keys-selection + :END: + + Selecting keys to encrypt to or to sign with will be a common + occurrence when working with GPGMe and the means available for + doing so are quite simple. + + They do depend on utilising a Context; however once the data is + recorded in another variable, that Context does not need to be the + same one which subsequent operations are performed. + + The easiest way to select a specific key is by searching for that + key's key ID or fingerprint, preferably the full fingerprint + without any spaces in it. A long key ID will probably be okay, but + is not advised and short key IDs are already a problem with some + being generated to match specific patterns. It does not matter + whether the pattern is upper or lower case. + + So this is the best method: + + #+begin_src python + import gpg + + k = gpg.Context().keylist(pattern="258E88DCBD3CD44D8E7AB43F6ECB6AF0DEADBEEF") + keys = list(k) + #+end_src + + This is passable and very likely to be common: + + #+begin_src python + import gpg + + k = gpg.Context().keylist(pattern="0x6ECB6AF0DEADBEEF") + keys = list(k) + #+end_src + + And this is a really bad idea: + + #+begin_src python + import gpg + + k = gpg.Context().keylist(pattern="0xDEADBEEF") + keys = list(k) + #+end_src + + Alternatively it may be that the intention is to create a list of + keys which all match a particular search string. For instance all + the addresses at a particular domain, like this: + + #+begin_src python + import gpg + + ncsc = gpg.Context().keylist(pattern="ncsc.mil") + nsa = list(ncsc) + #+end_src + + +*** Counting keys + :PROPERTIES: + :CUSTOM_ID: howto-keys-counting + :END: + + Counting the number of keys in your public keybox (=pubring.kbx=), + the format which has superseded the old keyring format + (=pubring.gpg= and =secring.gpg=), or the number of secret keys is + a very simple task. + + #+begin_src python + import gpg + + c = gpg.Context() + seckeys = c.keylist(pattern=None, secret=True) + pubkeys = c.keylist(pattern=None, secret=False) + + seclist = list(seckeys) + secnum = len(seclist) + + publist = list(pubkeys) + pubnum = len(publist) + + print(""" + Number of secret keys: {0} + Number of public keys: {1} + """.format(secnum, pubnum)) + #+end_src + + +** Get key + :PROPERTIES: + :CUSTOM_ID: howto-get-key + :END: + + An alternative method of getting a single key via its fingerprint + is available directly within a Context with =Context().get_key=. + This is the preferred method of selecting a key in order to modify + it, sign or certify it and for obtaining relevant data about a + single key as a part of other functions; when verifying a signature + made by that key, for instance. + + By default this method will select public keys, but it can select + secret keys as well. + + This first example demonstrates selecting the current key of Werner + Koch, which is due to expire at the end of 2018: + + #+begin_src python + import gpg + + fingerprint = "80615870F5BAD690333686D0F2AD85AC1E42B367" + key = gpg.Context().get_key(fingerprint) + #+end_src + + Whereas this example demonstrates selecting the author's current + key with the =secret= key word argument set to =True=: + + #+begin_src python + import gpg + + fingerprint = "DB4724E6FA4286C92B4E55C4321E4E2373590E5D" + key = gpg.Context().get_key(fingerprint, secret=True) + #+end_src + + It is, of course, quite possible to select expired, disabled and + revoked keys with this function, but only to effectively display + information about those keys. + + It is also possible to use both unicode or string literals and byte + literals with the fingerprint when getting a key in this way. + + +* Basic Functions + :PROPERTIES: + :CUSTOM_ID: howto-the-basics + :END: + + The most frequently called features of any cryptographic library + will be the most fundamental tasks for encryption software. In this + section we will look at how to programmatically encrypt data, + decrypt it, sign it and verify signatures. + + +** Encryption + :PROPERTIES: + :CUSTOM_ID: howto-basic-encryption + :END: + + Encrypting is very straight forward. In the first example below + the message, =text=, is encrypted to a single recipient's key. In + the second example the message will be encrypted to multiple + recipients. + + +*** Encrypting to one key + :PROPERTIES: + :CUSTOM_ID: howto-basic-encryption-single + :END: + + Once the the Context is set the main issues with encrypting data + is essentially reduced to key selection and the keyword arguments + specified in the =gpg.Context().encrypt()= method. + + Those keyword arguments are: =recipients=, a list of keys + encrypted to (covered in greater detail in the following section); + =sign=, whether or not to sign the plaintext data, see subsequent + sections on signing and verifying signatures below (defaults to + =True=); =sink=, to write results or partial results to a secure + sink instead of returning it (defaults to =None=); =passphrase=, + only used when utilising symmetric encryption (defaults to + =None=); =always_trust=, used to override the trust model settings + for recipient keys (defaults to =False=); =add_encrypt_to=, + utilises any preconfigured =encrypt-to= or =default-key= settings + in the user's =gpg.conf= file (defaults to =False=); =prepare=, + prepare for encryption (defaults to =False=); =expect_sign=, + prepare for signing (defaults to =False=); =compress=, compresses + the plaintext prior to encryption (defaults to =True=). + + #+begin_src python + import gpg + + a_key = "0x12345678DEADBEEF" + text = b"""Some text to test with. + + Since the text in this case must be bytes, it is most likely that + the input form will be a separate file which is opened with "rb" + as this is the simplest method of obtaining the correct data + format. + """ + + c = gpg.Context(armor=True) + rkey = list(c.keylist(pattern=a_key, secret=False)) + ciphertext, result, sign_result = c.encrypt(text, recipients=rkey, sign=False) + + with open("secret_plans.txt.asc", "wb") as afile: + afile.write(ciphertext) + #+end_src + + Though this is even more likely to be used like this; with the + plaintext input read from a file, the recipient keys used for + encryption regardless of key trust status and the encrypted output + also encrypted to any preconfigured keys set in the =gpg.conf= + file: + + #+begin_src python + import gpg + + a_key = "0x12345678DEADBEEF" + + with open("secret_plans.txt", "rb") as afile: + text = afile.read() + + c = gpg.Context(armor=True) + rkey = list(c.keylist(pattern=a_key, secret=False)) + ciphertext, result, sign_result = c.encrypt(text, recipients=rkey, + sign=True, always_trust=True, + add_encrypt_to=True) + + with open("secret_plans.txt.asc", "wb") as afile: + afile.write(ciphertext) + #+end_src + + If the =recipients= paramater is empty then the plaintext is + encrypted symmetrically. If no =passphrase= is supplied as a + parameter or via a callback registered with the =Context()= then + an out-of-band prompt for the passphrase via pinentry will be + invoked. + + +*** Encrypting to multiple keys + :PROPERTIES: + :CUSTOM_ID: howto-basic-encryption-multiple + :END: + + Encrypting to multiple keys essentially just expands upon the key + selection process and the recipients from the previous examples. + + The following example encrypts a message (=text=) to everyone with + an email address on the =gnupg.org= domain,[fn:3] but does /not/ encrypt + to a default key or other key which is configured to normally + encrypt to. + + #+begin_src python + import gpg + + text = b"""Oh look, another test message. + + The same rules apply as with the previous example and more likely + than not, the message will actually be drawn from reading the + contents of a file or, maybe, from entering data at an input() + prompt. + + Since the text in this case must be bytes, it is most likely that + the input form will be a separate file which is opened with "rb" + as this is the simplest method of obtaining the correct data + format. + """ + + c = gpg.Context(armor=True) + rpattern = list(c.keylist(pattern="@gnupg.org", secret=False)) + logrus = [] + + for i in range(len(rpattern)): + if rpattern[i].can_encrypt == 1: + logrus.append(rpattern[i]) + + ciphertext, result, sign_result = c.encrypt(text, recipients=logrus, sign=False, + always_trust=True) + + with open("secret_plans.txt.asc", "wb") as afile: + afile.write(ciphertext) + #+end_src + + All it would take to change the above example to sign the message + and also encrypt the message to any configured default keys would + be to change the =c.encrypt= line to this: + + #+begin_src python + ciphertext, result, sign_result = c.encrypt(text, recipients=logrus, + always_trust=True, + add_encrypt_to=True) + #+end_src + + The only keyword arguments requiring modification are those for + which the default values are changing. The default value of + =sign= is =True=, the default of =always_trust= is =False=, the + default of =add_encrypt_to= is =False=. + + If =always_trust= is not set to =True= and any of the recipient + keys are not trusted (e.g. not signed or locally signed) then the + encryption will raise an error. It is possible to mitigate this + somewhat with something more like this: + + #+begin_src python + import gpg + + with open("secret_plans.txt.asc", "rb") as afile: + text = afile.read() + + c = gpg.Context(armor=True) + rpattern = list(c.keylist(pattern="@gnupg.org", secret=False)) + logrus = [] + + for i in range(len(rpattern)): + if rpattern[i].can_encrypt == 1: + logrus.append(rpattern[i]) + + try: + ciphertext, result, sign_result = c.encrypt(text, recipients=logrus, add_encrypt_to=True) + except gpg.errors.InvalidRecipients as e: + for i in range(len(e.recipients)): + for n in range(len(logrus)): + if logrus[n].fpr == e.recipients[i].fpr: + logrus.remove(logrus[n]) + else: + pass + try: + ciphertext, result, sign_result = c.encrypt(text, recipients=logrus, add_encrypt_to=True) + except: + pass + + with open("secret_plans.txt.asc", "wb") as afile: + afile.write(ciphertext) + #+end_src + + This will attempt to encrypt to all the keys searched for, then + remove invalid recipients if it fails and try again. + + +** Decryption + :PROPERTIES: + :CUSTOM_ID: howto-basic-decryption + :END: + + Decrypting something encrypted to a key in one's secret keyring is + fairly straight forward. + + In this example code, however, preconfiguring either + =gpg.Context()= or =gpg.core.Context()= as =c= is unnecessary + because there is no need to modify the Context prior to conducting + the decryption and since the Context is only used once, setting it + to =c= simply adds lines for no gain. + + #+begin_src python + import gpg + + ciphertext = input("Enter path and filename of encrypted file: ") + newfile = input("Enter path and filename of file to save decrypted data to: ") + with open(ciphertext, "rb") as cfile: + plaintext, result, verify_result = gpg.Context().decrypt(cfile) + with open(newfile, "wb") as nfile: + nfile.write(plaintext) + #+end_src + + The data available in plaintext in this example is the decrypted + content as a byte object in =plaintext[0]=, the recipient key IDs + and algorithms in =plaintext[1]= and the results of verifying any + signatures of the data in =plaintext[0]=. + + +** Signing text and files + :PROPERTIES: + :CUSTOM_ID: howto-basic-signing + :END: + + The following sections demonstrate how to specify keys to sign with. + + +*** Signing key selection + :PROPERTIES: + :CUSTOM_ID: howto-basic-signing-signers + :END: + + By default GPGME and the Python bindings will use the default key + configured for the user invoking the GPGME API. If there is no + default key specified and there is more than one secret key + available it may be necessary to specify the key or keys with + which to sign messages and files. + + #+begin_src python + import gpg + + logrus = input("Enter the email address or string to match signing keys to: ") + hancock = gpg.Context().keylist(pattern=logrus, secret=True) + sig_src = list(hancock) + #+end_src + + The signing examples in the following sections include the + explicitly designated =signers= parameter in two of the five + examples; once where the resulting signature would be ASCII + armoured and once where it would not be armoured. + + While it would be possible to enter a key ID or fingerprint here + to match a specific key, it is not possible to enter two + fingerprints and match two keys since the patten expects a string, + bytes or None and not a list. A string with two fingerprints + won't match any single key. + + +*** Normal or default signing messages or files + :PROPERTIES: + :CUSTOM_ID: howto-basic-signing-normal + :END: + + The normal or default signing process is essentially the same as + is most often invoked when also encrypting a message or file. So + when the encryption component is not utilised, the result is to + produce an encoded and signed output which may or may not be ASCII + armoured and which may or may not also be compressed. + + By default compression will be used unless GnuPG detects that the + plaintext is already compressed. ASCII armouring will be + determined according to the value of =gpg.Context().armor=. + + The compression algorithm is selected in much the same way as the + symmetric encryption algorithm or the hash digest algorithm is + when multiple keys are involved; from the preferences saved into + the key itself or by comparison with the preferences with all + other keys involved. + + #+begin_src python + import gpg + + text0 = """Declaration of ... something. + + """ + text = text0.encode() + + c = gpg.Context(armor=True, signers=sig_src) + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.NORMAL) + + with open("/path/to/statement.txt.asc", "w") as afile: + afile.write(signed_data.decode()) + #+end_src + + Though everything in this example is accurate, it is more likely + that reading the input data from another file and writing the + result to a new file will be performed more like the way it is done + in the next example. Even if the output format is ASCII armoured. + + #+begin_src python + import gpg + + with open("/path/to/statement.txt", "rb") as tfile: + text = tfile.read() + + c = gpg.Context() + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.NORMAL) + + with open("/path/to/statement.txt.sig", "wb") as afile: + afile.write(signed_data) + #+end_src + + +*** Detached signing messages and files + :PROPERTIES: + :CUSTOM_ID: howto-basic-signing-detached + :END: + + Detached signatures will often be needed in programmatic uses of + GPGME, either for signing files (e.g. tarballs of code releases) + or as a component of message signing (e.g. PGP/MIME encoded + email). + + #+begin_src python + import gpg + + text0 = """Declaration of ... something. + + """ + text = text0.encode() + + c = gpg.Context(armor=True) + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.DETACH) + + with open("/path/to/statement.txt.asc", "w") as afile: + afile.write(signed_data.decode()) + #+end_src + + As with normal signatures, detached signatures are best handled as + byte literals, even when the output is ASCII armoured. + + #+begin_src python + import gpg + + with open("/path/to/statement.txt", "rb") as tfile: + text = tfile.read() + + c = gpg.Context(signers=sig_src) + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.DETACH) + + with open("/path/to/statement.txt.sig", "wb") as afile: + afile.write(signed_data) + #+end_src + + +*** Clearsigning messages or text + :PROPERTIES: + :CUSTOM_ID: howto-basic-signing-clear + :END: + + Though PGP/in-line messages are no longer encouraged in favour of + PGP/MIME, there is still sometimes value in utilising in-line + signatures. This is where clear-signed messages or text is of + value. + + #+begin_src python + import gpg + + text0 = """Declaration of ... something. + + """ + text = text0.encode() + + c = gpg.Context() + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.CLEAR) + + with open("/path/to/statement.txt.asc", "w") as afile: + afile.write(signed_data.decode()) + #+end_src + + In spite of the appearance of a clear-signed message, the data + handled by GPGME in signing it must still be byte literals. + + #+begin_src python + import gpg + + with open("/path/to/statement.txt", "rb") as tfile: + text = tfile.read() + + c = gpg.Context() + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.CLEAR) + + with open("/path/to/statement.txt.asc", "wb") as afile: + afile.write(signed_data) + #+end_src + + +** Signature verification + :PROPERTIES: + :CUSTOM_ID: howto-basic-verification + :END: + + Essentially there are two principal methods of verification of a + signature. The first of these is for use with the normal or + default signing method and for clear-signed messages. The second is + for use with files and data with detached signatures. + + The following example is intended for use with the default signing + method where the file was not ASCII armoured: + + #+begin_src python + import gpg + import time + + filename = "statement.txt" + gpg_file = "statement.txt.gpg" + + c = gpg.Context() + + try: + data, result = c.verify(open(gpg_file)) + verified = True + except gpg.errors.BadSignatures as e: + verified = False + print(e) + + if verified is True: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: + {0} + with key {1} + made at {2} + """.format(c.get_key(sign.fpr).uids[0].uid, + sign.fpr, time.ctime(sign.timestamp))) + else: + pass + #+end_src + + Whereas this next example, which is almost identical would work + with normal ASCII armoured files and with clear-signed files: + + #+begin_src python + import gpg + import time + + filename = "statement.txt" + asc_file = "statement.txt.asc" + + c = gpg.Context() + + try: + data, result = c.verify(open(asc_file)) + verified = True + except gpg.errors.BadSignatures as e: + verified = False + print(e) + + if verified is True: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: + {0} + with key {1} + made at {2} + """.format(c.get_key(sign.fpr).uids[0].uid, + sign.fpr, time.ctime(sign.timestamp))) + else: + pass + #+end_src + + In both of the previous examples it is also possible to compare the + original data that was signed against the signed data in =data= to + see if it matches with something like this: + + #+begin_src python + with open(filename, "rb") as afile: + text = afile.read() + + if text == data: + print("Good signature.") + else: + pass + #+end_src + + The following two examples, however, deal with detached signatures. + With his method of verification the data that was signed does not + get returned since it is already being explicitly referenced in the + first argument of =c.verify=. So =data= is =None= and only the + information in =result= is available. + + #+begin_src python + import gpg + import time + + filename = "statement.txt" + sig_file = "statement.txt.sig" + + c = gpg.Context() + + try: + data, result = c.verify(open(filename), open(sig_file)) + verified = True + except gpg.errors.BadSignatures as e: + verified = False + print(e) + + if verified is True: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: + {0} + with key {1} + made at {2} + """.format(c.get_key(sign.fpr).uids[0].uid, + sign.fpr, time.ctime(sign.timestamp))) + else: + pass + #+end_src + + #+begin_src python + import gpg + import time + + filename = "statement.txt" + asc_file = "statement.txt.asc" + + c = gpg.Context() + + try: + data, result = c.verify(open(filename), open(asc_file)) + verified = True + except gpg.errors.BadSignatures as e: + verified = False + print(e) + + if verified is not None: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: + {0} + with key {1} + made at {2} + """.format(c.get_key(sign.fpr).uids[0].uid, + sign.fpr, time.ctime(sign.timestamp))) + else: + pass + #+end_src + + +* Creating keys and subkeys + :PROPERTIES: + :CUSTOM_ID: key-generation + :END: + + The one thing, aside from GnuPG itself, that GPGME depends on, of + course, is the keys themselves. So it is necessary to be able to + generate them and modify them by adding subkeys, revoking or + disabling them, sometimes deleting them and doing the same for user + IDs. + + In the following examples a key will be created for the world's + greatest secret agent, Danger Mouse. Since Danger Mouse is a secret + agent he needs to be able to protect information to =SECRET= level + clearance, so his keys will be 3072-bit keys. + + The pre-configured =gpg.conf= file which sets cipher, digest and + other preferences contains the following configuration parameters: + + #+begin_src conf + expert + allow-freeform-uid + allow-secret-key-import + trust-model tofu+pgp + tofu-default-policy unknown + enable-large-rsa + enable-dsa2 + # cert-digest-algo SHA256 + cert-digest-algo SHA512 + default-preference-list TWOFISH CAMELLIA256 AES256 CAMELLIA192 AES192 CAMELLIA128 AES BLOWFISH IDEA CAST5 3DES SHA512 SHA384 SHA256 SHA224 RIPEMD160 SHA1 ZLIB BZIP2 ZIP Uncompressed + personal-cipher-preferences TWOFISH CAMELLIA256 AES256 CAMELLIA192 AES192 CAMELLIA128 AES BLOWFISH IDEA CAST5 3DES + personal-digest-preferences SHA512 SHA384 SHA256 SHA224 RIPEMD160 SHA1 + personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed + #+end_src + + +** Primary key + :PROPERTIES: + :CUSTOM_ID: keygen-primary + :END: + + Generating a primary key uses the =create_key= method in a Context. + It contains multiple arguments and keyword arguments, including: + =userid=, =algorithm=, =expires_in=, =expires=, =sign=, =encrypt=, + =certify=, =authenticate=, =passphrase= and =force=. The defaults + for all of those except =userid=, =algorithm=, =expires_in=, + =expires= and =passphrase= is =False=. The defaults for + =algorithm= and =passphrase= is =None=. The default for + =expires_in= is =0=. The default for =expires= is =True=. There + is no default for =userid=. + + If =passphrase= is left as =None= then the key will not be + generated with a passphrase, if =passphrase= is set to a string + then that will be the passphrase and if =passphrase= is set to + =True= then gpg-agent will launch pinentry to prompt for a + passphrase. For the sake of convenience, these examples will keep + =passphrase= set to =None=. + + #+begin_src python + import gpg + + c = gpg.Context() + + c.home_dir = "~/.gnupg-dm" + userid = "Danger Mouse " + + dmkey = c.create_key(userid, algorithm = "rsa3072", expires_in = 31536000, + sign = True, certify = True) + #+end_src + + One thing to note here is the use of setting the =c.home_dir= + parameter. This enables generating the key or keys in a different + location. In this case to keep the new key data created for this + example in a separate location rather than adding it to existing + and active key store data. As with the default directory, + =~/.gnupg=, any temporary or separate directory needs the + permissions set to only permit access by the directory owner. On + posix systems this means setting the directory permissions to 700. + + The successful generation of the key can be confirmed via the + returned =GenkeyResult= object, which includes the following data: + + #+begin_src python + print(""" + Fingerprint: {0} + Primary Key: {1} + Public Key: {2} + Secret Key: {3} + Sub Key: {4} + User IDs: {5} + """.format(dmkey.fpr, dmkey.primary, dmkey.pubkey, dmkey.seckey, dmkey.sub, + dmkey.uid)) + #+end_src + + Alternatively the information can be confirmed using the command + line program: + + #+begin_src shell + bash-4.4$ gpg --homedir ~/.gnupg-dm -K + ~/.gnupg-dm/pubring.kbx + ---------------------- + sec rsa3072 2018-03-15 [SC] [expires: 2019-03-15] + 177B7C25DB99745EE2EE13ED026D2F19E99E63AA + uid [ultimate] Danger Mouse + + bash-4.4$ + #+end_src + + As with generating keys manually, to preconfigure expanded + preferences for the cipher, digest and compression algorithms, the + =gpg.conf= file must contain those details in the home directory in + which the new key is being generated. I used a cut down version of + my own =gpg.conf= file in order to be able to generate this: + + #+begin_src shell + bash-4.4$ gpg --homedir ~/.gnupg-dm --edit-key 177B7C25DB99745EE2EE13ED026D2F19E99E63AA showpref quit + Secret key is available. + + sec rsa3072/026D2F19E99E63AA + created: 2018-03-15 expires: 2019-03-15 usage: SC + trust: ultimate validity: ultimate + [ultimate] (1). Danger Mouse + + [ultimate] (1). Danger Mouse + Cipher: TWOFISH, CAMELLIA256, AES256, CAMELLIA192, AES192, CAMELLIA128, AES, BLOWFISH, IDEA, CAST5, 3DES + Digest: SHA512, SHA384, SHA256, SHA224, RIPEMD160, SHA1 + Compression: ZLIB, BZIP2, ZIP, Uncompressed + Features: MDC, Keyserver no-modify + + bash-4.4$ + #+end_src + + +** Subkeys + :PROPERTIES: + :CUSTOM_ID: keygen-subkeys + :END: + + Adding subkeys to a primary key is fairly similar to creating the + primary key with the =create_subkey= method. Most of the arguments + are the same, but not quite all. Instead of the =userid= argument + there is now a =key= argument for selecting which primary key to + add the subkey to. + + In the following example an encryption subkey will be added to the + primary key. Since Danger Mouse is a security conscious secret + agent, this subkey will only be valid for about six months, half + the length of the primary key. + + #+begin_src python + import gpg + + c = gpg.Context() + c.home_dir = "~/.gnupg-dm" + + key = c.get_key(dmkey.fpr, secret = True) + dmsub = c.create_subkey(key, algorithm = "rsa3072", expires_in = 15768000, + encrypt = True) + #+end_src + + As with the primary key, the results here can be checked with: + + #+begin_src python + print(""" + Fingerprint: {0} + Primary Key: {1} + Public Key: {2} + Secret Key: {3} + Sub Key: {4} + User IDs: {5} + """.format(dmsub.fpr, dmsub.primary, dmsub.pubkey, dmsub.seckey, dmsub.sub, + dmsub.uid)) + #+end_src + + As well as on the command line with: + + #+begin_src shell + bash-4.4$ gpg --homedir ~/.gnupg-dm -K + ~/.gnupg-dm/pubring.kbx + ---------------------- + sec rsa3072 2018-03-15 [SC] [expires: 2019-03-15] + 177B7C25DB99745EE2EE13ED026D2F19E99E63AA + uid [ultimate] Danger Mouse + ssb rsa3072 2018-03-15 [E] [expires: 2018-09-13] + + bash-4.4$ + #+end_src + + +** User IDs + :PROPERTIES: + :CUSTOM_ID: keygen-uids + :END: + + By comparison to creating primary keys and subkeys, adding a new + user ID to an existing key is much simpler. The method used to do + this is =key_add_uid= and the only arguments it takes are for the + =key= and the new =uid=. + + #+begin_src python + import gpg + + c = gpg.Context() + c.home_dir = "~/.gnupg-dm" + + dmfpr = "177B7C25DB99745EE2EE13ED026D2F19E99E63AA" + key = c.get_key(dmfpr, secret = True) + uid = "Danger Mouse " + + c.key_add_uid(key, uid) + #+end_src + + Unsurprisingly the result of this is: + + #+begin_src shell + bash-4.4$ gpg --homedir ~/.gnupg-dm -K + ~/.gnupg-dm/pubring.kbx + ---------------------- + sec rsa3072 2018-03-15 [SC] [expires: 2019-03-15] + 177B7C25DB99745EE2EE13ED026D2F19E99E63AA + uid [ultimate] Danger Mouse + uid [ultimate] Danger Mouse + ssb rsa3072 2018-03-15 [E] [expires: 2018-09-13] + + bash-4.4$ + #+end_src + + +** Key certification + :PROPERTIES: + :CUSTOM_ID: key-sign + :END: + + Since key certification is more frequently referred to as key + signing, the method used to perform this function is =key_sign=. + + The =key_sign= method takes four arguments: =key=, =uids=, + =expires_in= and =local=. The default value of =uids= is =None= + and which results in all user IDs being selected. The default + values of =expires_in= snd =local= is =False=; which result in the + signature never expiring and being able to be exported. + + The =key= is the key being signed rather than the key doing the + signing. To change the key doing the signing refer to the signing + key selection above for signing messages and files. + + If the =uids= value is not =None= then it must either be a string + to match a single user ID or a list of strings to match multiple + user IDs. In this case the matching of those strings must be + precise and it is case sensitive. + + To sign Danger Mouse's key for just the initial user ID with a + signature which will last a little over a month, do this: + + #+begin_src python + import gpg + + c = gpg.Context() + uid = "Danger Mouse " + + dmfpr = "177B7C25DB99745EE2EE13ED026D2F19E99E63AA" + key = c.get_key(dmfpr, secret = True) + c.key_sign(key, uids = uid, expires_in = 2764800) + #+end_src + + +* Miscellaneous work-arounds + :PROPERTIES: + :CUSTOM_ID: cheats-and-hacks + :END: + + +** Group lines + :PROPERTIES: + :CUSTOM_ID: group-lines + :END: + + There is not yet an easy way to access groups configured in the + gpg.conf file from within GPGME. As a consequence these central + groupings of keys cannot be shared amongst multiple programs, such + as MUAs readily. + + The following code, however, provides a work-around for obtaining + this information in Python. + + #+begin_src python + import subprocess + + lines = subprocess.getoutput("gpgconf --list-options gpg").splitlines() + + for i in range(len(lines)): + if lines[i].startswith("group") is True: + line = lines[i] + else: + pass + + groups = line.split(":")[-1].replace('"', '').split(',') + + group_lines = groups + for i in range(len(group_lines)): + group_lines[i] = group_lines[i].split("=") + + group_lists = group_lines + for i in range(len(group_lists)): + group_lists[i][1] = group_lists[i][1].split() + #+end_src + + The result of that code is that =group_lines= is a list of lists + where =group_lines[i][0]= is the name of the group and + =group_lines[i][1]= is the key IDs of the group as a string. + + The =group_lists= result is very similar in that it is a list of + lists. The first part, =group_lists[i][0]= matches + =group_lines[i][0]= as the name of the group, but + =group_lists[i][1]= is the key IDs of the group as a string. + + +* Copyright and Licensing + :PROPERTIES: + :CUSTOM_ID: copyright-and-license + :END: + + +** Copyright (C) The GnuPG Project, 2018 + :PROPERTIES: + :CUSTOM_ID: copyright + :END: + + Copyright © The GnuPG Project, 2018. + + +** License GPL compatible + :PROPERTIES: + :CUSTOM_ID: license + :END: + + This file is free software; as a special exception the author gives + unlimited permission to copy and/or distribute it, with or without + modifications, as long as this notice is preserved. + + This file is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY, to the extent permitted by law; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. + + +* Footnotes + +[fn:1] =Short_History.org= and/or =Short_History.html=. + +[fn:2] The =lang/python/docs/= directory in the GPGME source. + +[fn:3] You probably don't really want to do this. Searching the +keyservers for "gnupg.org" produces over 400 results, the majority of +which aren't actually at the gnupg.org domain, but just included a +comment regarding the project in their key somewhere. diff --git a/lang/python/docs/TODO.org b/lang/python/docs/TODO.org index 9f039d81..add8f4ff 100644 --- a/lang/python/docs/TODO.org +++ b/lang/python/docs/TODO.org @@ -1,144 +1,219 @@ #+TITLE: Stuff To Do #+LATEX_COMPILER: xelatex #+LATEX_CLASS: article #+LATEX_CLASS_OPTIONS: [12pt] #+LATEX_HEADER: \usepackage{xltxtra} #+LATEX_HEADER: \usepackage[margin=1in]{geometry} #+LATEX_HEADER: \setmainfont[Ligatures={Common}]{Latin Modern Roman} * Project Task List :PROPERTIES: :CUSTOM_ID: task-list :END: ** DONE Documentation default format CLOSED: [2018-02-15 Thu 21:29] :PROPERTIES: :CUSTOM_ID: todo-docs-default :END: Decide on a default file format for documentation. The two main contenders being Org Mode, the default for the GnuPG Project and reStructuredText, the default for Python projects. A third option of DITA XML was considered due to a number of beneficial features it provides. The decision was made to use Org Mode in order to fully integrate with the rest of the GPGME and GnuPG documentation. It is possible to produce reST versions via Pandoc and DITA XML can be reached through converting to either Markdown or XHTML first. -** TODO Documentation HOWTO + +** STARTED Documentation HOWTO :PROPERTIES: :CUSTOM_ID: todo-docs-howto :END: + - State "STARTED" from "TODO" [2018-03-08 Thu 13:59] \\ + Started yesterday. Write a HOWTO style guide for the current Python bindings. +*** DONE Start python bindings HOWTO + CLOSED: [2018-03-07 Wed 18:14] + :PROPERTIES: + :CUSTOM_ID: howto-start + :END: + + +*** STARTED Include certain specific instructions in the HOWTO + :PROPERTIES: + :CUSTOM_ID: howto-requests + :END: + + Note: moved the S/MIME bits out to their own section of the TODO + list and may be served better by separate HOWTO documentation + anyway. + + - State "STARTED" from "TODO" [2018-03-09 Fri 15:27] + Some functions can be worked out from the handful of examples + available, but many more can't and I've already begun receiving + requests for certain functions to be explained. + + +**** DONE Standard scenarios + CLOSED: [2018-03-19 Mon 12:34] + :PROPERTIES: + :CUSTOM_ID: howto-the-basics + :END: + + - State "DONE" from "STARTED" [2018-03-19 Mon 12:34] \\ + All four of those are done. + - State "STARTED" from "TODO" [2018-03-09 Fri 15:26] \\ + Began with the example code, now to add the text. + What everyone expects: encryption, decryption, signing and verifying. + + +**** STARTED Key control + :PROPERTIES: + :CUSTOM_ID: howto-key-control + :END: + + - State "STARTED" from "TODO" [2018-03-19 Mon 12:35] \\ + Generating keys and subkeys are done, but revocation is still to be done. + Generating keys, adding subkeys, revoking subkeys (and keeping + the cert key), adding and revoking UIDs, signing/certifying keys. + + +**** DONE More key control + CLOSED: [2018-03-19 Mon 12:36] + :PROPERTIES: + :CUSTOM_ID: howto-key-selection + :END: + + - State "DONE" from "TODO" [2018-03-19 Mon 12:36] \\ + Key selection, searching, matching and counting is done. + Selecting keys to encrypt to or manipulate in other ways (e.g. as + with key control or the basics). + + ** TODO Documentation SWIG :PROPERTIES: :CUSTOM_ID: todo-docs-swig :END: Write documentation for the complete SWIG bindings demonstrating the correspondence with GPGME itself. Note: it is likely that this will be more in the nature of something to be used in conjunction with the existing GPGME documentation which makes it easier for Python developers to use. + ** TODO GUI examples :PROPERTIES: :CUSTOM_ID: todo-gui-examples :END: Create some examples of using Python bindings in a GUI application to either match or be similar to the old GTK2 examples available with PyME. + ** TODO Replace SWIG :PROPERTIES: :CUSTOM_ID: todo-replace-swig :END: Selecting SWIG for this project in 2002 was understandable and effectively the only viable option. The options available now, however, are significantly improved and some of those would resolve a number of existing problems with using SWIG, particularly when running code on both POSIX compliant and Windows platforms. The long term goal is to replace SWIG by reimplementing the Python bindings using a more suitable means of interfacing with the GPGME C source code. + *** TODO Replacement for SWIG :PROPERTIES: :CUSTOM_ID: todo-replace-swig-replacement :END: Decide on a replacement for SWIG. Currently CFFI is looking like the most viable candidate, but some additional testing and checks are yet to be completed. + ** TODO API for an API :PROPERTIES: :CUSTOM_ID: todo-api-squared :END: A C API like GPGME is not what most modern developers think of when they hear the term API. Normally they think of something they can interact with like a RESTful web API. Though RESTful is unlikely given the nature of GPGME and the process of encryption, it may be possible to provide a more familiar interface which can be utilised by developers of other languages for which bindings are not available or for which it is too difficult to create proper bindings. + +** TODO S/MIME + :PROPERTIES: + :CUSTOM_ID: s-mime + :END: + + Eventually add some of this, but the OpenPGP details are far more + important at the moment. + + * Project Task Details :PROPERTIES: :CUSTOM_ID: detailed-tasks :END: ** Working examples :PROPERTIES: :CUSTOM_ID: working-examples :END: The old GUI examples were unable to be retained since they depended on GTK2 and Python 2's integration with GTK2. Current GPGME examples so far only include command line tools or basic Python code for use with either Python 2.7 or Python 3.4 and above. Future GUI examples ought to utilise available GUI modules and libraries supported by Python 3. This may include Qt frameworks, Tkinter, GTK3 or something else entirely. ** Documentation :PROPERTIES: :CUSTOM_ID: documentation :END: The legacy documentation which no longer applies to the Python bindings has been removed. Current and future documentation will adhere to the GnuPG standard of using Org Mode and not use the reStructuredText (reST) format more commonly associated with Python documentation. The reasons for this are that this project is best served as shipping with the rest of GPGME and the documentation ought to match that. There are also aspects of Org Mode's publishing features which are superior to the defaults of reST, including the capacity to generate fully validating strict XHTML output. If reST files are required at a later point for future inclusion with other Python packages, then that format can be generated from the .org files with Pandoc before being leveraged by either Docutils, Sphinx or something else. While there are some advanced typesetting features of reST which are not directly available to Org Mode, more often than not those features are best implemented with either HTML and CSS, with LaTeX to produce a PDF or via a number of XML solutions. Both reST and Org Mode have multiple paths by which to achieve all of these. diff --git a/lang/python/examples/howto/README.org b/lang/python/examples/howto/README.org new file mode 100644 index 00000000..b74ae7e2 --- /dev/null +++ b/lang/python/examples/howto/README.org @@ -0,0 +1,58 @@ +#+TITLE: GPGME Python Bindings HOWTO Examples +#+LATEX_COMPILER: xelatex +#+LATEX_CLASS: article +#+LATEX_CLASS_OPTIONS: [12pt] +#+LATEX_HEADER: \usepackage{xltxtra} +#+LATEX_HEADER: \usepackage[margin=1in]{geometry} +#+LATEX_HEADER: \setmainfont[Ligatures={Common}]{Times New Roman} +#+LATEX_HEADER: \author{Ben McGinnes } + + +* Examples + :PROPERTIES: + :CUSTOM_ID: gpgme-python3-examples + :END: + + The contents of this directory are the examples included in the /GNU + Privacy Guard (GnuPG) Made Easy Python Bindings HOWTO/ file. Each + script is explicitly for Python 3 and specifically for Python 3.4 or + later. + + Some of these scripts may work with Python 2.7, but there are no + guarantees. They will include the relevant imports from the + =__future__= module to facilitate that if possible. + + +* Copyright and Licensing + :PROPERTIES: + :CUSTOM_ID: copyright-and-license + :END: + + Unless otherwise stated, all the examples in this directory are + released under the same terms as GPGME itself; that is they are dual + licensed under the terms of both the GNU General Public License + version 2.0 (or any later version) *and* the GNU Lesser General + Public License version 2.1 (or any later version). + + +** Copyright (C) The GnuPG Project, 2018 + :PROPERTIES: + :CUSTOM_ID: copyright + :END: + + Copyright © The GnuPG Project, 2018. + + +** License GPL compatible + :PROPERTIES: + :CUSTOM_ID: license + :END: + + This file is free software; as a special exception the author gives + unlimited permission to copy and/or distribute it, with or without + modifications, as long as this notice is preserved. + + This file is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY, to the extent permitted by law; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. diff --git a/lang/python/examples/howto/clear-sign-file.py b/lang/python/examples/howto/clear-sign-file.py new file mode 100755 index 00000000..597bbc59 --- /dev/null +++ b/lang/python/examples/howto/clear-sign-file.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +""" +Clear-signs a file with a specified key. If entering both the key and the +filename on the command line, the key must be entered first. +""" + +if len(sys.argv) > 3: + logrus = sys.argv[1] + filename = " ".join(sys.argv[2:]) +elif len(sys.argv) == 3: + logrus = sys.argv[1] + filename = sys.argv[2] +elif len(sys.argv) == 2: + logrus = sys.argv[1] + filename = input("Enter the path and filename to sign: ") +else: + logrus = input("Enter the fingerprint or key ID to sign with: ") + filename = input("Enter the path and filename to sign: ") + +with open(filename, "rb") as f: + text = f.read() + +key = list(gpg.Context().keylist(pattern=logrus)) + +with gpg.Context(armor=True, signers=key) as c: + signed_data, result = c.sign(text, mode=gpg.constants.sig.mode.CLEAR) + with open("{0}.asc".format(filename), "wb") as f: + f.write(signed_data) diff --git a/lang/python/examples/howto/decrypt-file.py b/lang/python/examples/howto/decrypt-file.py new file mode 100755 index 00000000..60a050bd --- /dev/null +++ b/lang/python/examples/howto/decrypt-file.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +if len(sys.argv) == 3: + ciphertext = sys.argv[1] + newfile = sys.argv[2] +elif len(sys.argv) == 2: + ciphertext = sys.argv[1] + newfile = input("Enter path and filename of file to save decrypted data to: ") +else: + ciphertext = input("Enter path and filename of encrypted file: ") + newfile = input("Enter path and filename of file to save decrypted data to: ") + +with open(ciphertext, "rb") as cfile: + plaintext, result, verify_result = gpg.Context().decrypt(cfile) + +with open(newfile, "wb") as nfile: + nfile.write(plaintext) diff --git a/lang/python/examples/howto/detach-sign-file.py b/lang/python/examples/howto/detach-sign-file.py new file mode 100755 index 00000000..99fbe65e --- /dev/null +++ b/lang/python/examples/howto/detach-sign-file.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +""" +Signs a file with a specified key. If entering both the key and the filename +on the command line, the key must be entered first. + +Will produce both an ASCII armoured and GPG binary format copy of the detached +signature file. +""" + +if len(sys.argv) > 3: + logrus = sys.argv[1] + filename = " ".join(sys.argv[2:]) +elif len(sys.argv) == 3: + logrus = sys.argv[1] + filename = sys.argv[2] +elif len(sys.argv) == 2: + logrus = sys.argv[1] + filename = input("Enter the path and filename to sign: ") +else: + logrus = input("Enter the fingerprint or key ID to sign with: ") + filename = input("Enter the path and filename to sign: ") + +with open(filename, "rb") as f: + text = f.read() + +key = list(gpg.Context().keylist(pattern=logrus)) + +with gpg.Context(armor=True, signers=key) as ca: + signed_data, result = ca.sign(text, mode=gpg.constants.sig.mode.DETACH) + with open("{0}.asc".format(filename), "wb") as fa: + fa.write(signed_data) + +with gpg.Context(signers=key) as cb: + signed_data, result = cb.sign(text, mode=gpg.constants.sig.mode.DETACH) + with open("{0}.sig".format(filename), "wb") as fb: + fb.write(signed_data) diff --git a/lang/python/examples/howto/encrypt-file.py b/lang/python/examples/howto/encrypt-file.py new file mode 100755 index 00000000..ad4e1cef --- /dev/null +++ b/lang/python/examples/howto/encrypt-file.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +""" +Encrypts a file to a specified key. If entering both the key and the filename +on the command line, the key must be entered first. + +Will produce both an ASCII armoured and GPG binary format copy of the encrypted +file. +""" + +if len(sys.argv) > 3: + a_key = sys.argv[1] + filename = " ".join(sys.argv[2:]) +elif len(sys.argv) == 3: + a_key = sys.argv[1] + filename = sys.argv[2] +elif len(sys.argv) == 2: + a_key = sys.argv[1] + filename = input("Enter the path and filename to encrypt: ") +else: + a_key = input("Enter the fingerprint or key ID to encrypt to: ") + filename = input("Enter the path and filename to encrypt: ") + +rkey = list(gpg.Context().keylist(pattern=a_key, secret=False)) +with open(filename, "rb") as f: + text = f.read() + +with gpg.Context(armor=True) as ca: + try: + ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey, + sign=False) + with open("{0}.asc".format(filename), "wb") as fa: + fa.write(ciphertext) + except gpg.errors.InvalidRecipients as e: + print(e) + +with gpg.Context() as cg: + try: + ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey, + sign=False) + with open("{0}.gpg".format(filename), "wb") as fg: + fg.write(ciphertext) + except gpg.errors.InvalidRecipients as e: + print(e) diff --git a/lang/python/examples/howto/encrypt-sign-file.py b/lang/python/examples/howto/encrypt-sign-file.py new file mode 100755 index 00000000..41aaac86 --- /dev/null +++ b/lang/python/examples/howto/encrypt-sign-file.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +""" +Signs and encrypts a file to a specified key. If entering both the key and the +filename on the command line, the key must be entered first. + +Signs with and also encrypts to the default key of the user invoking the +script. Will treat all recipients as trusted to permit encryption. + +Will produce both an ASCII armoured and GPG binary format copy of the signed +and encrypted file. +""" + +if len(sys.argv) > 3: + a_key = sys.argv[1] + filename = " ".join(sys.argv[2:]) +elif len(sys.argv) == 3: + a_key = sys.argv[1] + filename = sys.argv[2] +elif len(sys.argv) == 2: + a_key = sys.argv[1] + filename = input("Enter the path and filename to encrypt: ") +else: + a_key = input("Enter the fingerprint or key ID to encrypt to: ") + filename = input("Enter the path and filename to encrypt: ") + +rkey = list(gpg.Context().keylist(pattern=a_key, secret=False)) +with open(filename, "rb") as f: + text = f.read() + +with gpg.Context(armor=True) as ca: + ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey, + always_trust=True, + add_encrypt_to=True) + with open("{0}.asc".format(filename), "wb") as fa: + fa.write(ciphertext) + +with gpg.Context() as cg: + ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey, + always_trust=True, + add_encrypt_to=True) + with open("{0}.gpg".format(filename), "wb") as fg: + fg.write(ciphertext) diff --git a/lang/python/examples/howto/groups.py b/lang/python/examples/howto/groups.py new file mode 100644 index 00000000..5e7fdf60 --- /dev/null +++ b/lang/python/examples/howto/groups.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import subprocess + +""" +Intended for use with other scripts. + +Usage: from groups import group_lists +""" + +lines = subprocess.getoutput("gpgconf --list-options gpg").splitlines() + +for i in range(len(lines)): + if lines[i].startswith("group") is True: + line = lines[i] + else: + pass + +groups = line.split(":")[-1].replace('"', '').split(',') + +group_lines = groups +for i in range(len(group_lines)): + group_lines[i] = group_lines[i].split("=") + +group_lists = group_lines +for i in range(len(group_lists)): + group_lists[i][1] = group_lists[i][1].split() diff --git a/lang/python/examples/howto/keycount.py b/lang/python/examples/howto/keycount.py new file mode 100755 index 00000000..8e25454c --- /dev/null +++ b/lang/python/examples/howto/keycount.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg + +c = gpg.Context() +seckeys = c.keylist(pattern=None, secret=True) +pubkeys = c.keylist(pattern=None, secret=False) + +seclist = list(seckeys) +secnum = len(seclist) + +publist = list(pubkeys) +pubnum = len(publist) + +print(""" +Number of secret keys: {0} +Number of public keys: {1} +""".format(secnum, pubnum)) diff --git a/lang/python/examples/howto/sign-file.py b/lang/python/examples/howto/sign-file.py new file mode 100755 index 00000000..01006df0 --- /dev/null +++ b/lang/python/examples/howto/sign-file.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys + +""" +Signs a file with a specified key. If entering both the key and the filename +on the command line, the key must be entered first. + +Will produce both an ASCII armoured and GPG binary format copy of the signed +file. +""" + +if len(sys.argv) > 3: + logrus = sys.argv[1] + filename = " ".join(sys.argv[2:]) +elif len(sys.argv) == 3: + logrus = sys.argv[1] + filename = sys.argv[2] +elif len(sys.argv) == 2: + logrus = sys.argv[1] + filename = input("Enter the path and filename to sign: ") +else: + logrus = input("Enter the fingerprint or key ID to sign with: ") + filename = input("Enter the path and filename to sign: ") + +with open(filename, "rb") as f: + text = f.read() + +key = list(gpg.Context().keylist(pattern=logrus)) + +with gpg.Context(armor=True, signers=key) as ca: + signed_data, result = ca.sign(text, mode=gpg.constants.sig.mode.NORMAL) + with open("{0}.asc".format(filename), "wb") as fa: + fa.write(signed_data) + +with gpg.Context(signers=key) as cg: + signed_data, result = cg.sign(text, mode=gpg.constants.sig.mode.NORMAL) + with open("{0}.gpg".format(filename), "wb") as fg: + fg.write(signed_data) diff --git a/lang/python/examples/howto/verify-signatures.py b/lang/python/examples/howto/verify-signatures.py new file mode 100755 index 00000000..8aafc3ba --- /dev/null +++ b/lang/python/examples/howto/verify-signatures.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys +import time + +""" +Verifies a signed file which has been signed with a detached signature. +""" + +if len(sys.argv) > 2: + filename = sys.argv[1] + sig_file = sys.argv[2] +elif len(sys.argv) == 2: + filename = sys.argv[1] + sig_file = input("Enter the path and filename of the detached signature: ") +else: + filename = input("Enter the path and filename to verify: ") + sig_file = input("Enter the path and filename of the detached signature: ") + +c = gpg.Context() + +try: + data, result = c.verify(open(filename), open(sig_file)) + verified = True +except gpg.errors.BadSignatures as e: + verified = False + print(e) + +if verified is True: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: +{0} +with key {1} +made at {2} +""".format(c.get_key(sign.fpr).uids[0].uid, sign.fpr, + time.ctime(sign.timestamp))) +else: + pass diff --git a/lang/python/examples/howto/verify-signed-file.py b/lang/python/examples/howto/verify-signed-file.py new file mode 100755 index 00000000..9f8702f5 --- /dev/null +++ b/lang/python/examples/howto/verify-signed-file.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, unicode_literals + +# Copyright (C) 2018 Ben McGinnes +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 2 of the License, or (at your option) any later +# version. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation; either version 2.1 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU +# Lesser General Public Licensefor more details. +# +# You should have received a copy of the GNU General Public License and the GNU +# Lesser General Public along with this program; if not, see +# . + +import gpg +import sys +import time + +""" +Verifies a signed file which has been signed with either NORMAL or CLEAR modes. +""" + +if len(sys.argv) > 2: + filename = " ".join(sys.argv[1:]) +elif len(sys.argv) == 2: + filename = sys.argv[1] +else: + filename = input("Enter the path and filename to sign: ") + +c = gpg.Context() + +try: + data, result = c.verify(open(filename)) + verified = True +except gpg.errors.BadSignatures as e: + verified = False + print(e) + +if verified is True: + for i in range(len(result.signatures)): + sign = result.signatures[i] + print("""Good signature from: +{0} +with key {1} +made at {2} +""".format(c.get_key(sign.fpr).uids[0].uid, sign.fpr, + time.ctime(sign.timestamp))) +else: + pass diff --git a/lang/python/examples/encrypt-to-all.py b/lang/python/examples/low_level-encrypt_to_all.py similarity index 100% rename from lang/python/examples/encrypt-to-all.py rename to lang/python/examples/low_level-encrypt_to_all.py diff --git a/src/gpgme-tool.c b/src/gpgme-tool.c index 3e2dc785..e7a7a6f3 100644 --- a/src/gpgme-tool.c +++ b/src/gpgme-tool.c @@ -1,3448 +1,3448 @@ /* gpgme-tool.c - Assuan server exposing GnuPG Made Easy operations. Copyright (C) 2009, 2010, 2012, 2013 g10 Code GmbH Copyright (C) 2001, 2003, 2009, 2011 Free Software Foundation, Inc. This file is part of GPGME. GPGME is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. GPGME is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include #include "argparse.h" #include "gpgme.h" /* GCC attributes. */ #if __GNUC__ >= 4 # define GT_GCC_A_SENTINEL(a) __attribute__ ((sentinel(a))) #else # define GT_GCC_A_SENTINEL(a) #endif #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) # define GT_GCC_A_PRINTF(f, a) __attribute__ ((format (printf,f,a))) #else # define GT_GCC_A_PRINTF(f, a) #endif #define DIM(v) (sizeof(v)/sizeof((v)[0])) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) /* MEMBUF */ /* A simple implementation of a dynamic buffer. Use init_membuf() to create a buffer, put_membuf to append bytes and get_membuf to release and return the buffer. Allocation errors are detected but only returned at the final get_membuf(), this helps not to clutter the code with out-of-core checks. */ /* The definition of the structure is private, we only need it here, so it can be allocated on the stack. */ struct private_membuf_s { size_t len; size_t size; char *buf; int out_of_core; }; typedef struct private_membuf_s membuf_t; /* Return the current length of the membuf. */ #define get_membuf_len(a) ((a)->len) #define is_membuf_ready(a) ((a)->buf || (a)->out_of_core) #define MEMBUF_ZERO { 0, 0, NULL, 0} static void init_membuf (membuf_t *mb, int initiallen) { mb->len = 0; mb->size = initiallen; mb->out_of_core = 0; mb->buf = malloc (initiallen); if (!mb->buf) mb->out_of_core = errno; } /* Shift the the content of the membuf MB by AMOUNT bytes. The next operation will then behave as if AMOUNT bytes had not been put into the buffer. If AMOUNT is greater than the actual accumulated bytes, the membuf is basically reset to its initial state. */ #if 0 /* Not yet used. */ static void clear_membuf (membuf_t *mb, size_t amount) { /* No need to clear if we are already out of core. */ if (mb->out_of_core) return; if (amount >= mb->len) mb->len = 0; else { mb->len -= amount; memmove (mb->buf, mb->buf+amount, mb->len); } } #endif /* unused */ static void put_membuf (membuf_t *mb, const void *buf, size_t len) { if (mb->out_of_core || !len) return; if (mb->len + len >= mb->size) { char *p; mb->size += len + 1024; p = realloc (mb->buf, mb->size); if (!p) { mb->out_of_core = errno ? errno : ENOMEM; return; } mb->buf = p; } memcpy (mb->buf + mb->len, buf, len); mb->len += len; } #if 0 /* Not yet used. */ static void put_membuf_str (membuf_t *mb, const char *string) { put_membuf (mb, string, strlen (string)); } #endif /* unused */ static void * get_membuf (membuf_t *mb, size_t *len) { char *p; if (mb->out_of_core) { if (mb->buf) { free (mb->buf); mb->buf = NULL; } gpg_err_set_errno (mb->out_of_core); return NULL; } p = mb->buf; if (len) *len = mb->len; mb->buf = NULL; mb->out_of_core = ENOMEM; /* hack to make sure it won't get reused. */ return p; } /* Peek at the membuf MB. On success a pointer to the buffer is returned which is valid until the next operation on MB. If LEN is not NULL the current LEN of the buffer is stored there. On error NULL is returned and ERRNO is set. */ #if 0 /* Not yet used. */ static const void * peek_membuf (membuf_t *mb, size_t *len) { const char *p; if (mb->out_of_core) { gpg_err_set_errno (mb->out_of_core); return NULL; } p = mb->buf; if (len) *len = mb->len; return p; } #endif /* unused */ /* SUPPORT. */ FILE *log_stream; char program_name[] = "gpgme-tool"; #define spacep(p) (*(p) == ' ' || *(p) == '\t') void log_error (int status, gpg_error_t errnum, const char *fmt, ...) GT_GCC_A_PRINTF(3,4); void log_init (void) { log_stream = stderr; } void log_error (int status, gpg_error_t errnum, const char *fmt, ...) { va_list ap; fprintf (log_stream, "%s: ", program_name); va_start (ap, fmt); vfprintf (log_stream, fmt, ap); va_end (ap); if (errnum) { fprintf (log_stream, ": %s", gpg_strerror (errnum)); if (gpg_err_source (errnum) != GPG_ERR_SOURCE_GPGME) fprintf (log_stream, " <%s>", gpg_strsource (errnum)); } fprintf (log_stream, "\n"); if (status) exit (status); } /* Note that it is sufficient to allocate the target string D as long as the source string S, i.e.: strlen(s)+1;. D == S is allowed. */ static void strcpy_escaped_plus (char *d, const char *s) { while (*s) { if (*s == '%' && s[1] && s[2]) { s++; *d++ = xtoi_2 (s); s += 2; } else if (*s == '+') *d++ = ' ', s++; else *d++ = *s++; } *d = 0; } /* Check whether the option NAME appears in LINE. */ static int has_option (const char *line, const char *name) { const char *s; int n = strlen (name); s = strstr (line, name); return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n))); } /* Skip over options. It is assumed that leading spaces have been removed (this is the case for lines passed to a handler from assuan). Blanks after the options are also removed. */ static char * skip_options (char *line) { while ( *line == '-' && line[1] == '-' ) { while (*line && !spacep (line)) line++; while (spacep (line)) line++; } return line; } typedef gpg_error_t (*result_xml_write_cb_t) (void *hook, const void *buf, size_t len); static char xml_preamble1[] = "\n"; static const char xml_preamble2[] = "\n"; static const char xml_end[] = "\n"; struct result_xml_state { int indent; result_xml_write_cb_t cb; void *hook; #define MAX_TAGS 20 int next_tag; const char *tag[MAX_TAGS]; int had_data[MAX_TAGS]; }; void result_init (struct result_xml_state *state, int indent, result_xml_write_cb_t cb, void *hook) { memset (state, '\0', sizeof (*state)); state->indent = indent; state->cb = cb; state->hook = hook; } gpg_error_t result_xml_indent (struct result_xml_state *state) { char spaces[state->indent + 1]; int i; for (i = 0; i < state->indent; i++) spaces[i] = ' '; spaces[i] = '\0'; return (*state->cb) (state->hook, spaces, i); } gpg_error_t result_xml_tag_start (struct result_xml_state *state, const char *name, ...) { result_xml_write_cb_t cb = state->cb; void *hook = state->hook; va_list ap; char *attr; char *attr_val; char string_null[] = "(null)"; va_start (ap, name); if (state->next_tag > 0) { if (! state->had_data[state->next_tag - 1]) { (*cb) (hook, ">\n", 2); (*cb) (hook, NULL, 0); } state->had_data[state->next_tag - 1] = 1; } result_xml_indent (state); (*cb) (hook, "<", 1); (*cb) (hook, name, strlen (name)); state->tag[state->next_tag] = name; state->had_data[state->next_tag] = 0; state->indent += 2; state->next_tag++; while (1) { attr = va_arg (ap, char *); if (attr == NULL) break; attr_val = va_arg (ap, char *); if (attr_val == NULL) attr_val = string_null; (*cb) (hook, " ", 1); (*cb) (hook, attr, strlen (attr)); (*cb) (hook, "=\"", 2); (*cb) (hook, attr_val, strlen (attr_val)); (*cb) (hook, "\"", 1); } va_end (ap); return 0; } /* Return a constant string with an XML entity for C. */ static const char * result_xml_escape_replacement(char c) { switch (c) { case '<': return "<"; case '>': return ">"; case '&': return "&"; default: return NULL; } } /* Escape DATA by replacing certain characters with their XML entities. The result is stored in a newly allocated buffer which address will be stored at BUF. Returns 0 on success. */ static gpg_error_t result_xml_escape (const char *data, char **buf) { int data_len, i; const char *r; membuf_t mb; init_membuf (&mb, 128); if (data) { data_len = strlen (data); for (i = 0; i < data_len; i++) { r = result_xml_escape_replacement (data[i]); if (r) put_membuf (&mb, r, strlen (r)); else put_membuf (&mb, data+i, 1); } } put_membuf (&mb, "", 1); *buf = get_membuf (&mb, NULL); return *buf? 0 : gpg_error_from_syserror (); } gpg_error_t result_xml_tag_data (struct result_xml_state *state, const char *data) { gpg_error_t err; result_xml_write_cb_t cb = state->cb; void *hook = state->hook; char *buf = NULL; if (state->had_data[state->next_tag - 1]) { (*cb) (hook, "\n", 2); (*cb) (hook, NULL, 0); result_xml_indent (state); } else (*cb) (hook, ">", 1); state->had_data[state->next_tag - 1] = 2; err = result_xml_escape (data, &buf); if (err) return err; (*cb) (hook, buf, strlen (buf)); free (buf); return 0; } gpg_error_t result_xml_tag_end (struct result_xml_state *state) { result_xml_write_cb_t cb = state->cb; void *hook = state->hook; state->next_tag--; state->indent -= 2; if (state->had_data[state->next_tag]) { if (state->had_data[state->next_tag] == 1) result_xml_indent (state); (*cb) (hook, "tag[state->next_tag], strlen (state->tag[state->next_tag])); (*cb) (hook, ">\n", 2); (*cb) (hook, NULL, 0); } else { (*cb) (hook, " />\n", 4); (*cb) (hook, NULL, 0); } return 0; } gpg_error_t result_add_error (struct result_xml_state *state, const char *name, gpg_error_t err) { char code[20]; char msg[1024]; snprintf (code, sizeof (code) - 1, "0x%x", err); snprintf (msg, sizeof (msg) - 1, "%s <%s>", gpg_strerror (err), gpg_strsource (err)); result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_data (state, msg); result_xml_tag_end (state); return 0; } gpg_error_t result_add_pubkey_algo (struct result_xml_state *state, const char *name, gpgme_pubkey_algo_t algo) { char code[20]; char msg[80]; snprintf (code, sizeof (code) - 1, "0x%x", algo); snprintf (msg, sizeof (msg) - 1, "%s", gpgme_pubkey_algo_name (algo)); result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_data (state, msg); result_xml_tag_end (state); return 0; } gpg_error_t result_add_hash_algo (struct result_xml_state *state, const char *name, gpgme_hash_algo_t algo) { char code[20]; char msg[80]; snprintf (code, sizeof (code) - 1, "0x%x", algo); snprintf (msg, sizeof (msg) - 1, "%s", gpgme_hash_algo_name (algo)); result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_data (state, msg); result_xml_tag_end (state); return 0; } gpg_error_t result_add_keyid (struct result_xml_state *state, const char *name, const char *keyid) { result_xml_tag_start (state, name, NULL); result_xml_tag_data (state, keyid); result_xml_tag_end (state); return 0; } gpg_error_t result_add_fpr (struct result_xml_state *state, const char *name, const char *fpr) { result_xml_tag_start (state, name, NULL); result_xml_tag_data (state, fpr); result_xml_tag_end (state); return 0; } gpg_error_t result_add_timestamp (struct result_xml_state *state, const char *name, unsigned int timestamp) { char code[20]; snprintf (code, sizeof (code) - 1, "%ui", timestamp); result_xml_tag_start (state, name, "unix", code, NULL); result_xml_tag_end (state); return 0; } gpg_error_t result_add_sig_mode (struct result_xml_state *state, const char *name, gpgme_sig_mode_t sig_mode) { const char *mode; char code[20]; snprintf (code, sizeof (code) - 1, "%i", sig_mode); switch (sig_mode) { case GPGME_SIG_MODE_NORMAL: mode = "normal"; break; case GPGME_SIG_MODE_DETACH: mode = "detach"; break; case GPGME_SIG_MODE_CLEAR: mode = "clear"; break; default: mode = "unknown"; } result_xml_tag_start (state, name, "type", mode, "value", code, NULL); result_xml_tag_data (state, mode); result_xml_tag_end (state); return 0; } gpg_error_t result_add_protocol (struct result_xml_state *state, const char *name, gpgme_protocol_t protocol) { const char *str; char code[20]; snprintf (code, sizeof (code) - 1, "%i", protocol); str = gpgme_get_protocol_name(protocol); if (!str) str = "invalid"; result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_data (state, str); result_xml_tag_end (state); return 0; } gpg_error_t result_add_validity (struct result_xml_state *state, const char *name, gpgme_validity_t validity) { const char *str; char code[20]; snprintf (code, sizeof (code) - 1, "%i", validity); switch (validity) { case GPGME_VALIDITY_UNDEFINED: str ="undefined"; break; case GPGME_VALIDITY_NEVER: str ="never"; break; case GPGME_VALIDITY_MARGINAL: str ="marginal"; break; case GPGME_VALIDITY_FULL: str ="full"; break; case GPGME_VALIDITY_ULTIMATE: str ="ultimate"; break; default: str ="unknown"; } result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_data (state, str); result_xml_tag_end (state); return 0; } gpg_error_t result_add_value (struct result_xml_state *state, const char *name, unsigned int val) { char code[20]; snprintf (code, sizeof (code) - 1, "0x%x", val); result_xml_tag_start (state, name, "value", code, NULL); result_xml_tag_end (state); return 0; } gpg_error_t result_add_string (struct result_xml_state *state, const char *name, const char *str) { if (!str) str = ""; result_xml_tag_start (state, name, NULL); result_xml_tag_data (state, str); result_xml_tag_end (state); return 0; } gpg_error_t result_encrypt_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_encrypt_result_t res = gpgme_op_encrypt_result (ctx); gpgme_invalid_key_t inv_recp; if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "encrypt-result", NULL); inv_recp = res->invalid_recipients; if (inv_recp) { result_xml_tag_start (&state, "invalid-recipients", NULL); while (inv_recp) { result_xml_tag_start (&state, "invalid-key", NULL); if (inv_recp->fpr) result_add_fpr (&state, "fpr", inv_recp->fpr); result_add_error (&state, "reason", inv_recp->reason); result_xml_tag_end (&state); inv_recp = inv_recp->next; } result_xml_tag_end (&state); } result_xml_tag_end (&state); return 0; } gpg_error_t result_decrypt_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_decrypt_result_t res = gpgme_op_decrypt_result (ctx); gpgme_recipient_t recp; if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "decrypt-result", NULL); if (res->file_name) { result_xml_tag_start (&state, "file-name", NULL); result_xml_tag_data (&state, res->file_name); result_xml_tag_end (&state); } if (res->unsupported_algorithm) { result_xml_tag_start (&state, "unsupported-alogorithm", NULL); result_xml_tag_data (&state, res->unsupported_algorithm); result_xml_tag_end (&state); } if (res->wrong_key_usage) { result_xml_tag_start (&state, "wrong-key-usage", NULL); result_xml_tag_end (&state); } recp = res->recipients; if (recp) { result_xml_tag_start (&state, "recipients", NULL); while (recp) { result_xml_tag_start (&state, "recipient", NULL); result_add_keyid (&state, "keyid", recp->keyid); result_add_pubkey_algo (&state, "pubkey-algo", recp->pubkey_algo); result_add_error (&state, "status", recp->status); result_xml_tag_end (&state); recp = recp->next; } result_xml_tag_end (&state); } result_xml_tag_end (&state); return 0; } gpg_error_t result_sign_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_sign_result_t res = gpgme_op_sign_result (ctx); gpgme_invalid_key_t inv_key; gpgme_new_signature_t new_sig; if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "sign-result", NULL); inv_key = res->invalid_signers; if (inv_key) { result_xml_tag_start (&state, "invalid-signers", NULL); while (inv_key) { result_xml_tag_start (&state, "invalid-key", NULL); if (inv_key->fpr) result_add_fpr (&state, "fpr", inv_key->fpr); result_add_error (&state, "reason", inv_key->reason); result_xml_tag_end (&state); inv_key = inv_key->next; } result_xml_tag_end (&state); } new_sig = res->signatures; if (new_sig) { result_xml_tag_start (&state, "signatures", NULL); while (new_sig) { result_xml_tag_start (&state, "new-signature", NULL); result_add_sig_mode (&state, "type", new_sig->type); result_add_pubkey_algo (&state, "pubkey-algo", new_sig->pubkey_algo); result_add_hash_algo (&state, "hash-algo", new_sig->hash_algo); result_add_timestamp (&state, "timestamp", new_sig->timestamp); if (new_sig->fpr) result_add_fpr (&state, "fpr", new_sig->fpr); result_add_value (&state, "sig-class", new_sig->sig_class); result_xml_tag_end (&state); new_sig = new_sig->next; } result_xml_tag_end (&state); } result_xml_tag_end (&state); return 0; } gpg_error_t result_verify_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_verify_result_t res = gpgme_op_verify_result (ctx); gpgme_signature_t sig; if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "verify-result", NULL); if (res->file_name) { result_xml_tag_start (&state, "file-name", NULL); result_xml_tag_data (&state, res->file_name); result_xml_tag_end (&state); } sig = res->signatures; if (sig) { result_xml_tag_start (&state, "signatures", NULL); while (sig) { result_xml_tag_start (&state, "signature", NULL); /* FIXME: Could be done better. */ result_add_value (&state, "summary", sig->summary); if (sig->fpr) result_add_fpr (&state, "fpr", sig->fpr); result_add_error (&state, "status", sig->status); /* FIXME: notations */ result_add_timestamp (&state, "timestamp", sig->timestamp); result_add_timestamp (&state, "exp-timestamp", sig->exp_timestamp); result_add_value (&state, "wrong-key-usage", sig->wrong_key_usage); result_add_value (&state, "pka-trust", sig->pka_trust); result_add_value (&state, "chain-model", sig->chain_model); result_add_value (&state, "validity", sig->validity); result_add_error (&state, "validity-reason", sig->validity_reason); result_add_pubkey_algo (&state, "pubkey-algo", sig->pubkey_algo); result_add_hash_algo (&state, "hash-algo", sig->hash_algo); if (sig->pka_address) result_add_string (&state, "pka_address", sig->pka_address); result_xml_tag_end (&state); sig = sig->next; } result_xml_tag_end (&state); } result_xml_tag_end (&state); return 0; } gpg_error_t result_import_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_import_result_t res = gpgme_op_import_result (ctx); gpgme_import_status_t stat; if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "import-result", NULL); result_add_value (&state, "considered", res->considered); result_add_value (&state, "no-user-id", res->no_user_id); result_add_value (&state, "imported", res->imported); result_add_value (&state, "imported-rsa", res->imported_rsa); result_add_value (&state, "unchanged", res->unchanged); result_add_value (&state, "new-user-ids", res->new_user_ids); result_add_value (&state, "new-sub-keys", res->new_sub_keys); result_add_value (&state, "new-signatures", res->new_signatures); result_add_value (&state, "new-revocations", res->new_revocations); result_add_value (&state, "secret-read", res->secret_read); result_add_value (&state, "secret-imported", res->secret_imported); result_add_value (&state, "secret-unchanged", res->secret_unchanged); result_add_value (&state, "skipped-new-keys", res->skipped_new_keys); result_add_value (&state, "not-imported", res->not_imported); stat = res->imports; if (stat) { result_xml_tag_start (&state, "imports", NULL); while (stat) { result_xml_tag_start (&state, "import-status", NULL); if (stat->fpr) result_add_fpr (&state, "fpr", stat->fpr); result_add_error (&state, "result", stat->result); /* FIXME: Could be done better. */ result_add_value (&state, "status", stat->status); result_xml_tag_end (&state); stat = stat->next; } result_xml_tag_end (&state); } result_xml_tag_end (&state); return 0; } gpg_error_t result_genkey_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_genkey_result_t res = gpgme_op_genkey_result (ctx); if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "genkey-result", NULL); result_add_value (&state, "primary", res->primary); result_add_value (&state, "sub", res->sub); if (res->fpr) result_add_fpr (&state, "fpr", res->fpr); result_xml_tag_end (&state); return 0; } gpg_error_t result_keylist_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_keylist_result_t res = gpgme_op_keylist_result (ctx); if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "keylist-result", NULL); result_add_value (&state, "truncated", res->truncated); result_xml_tag_end (&state); return 0; } gpg_error_t result_vfs_mount_to_xml (gpgme_ctx_t ctx, int indent, result_xml_write_cb_t cb, void *hook) { struct result_xml_state state; gpgme_vfs_mount_result_t res = gpgme_op_vfs_mount_result (ctx); if (! res) return 0; result_init (&state, indent, cb, hook); result_xml_tag_start (&state, "vfs-mount-result", NULL); result_add_string (&state, "mount-dir", res->mount_dir); result_xml_tag_end (&state); return 0; } typedef enum status { STATUS_PROTOCOL, STATUS_PROGRESS, STATUS_ENGINE, STATUS_ARMOR, STATUS_TEXTMODE, STATUS_INCLUDE_CERTS, STATUS_KEYLIST_MODE, STATUS_RECIPIENT, STATUS_ENCRYPT_RESULT, STATUS_IDENTIFY_RESULT } status_t; const char *status_string[] = { "PROTOCOL", "PROGRESS", "ENGINE", "ARMOR", "TEXTMODE", "INCLUDE_CERTS", "KEYLIST_MODE", "RECIPIENT", "ENCRYPT_RESULT", "IDENTIFY_RESULT" }; struct gpgme_tool { gpgme_ctx_t ctx; #define MAX_RECIPIENTS 10 gpgme_key_t recipients[MAX_RECIPIENTS + 1]; int recipients_nr; gpg_error_t (*write_status) (void *hook, const char *status, const char *msg); void *write_status_hook; gpg_error_t (*write_data) (void *hook, const void *buf, size_t len); void *write_data_hook; }; typedef struct gpgme_tool *gpgme_tool_t; /* Forward declaration. */ void gt_write_status (gpgme_tool_t gt, status_t status, ...) GT_GCC_A_SENTINEL(0); static gpg_error_t server_passphrase_cb (void *opaque, const char *uid_hint, const char *info, int was_bad, int fd); void _gt_progress_cb (void *opaque, const char *what, int type, int current, int total) { gpgme_tool_t gt = opaque; char buf[100]; snprintf (buf, sizeof (buf), "0x%02x %i %i", type, current, total); gt_write_status (gt, STATUS_PROGRESS, what, buf, NULL); } gpg_error_t _gt_gpgme_new (gpgme_tool_t gt, gpgme_ctx_t *ctx) { gpg_error_t err; err = gpgme_new (ctx); if (err) return err; gpgme_set_progress_cb (*ctx, _gt_progress_cb, gt); return 0; } void gt_init (gpgme_tool_t gt) { gpg_error_t err; memset (gt, '\0', sizeof (*gt)); err = _gt_gpgme_new (gt, >->ctx); if (err) log_error (1, err, "can't create gpgme context"); } gpg_error_t gt_signers_add (gpgme_tool_t gt, const char *fpr) { gpg_error_t err; gpgme_key_t key; err = gpgme_get_key (gt->ctx, fpr, &key, 0); if (err) return err; return gpgme_signers_add (gt->ctx, key); } gpg_error_t gt_signers_clear (gpgme_tool_t gt) { gpgme_signers_clear (gt->ctx); return 0; } gpg_error_t gt_get_key (gpgme_tool_t gt, const char *pattern, gpgme_key_t *r_key) { gpgme_ctx_t ctx; gpgme_ctx_t listctx; gpgme_error_t err; gpgme_key_t key; if (!gt || !r_key || !pattern) return gpg_error (GPG_ERR_INV_VALUE); ctx = gt->ctx; err = gpgme_new (&listctx); if (err) return err; { gpgme_protocol_t proto; gpgme_engine_info_t info; /* Clone the relevant state. */ proto = gpgme_get_protocol (ctx); /* The g13 protocol does not allow keylisting, we need to choose something else. */ if (proto == GPGME_PROTOCOL_G13) proto = GPGME_PROTOCOL_OpenPGP; gpgme_set_protocol (listctx, proto); gpgme_set_keylist_mode (listctx, gpgme_get_keylist_mode (ctx)); info = gpgme_ctx_get_engine_info (ctx); while (info && info->protocol != proto) info = info->next; if (info) gpgme_ctx_set_engine_info (listctx, proto, info->file_name, info->home_dir); } err = gpgme_op_keylist_start (listctx, pattern, 0); if (!err) err = gpgme_op_keylist_next (listctx, r_key); if (!err) { try_next_key: err = gpgme_op_keylist_next (listctx, &key); if (gpgme_err_code (err) == GPG_ERR_EOF) err = 0; else { if (!err && *r_key && (*r_key)->subkeys && (*r_key)->subkeys->fpr && key && key->subkeys && key->subkeys->fpr && !strcmp ((*r_key)->subkeys->fpr, key->subkeys->fpr)) { /* The fingerprint is identical. We assume that this is the same key and don't mark it as an ambiguous. This problem may occur with corrupted keyrings and has been noticed often with gpgsm. In fact gpgsm uses a similar hack to sort out such duplicates but it can't do that while listing keys. */ gpgme_key_unref (key); goto try_next_key; } if (!err) { gpgme_key_unref (key); err = gpg_error (GPG_ERR_AMBIGUOUS_NAME); } gpgme_key_unref (*r_key); } } gpgme_release (listctx); if (! err) gt_write_status (gt, STATUS_RECIPIENT, ((*r_key)->subkeys && (*r_key)->subkeys->fpr) ? (*r_key)->subkeys->fpr : "invalid", NULL); return err; } gpg_error_t gt_recipients_add (gpgme_tool_t gt, const char *pattern) { gpg_error_t err; gpgme_key_t key; if (gt->recipients_nr >= MAX_RECIPIENTS) return gpg_error (GPG_ERR_ENOMEM); if (gpgme_get_protocol (gt->ctx) == GPGME_PROTOCOL_UISERVER) err = gpgme_key_from_uid (&key, pattern); else err = gt_get_key (gt, pattern, &key); if (err) return err; gt->recipients[gt->recipients_nr++] = key; return 0; } void gt_recipients_clear (gpgme_tool_t gt) { int idx; for (idx = 0; idx < gt->recipients_nr; idx++) gpgme_key_unref (gt->recipients[idx]); memset (gt->recipients, '\0', gt->recipients_nr * sizeof (gpgme_key_t)); gt->recipients_nr = 0; } gpg_error_t gt_reset (gpgme_tool_t gt) { gpg_error_t err; gpgme_ctx_t ctx; err = _gt_gpgme_new (gt, &ctx); if (err) return err; gpgme_release (gt->ctx); gt->ctx = ctx; gt_recipients_clear (gt); return 0; } void gt_write_status (gpgme_tool_t gt, status_t status, ...) { va_list ap; const char *text; char buf[950]; char *p; size_t n; gpg_error_t err; va_start (ap, status); p = buf; n = 0; while ((text = va_arg (ap, const char *))) { if (n) { *p++ = ' '; n++; } while (*text && n < sizeof (buf) - 2) { *p++ = *text++; n++; } } *p = 0; va_end (ap); err = gt->write_status (gt->write_status_hook, status_string[status], buf); if (err) log_error (1, err, "can't write status line"); } gpg_error_t gt_write_data (gpgme_tool_t gt, const void *buf, size_t len) { return gt->write_data (gt->write_data_hook, buf, len); } gpg_error_t gt_get_engine_info (gpgme_tool_t gt, gpgme_protocol_t proto) { gpgme_engine_info_t info; info = gpgme_ctx_get_engine_info (gt->ctx); while (info) { if (proto == GPGME_PROTOCOL_UNKNOWN || proto == info->protocol) gt_write_status (gt, STATUS_ENGINE, gpgme_get_protocol_name (info->protocol), info->file_name, info->version, info->req_version, info->home_dir, NULL); info = info->next; } return 0; } gpgme_protocol_t gt_protocol_from_name (const char *name) { if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_OpenPGP))) return GPGME_PROTOCOL_OpenPGP; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_CMS))) return GPGME_PROTOCOL_CMS; if (! strcasecmp (name,gpgme_get_protocol_name (GPGME_PROTOCOL_GPGCONF))) return GPGME_PROTOCOL_GPGCONF; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_ASSUAN))) return GPGME_PROTOCOL_ASSUAN; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_G13))) return GPGME_PROTOCOL_G13; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_UISERVER))) return GPGME_PROTOCOL_UISERVER; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_SPAWN))) return GPGME_PROTOCOL_SPAWN; if (! strcasecmp (name, gpgme_get_protocol_name (GPGME_PROTOCOL_DEFAULT))) return GPGME_PROTOCOL_DEFAULT; return GPGME_PROTOCOL_UNKNOWN; } gpg_error_t gt_set_protocol (gpgme_tool_t gt, gpgme_protocol_t proto) { return gpgme_set_protocol (gt->ctx, proto); } gpg_error_t gt_get_protocol (gpgme_tool_t gt) { gpgme_protocol_t proto = gpgme_get_protocol (gt->ctx); gt_write_status (gt, STATUS_PROTOCOL, gpgme_get_protocol_name (proto), NULL); return 0; } gpg_error_t gt_set_sub_protocol (gpgme_tool_t gt, gpgme_protocol_t proto) { return gpgme_set_sub_protocol (gt->ctx, proto); } gpg_error_t gt_get_sub_protocol (gpgme_tool_t gt) { gpgme_protocol_t proto = gpgme_get_sub_protocol (gt->ctx); gt_write_status (gt, STATUS_PROTOCOL, gpgme_get_protocol_name (proto), NULL); return 0; } gpg_error_t gt_set_pinentry_mode (gpgme_tool_t gt, gpgme_pinentry_mode_t mode, void *opaque) { gpg_error_t err; gpgme_set_passphrase_cb (gt->ctx, NULL, NULL); err = gpgme_set_pinentry_mode (gt->ctx, mode); if (!err && mode == GPGME_PINENTRY_MODE_LOOPBACK) gpgme_set_passphrase_cb (gt->ctx, server_passphrase_cb, opaque); return err; } gpg_error_t gt_set_armor (gpgme_tool_t gt, int armor) { gpgme_set_armor (gt->ctx, armor); return 0; } gpg_error_t gt_get_armor (gpgme_tool_t gt) { gt_write_status (gt, STATUS_ARMOR, gpgme_get_armor (gt->ctx) ? "true" : "false", NULL); return 0; } gpg_error_t gt_set_textmode (gpgme_tool_t gt, int textmode) { gpgme_set_textmode (gt->ctx, textmode); return 0; } gpg_error_t gt_get_textmode (gpgme_tool_t gt) { gt_write_status (gt, STATUS_TEXTMODE, gpgme_get_textmode (gt->ctx) ? "true" : "false", NULL); return 0; } gpg_error_t gt_set_keylist_mode (gpgme_tool_t gt, gpgme_keylist_mode_t keylist_mode) { gpgme_set_keylist_mode (gt->ctx, keylist_mode); return 0; } gpg_error_t gt_get_keylist_mode (gpgme_tool_t gt) { #define NR_KEYLIST_MODES 6 const char *modes[NR_KEYLIST_MODES + 1]; int idx = 0; gpgme_keylist_mode_t mode = gpgme_get_keylist_mode (gt->ctx); if (mode & GPGME_KEYLIST_MODE_LOCAL) modes[idx++] = "local"; if (mode & GPGME_KEYLIST_MODE_EXTERN) modes[idx++] = "extern"; if (mode & GPGME_KEYLIST_MODE_SIGS) modes[idx++] = "sigs"; if (mode & GPGME_KEYLIST_MODE_SIG_NOTATIONS) modes[idx++] = "sig_notations"; if (mode & GPGME_KEYLIST_MODE_WITH_SECRET) modes[idx++] = "with_secret"; if (mode & GPGME_KEYLIST_MODE_EPHEMERAL) modes[idx++] = "ephemeral"; if (mode & GPGME_KEYLIST_MODE_VALIDATE) modes[idx++] = "validate"; modes[idx++] = NULL; gt_write_status (gt, STATUS_KEYLIST_MODE, modes[0], modes[1], modes[2], modes[3], modes[4], modes[5], modes[6], NULL); return 0; } gpg_error_t gt_set_include_certs (gpgme_tool_t gt, int include_certs) { gpgme_set_include_certs (gt->ctx, include_certs); return 0; } gpg_error_t gt_get_include_certs (gpgme_tool_t gt) { int include_certs = gpgme_get_include_certs (gt->ctx); char buf[100]; if (include_certs == GPGME_INCLUDE_CERTS_DEFAULT) strcpy (buf, "default"); else snprintf (buf, sizeof (buf), "%i", include_certs); gt_write_status (gt, STATUS_INCLUDE_CERTS, buf, NULL); return 0; } gpg_error_t gt_decrypt_verify (gpgme_tool_t gt, gpgme_data_t cipher, gpgme_data_t plain, int verify) { if (verify) return gpgme_op_decrypt_verify (gt->ctx, cipher, plain); else return gpgme_op_decrypt (gt->ctx, cipher, plain); } gpg_error_t gt_sign_encrypt (gpgme_tool_t gt, gpgme_encrypt_flags_t flags, gpgme_data_t plain, gpgme_data_t cipher, int sign) { gpg_error_t err; gpgme_key_t *recp; recp = gt->recipients_nr? gt->recipients : NULL; if (sign) err = gpgme_op_encrypt_sign (gt->ctx, recp, flags, plain, cipher); else err = gpgme_op_encrypt (gt->ctx, recp, flags, plain, cipher); gt_recipients_clear (gt); return err; } gpg_error_t gt_sign (gpgme_tool_t gt, gpgme_data_t plain, gpgme_data_t sig, gpgme_sig_mode_t mode) { return gpgme_op_sign (gt->ctx, plain, sig, mode); } gpg_error_t gt_verify (gpgme_tool_t gt, gpgme_data_t sig, gpgme_data_t sig_text, gpgme_data_t plain) { return gpgme_op_verify (gt->ctx, sig, sig_text, plain); } gpg_error_t gt_import (gpgme_tool_t gt, gpgme_data_t data) { return gpgme_op_import (gt->ctx, data); } gpg_error_t gt_export (gpgme_tool_t gt, const char *pattern[], gpgme_export_mode_t mode, gpgme_data_t data) { return gpgme_op_export_ext (gt->ctx, pattern, mode, data); } gpg_error_t gt_genkey (gpgme_tool_t gt, const char *parms, gpgme_data_t public, gpgme_data_t secret) { return gpgme_op_genkey (gt->ctx, parms, public, secret); } gpg_error_t gt_import_keys (gpgme_tool_t gt, char *fpr[]) { gpg_error_t err = 0; int cnt; int idx; gpgme_key_t *keys; cnt = 0; while (fpr[cnt]) cnt++; if (! cnt) return gpg_error (GPG_ERR_INV_VALUE); keys = malloc ((cnt + 1) * sizeof (gpgme_key_t)); if (! keys) return gpg_error_from_syserror (); for (idx = 0; idx < cnt; idx++) { err = gpgme_get_key (gt->ctx, fpr[idx], &keys[idx], 0); if (err) break; } if (! err) { keys[cnt] = NULL; err = gpgme_op_import_keys (gt->ctx, keys); } /* Rollback. */ while (--idx >= 0) gpgme_key_unref (keys[idx]); free (keys); return err; } gpg_error_t gt_delete (gpgme_tool_t gt, char *fpr, int allow_secret) { gpg_error_t err; gpgme_key_t key; err = gpgme_get_key (gt->ctx, fpr, &key, 0); if (err) return err; err = gpgme_op_delete (gt->ctx, key, allow_secret); gpgme_key_unref (key); return err; } gpg_error_t gt_keylist_start (gpgme_tool_t gt, const char *pattern[], int secret_only) { return gpgme_op_keylist_ext_start (gt->ctx, pattern, secret_only, 0); } gpg_error_t gt_keylist_next (gpgme_tool_t gt, gpgme_key_t *key) { return gpgme_op_keylist_next (gt->ctx, key); } gpg_error_t gt_getauditlog (gpgme_tool_t gt, gpgme_data_t output, unsigned int flags) { return gpgme_op_getauditlog (gt->ctx, output, flags); } gpg_error_t gt_vfs_mount (gpgme_tool_t gt, const char *container_file, const char *mount_dir, int flags) { gpg_error_t err; gpg_error_t op_err; err = gpgme_op_vfs_mount (gt->ctx, container_file, mount_dir, flags, &op_err); return err ? err : op_err; } gpg_error_t gt_vfs_create (gpgme_tool_t gt, const char *container_file, int flags) { gpg_error_t err; gpg_error_t op_err; err = gpgme_op_vfs_create (gt->ctx, gt->recipients, container_file, flags, &op_err); gt_recipients_clear (gt); return err ? err : op_err; } gpg_error_t gt_passwd (gpgme_tool_t gt, char *fpr) { gpg_error_t err; gpgme_key_t key; err = gpgme_get_key (gt->ctx, fpr, &key, 0); if (err) return gpg_err_code (err) == GPG_ERR_EOF? gpg_error (GPG_ERR_NO_PUBKEY):err; err = gpgme_op_passwd (gt->ctx, key, 0); gpgme_key_unref (key); return err; } gpg_error_t gt_identify (gpgme_tool_t gt, gpgme_data_t data) { const char *s = "?"; switch (gpgme_data_identify (data, 0)) { case GPGME_DATA_TYPE_INVALID: return gpg_error (GPG_ERR_GENERAL); case GPGME_DATA_TYPE_UNKNOWN : s = "unknown"; break; case GPGME_DATA_TYPE_PGP_SIGNED : s = "PGP-signed"; break; case GPGME_DATA_TYPE_PGP_SIGNATURE: s = "PGP-signature"; break; case GPGME_DATA_TYPE_PGP_ENCRYPTED: s = "PGP-encrypted"; break; case GPGME_DATA_TYPE_PGP_OTHER : s = "PGP"; break; case GPGME_DATA_TYPE_PGP_KEY : s = "PGP-key"; break; case GPGME_DATA_TYPE_CMS_SIGNED : s = "CMS-signed"; break; case GPGME_DATA_TYPE_CMS_ENCRYPTED: s = "CMS-encrypted"; break; case GPGME_DATA_TYPE_CMS_OTHER : s = "CMS"; break; case GPGME_DATA_TYPE_X509_CERT : s = "X.509"; break; case GPGME_DATA_TYPE_PKCS12 : s = "PKCS12"; break; } gt_write_status (gt, STATUS_IDENTIFY_RESULT, s, NULL); return 0; } gpg_error_t gt_spawn (gpgme_tool_t gt, const char *pgm, gpgme_data_t inp, gpgme_data_t outp) { gpg_error_t err; err = gpgme_op_spawn (gt->ctx, pgm, NULL, inp, outp, outp, 0); return err; } #define GT_RESULT_ENCRYPT 0x1 #define GT_RESULT_DECRYPT 0x2 #define GT_RESULT_SIGN 0x4 #define GT_RESULT_VERIFY 0x8 #define GT_RESULT_IMPORT 0x10 #define GT_RESULT_GENKEY 0x20 #define GT_RESULT_KEYLIST 0x40 #define GT_RESULT_VFS_MOUNT 0x80 #define GT_RESULT_ALL (~0U) gpg_error_t gt_result (gpgme_tool_t gt, unsigned int flags) { int indent = 2; gt_write_data (gt, xml_preamble1, strlen (xml_preamble1)); gt_write_data (gt, NULL, 0); gt_write_data (gt, xml_preamble2, strlen (xml_preamble2)); gt_write_data (gt, NULL, 0); if (flags & GT_RESULT_ENCRYPT) result_encrypt_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_DECRYPT) result_decrypt_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_SIGN) result_sign_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_VERIFY) result_verify_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_IMPORT) result_import_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_GENKEY) result_genkey_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_KEYLIST) result_keylist_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); if (flags & GT_RESULT_VFS_MOUNT) result_vfs_mount_to_xml (gt->ctx, indent, (result_xml_write_cb_t) gt_write_data, gt); gt_write_data (gt, xml_end, strlen (xml_end)); return 0; } /* GPGME SERVER. */ #include struct server { gpgme_tool_t gt; assuan_context_t assuan_ctx; gpgme_data_encoding_t input_enc; gpgme_data_encoding_t output_enc; assuan_fd_t input_fd; char *input_filename; FILE *input_stream; assuan_fd_t output_fd; char *output_filename; FILE *output_stream; assuan_fd_t message_fd; char *message_filename; FILE *message_stream; gpgme_data_encoding_t message_enc; }; gpg_error_t server_write_status (void *hook, const char *status, const char *msg) { struct server *server = hook; return assuan_write_status (server->assuan_ctx, status, msg); } gpg_error_t server_write_data (void *hook, const void *buf, size_t len) { struct server *server = hook; return assuan_send_data (server->assuan_ctx, buf, len); } static gpg_error_t server_passphrase_cb (void *opaque, const char *uid_hint, const char *info, int was_bad, int fd) { struct server *server = opaque; gpg_error_t err; unsigned char *buf = NULL; size_t buflen = 0; (void)was_bad; if (server && server->assuan_ctx) { if (uid_hint) assuan_write_status (server->assuan_ctx, "USERID_HINT", uid_hint); if (info) assuan_write_status (server->assuan_ctx, "NEED_PASSPHRASE", info); err = assuan_inquire (server->assuan_ctx, "PASSPHRASE", &buf, &buflen, 100); } else err = gpg_error (GPG_ERR_NO_PASSPHRASE); if (!err) { /* We take care to always send a LF. */ if (gpgme_io_writen (fd, buf, buflen)) err = gpg_error_from_syserror (); else if (!memchr (buf, '\n', buflen) && gpgme_io_writen (fd, "\n", 1)) err = gpg_error_from_syserror (); } free (buf); return err; } /* Wrapper around assuan_command_parse_fd to also handle a "file=FILENAME" argument. On success either a filename is returned at FILENAME or a file descriptor at RFD; the other one is set to NULL respective ASSUAN_INVALID_FD. */ static gpg_error_t server_parse_fd (assuan_context_t ctx, char *line, assuan_fd_t *rfd, char **filename) { *rfd = ASSUAN_INVALID_FD; *filename = NULL; if (! strncasecmp (line, "file=", 5)) { char *term; *filename = strdup (line + 5); if (!*filename) return gpg_error_from_syserror(); term = strchr (*filename, ' '); if (term) *term = '\0'; return 0; } else return assuan_command_parse_fd (ctx, line, rfd); } static gpgme_data_encoding_t server_data_encoding (const char *line) { if (strstr (line, "--binary")) return GPGME_DATA_ENCODING_BINARY; if (strstr (line, "--base64")) return GPGME_DATA_ENCODING_BASE64; if (strstr (line, "--armor")) return GPGME_DATA_ENCODING_ARMOR; if (strstr (line, "--url")) return GPGME_DATA_ENCODING_URL; if (strstr (line, "--urlesc")) return GPGME_DATA_ENCODING_URLESC; if (strstr (line, "--url0")) return GPGME_DATA_ENCODING_URL0; if (strstr (line, "--mime")) return GPGME_DATA_ENCODING_MIME; return GPGME_DATA_ENCODING_NONE; } static gpgme_error_t server_data_obj (assuan_fd_t fd, char *fn, int out, gpgme_data_encoding_t encoding, gpgme_data_t *data, FILE **fs) { gpgme_error_t err; *fs = NULL; if (fn) { *fs = fopen (fn, out ? "wb" : "rb"); if (!*fs) return gpg_error_from_syserror (); err = gpgme_data_new_from_stream (data, *fs); } else err = gpgme_data_new_from_fd (data, (int) fd); if (err) return err; return gpgme_data_set_encoding (*data, encoding); } void server_reset_fds (struct server *server) { /* assuan closes the input and output FDs for us when doing a RESET, but we use this same function after commands, so repeat it here. */ if (server->input_fd != ASSUAN_INVALID_FD) { #if HAVE_W32_SYSTEM CloseHandle (server->input_fd); #else close (server->input_fd); #endif server->input_fd = ASSUAN_INVALID_FD; } if (server->output_fd != ASSUAN_INVALID_FD) { #if HAVE_W32_SYSTEM CloseHandle (server->output_fd); #else close (server->output_fd); #endif server->output_fd = ASSUAN_INVALID_FD; } if (server->message_fd != ASSUAN_INVALID_FD) { /* FIXME: Assuan should provide a close function. */ #if HAVE_W32_SYSTEM CloseHandle (server->message_fd); #else close (server->message_fd); #endif server->message_fd = ASSUAN_INVALID_FD; } if (server->input_filename) { free (server->input_filename); server->input_filename = NULL; } if (server->output_filename) { free (server->output_filename); server->output_filename = NULL; } if (server->message_filename) { free (server->message_filename); server->message_filename = NULL; } if (server->input_stream) { fclose (server->input_stream); server->input_stream = NULL; } if (server->output_stream) { fclose (server->output_stream); server->output_stream = NULL; } if (server->message_stream) { fclose (server->message_stream); server->message_stream = NULL; } server->input_enc = GPGME_DATA_ENCODING_NONE; server->output_enc = GPGME_DATA_ENCODING_NONE; server->message_enc = GPGME_DATA_ENCODING_NONE; } static gpg_error_t reset_notify (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); (void)line; server_reset_fds (server); gt_reset (server->gt); return 0; } static const char hlp_version[] = "VERSION []\n" "\n" "Call the function gpgme_check_version."; static gpg_error_t cmd_version (assuan_context_t ctx, char *line) { if (line && *line) { const char *version = gpgme_check_version (line); return version ? 0 : gpg_error (GPG_ERR_SELFTEST_FAILED); } else { const char *version = gpgme_check_version (NULL); return assuan_send_data (ctx, version, strlen (version)); } } static const char hlp_engine[] = "ENGINE []\n" "\n" "Get information about a GPGME engine (a.k.a. protocol)."; static gpg_error_t cmd_engine (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); return gt_get_engine_info (server->gt, gt_protocol_from_name (line)); } static const char hlp_protocol[] = "PROTOCOL []\n" "\n" "With NAME, set the protocol. Without, return the current\n" "protocol."; static gpg_error_t cmd_protocol (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) return gt_set_protocol (server->gt, gt_protocol_from_name (line)); else return gt_get_protocol (server->gt); } static const char hlp_sub_protocol[] = "SUB_PROTOCOL []\n" "\n" "With NAME, set the sub-protocol. Without, return the\n" "current sub-protocol."; static gpg_error_t cmd_sub_protocol (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) return gt_set_sub_protocol (server->gt, gt_protocol_from_name (line)); else return gt_get_sub_protocol (server->gt); } static const char hlp_pinentry_mode[] = "PINENTRY_MODE \n" "\n" "Set the pinentry mode to NAME. Allowedvalues for NAME are:\n" " default - reset to the default of the engine,\n" " ask - force the use of the pinentry,\n" " cancel - emulate use of pinentry's cancel button,\n" " error - return a pinentry error,\n" " loopback - redirect pinentry queries to the caller.\n" "Note that only recent versions of GPG support changing the pinentry mode."; static gpg_error_t cmd_pinentry_mode (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpgme_pinentry_mode_t mode; if (!line || !*line || !strcmp (line, "default")) mode = GPGME_PINENTRY_MODE_DEFAULT; else if (!strcmp (line, "ask")) mode = GPGME_PINENTRY_MODE_ASK; else if (!strcmp (line, "cancel")) mode = GPGME_PINENTRY_MODE_CANCEL; else if (!strcmp (line, "error")) mode = GPGME_PINENTRY_MODE_ERROR; else if (!strcmp (line, "loopback")) mode = GPGME_PINENTRY_MODE_LOOPBACK; else return gpg_error (GPG_ERR_INV_VALUE); return gt_set_pinentry_mode (server->gt, mode, server); } static const char hlp_armor[] = "ARMOR [true|false]\n" "\n" "With 'true' or 'false', turn output ASCII armoring on or\n" "off. Without, return the current armoring status."; static gpg_error_t cmd_armor (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) { int flag = 0; if (! strcasecmp (line, "true") || ! strcasecmp (line, "yes") || line[0] == '1') flag = 1; return gt_set_armor (server->gt, flag); } else return gt_get_armor (server->gt); } static const char hlp_textmode[] = "TEXTMODE [true|false]\n" "\n" "With 'true' or 'false', turn text mode on or off.\n" "Without, return the current text mode status."; static gpg_error_t cmd_textmode (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) { int flag = 0; if (! strcasecmp (line, "true") || ! strcasecmp (line, "yes") || line[0] == '1') flag = 1; return gt_set_textmode (server->gt, flag); } else return gt_get_textmode (server->gt); } static const char hlp_include_certs[] = "INCLUDE_CERTS [default|]\n" "\n" "With DEFAULT or N, set how many certificates should be\n" "included in the next S/MIME signed message. See the\n" "GPGME documentation for details on the meaning of" "various N. Without either, return the current setting."; static gpg_error_t cmd_include_certs (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) { int include_certs = 0; if (! strcasecmp (line, "default")) include_certs = GPGME_INCLUDE_CERTS_DEFAULT; else include_certs = atoi (line); return gt_set_include_certs (server->gt, include_certs); } else return gt_get_include_certs (server->gt); } static const char hlp_keylist_mode[] = "KEYLIST_MODE [local] [extern] [sigs] [sig_notations]\n" " [ephemeral] [validate]\n" "\n" "Set the mode for the next KEYLIST command."; static gpg_error_t cmd_keylist_mode (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) { gpgme_keylist_mode_t mode = 0; if (strstr (line, "local")) mode |= GPGME_KEYLIST_MODE_LOCAL; if (strstr (line, "extern")) mode |= GPGME_KEYLIST_MODE_EXTERN; if (strstr (line, "sigs")) mode |= GPGME_KEYLIST_MODE_SIGS; if (strstr (line, "sig_notations")) mode |= GPGME_KEYLIST_MODE_SIG_NOTATIONS; if (strstr (line, "with_secret")) mode |= GPGME_KEYLIST_MODE_WITH_SECRET; if (strstr (line, "ephemeral")) mode |= GPGME_KEYLIST_MODE_EPHEMERAL; if (strstr (line, "validate")) mode |= GPGME_KEYLIST_MODE_VALIDATE; return gt_set_keylist_mode (server->gt, mode); } else return gt_get_keylist_mode (server->gt); } static const char hlp_input[] = "INPUT [|FILE=]\n" "\n" "Set the input for the next command. Use either the\n" "Assuan file descriptor FD or a filesystem PATH."; static gpg_error_t cmd_input (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t sysfd; char *filename; err = server_parse_fd (ctx, line, &sysfd, &filename); if (err) return err; server->input_fd = sysfd; server->input_filename = filename; server->input_enc = server_data_encoding (line); return 0; } static const char hlp_output[] = "OUTPUT [|FILE=]\n" "\n" "Set the output for the next command. Use either the\n" "Assuan file descriptor FD or a filesystem PATH."; static gpg_error_t cmd_output (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t sysfd; char *filename; err = server_parse_fd (ctx, line, &sysfd, &filename); if (err) return err; server->output_fd = sysfd; server->output_filename = filename; server->output_enc = server_data_encoding (line); return 0; } static const char hlp_message[] = "MESSAGE [|FILE=]\n" "\n" "Set the plaintext message for the next VERIFY command\n" "with a detached signature. Use either the Assuan file\n" "descriptor FD or a filesystem PATH."; static gpg_error_t cmd_message (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t sysfd; char *filename; err = server_parse_fd (ctx, line, &sysfd, &filename); if (err) return err; server->message_fd = sysfd; server->message_filename = filename; server->message_enc = server_data_encoding (line); return 0; } static const char hlp_recipient[] = "RECIPIENT \n" "\n" "Add the key matching PATTERN to the list of recipients\n" "for the next encryption command."; static gpg_error_t cmd_recipient (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); return gt_recipients_add (server->gt, line); } static const char hlp_signer[] = "SIGNER \n" "\n" "Add the key with FINGERPRINT to the list of signers to\n" "be used for the next signing command."; static gpg_error_t cmd_signer (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); return gt_signers_add (server->gt, line); } static const char hlp_signers_clear[] = "SIGNERS_CLEAR\n" "\n" "Clear the list of signers specified by previous SIGNER\n" "commands."; static gpg_error_t cmd_signers_clear (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); (void)line; return gt_signers_clear (server->gt); } static gpg_error_t _cmd_decrypt_verify (assuan_context_t ctx, char *line, int verify) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; assuan_fd_t out_fd; char *out_fn; gpgme_data_t inp_data; gpgme_data_t out_data; (void)line; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; out_fd = server->output_fd; out_fn = server->output_filename; if (out_fd == ASSUAN_INVALID_FD && !out_fn) return GPG_ERR_ASS_NO_OUTPUT; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); return err; } err = gt_decrypt_verify (server->gt, inp_data, out_data, verify); gpgme_data_release (inp_data); gpgme_data_release (out_data); server_reset_fds (server); return err; } static const char hlp_decrypt[] = "DECRYPT\n" "\n" "Decrypt the object set by the last INPUT command and\n" "write the decrypted message to the object set by the\n" "last OUTPUT command."; static gpg_error_t cmd_decrypt (assuan_context_t ctx, char *line) { return _cmd_decrypt_verify (ctx, line, 0); } static const char hlp_decrypt_verify[] = "DECRYPT_VERIFY\n" "\n" "Decrypt the object set by the last INPUT command and\n" "verify any embedded signatures. Write the decrypted\n" "message to the object set by the last OUTPUT command."; static gpg_error_t cmd_decrypt_verify (assuan_context_t ctx, char *line) { return _cmd_decrypt_verify (ctx, line, 1); } static gpg_error_t _cmd_sign_encrypt (assuan_context_t ctx, char *line, int sign) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; assuan_fd_t out_fd; char *out_fn; gpgme_data_t inp_data = NULL; gpgme_data_t out_data = NULL; gpgme_encrypt_flags_t flags = 0; if (strstr (line, "--always-trust")) flags |= GPGME_ENCRYPT_ALWAYS_TRUST; if (strstr (line, "--no-encrypt-to")) flags |= GPGME_ENCRYPT_NO_ENCRYPT_TO; if (strstr (line, "--prepare")) flags |= GPGME_ENCRYPT_PREPARE; if (strstr (line, "--expect-sign")) flags |= GPGME_ENCRYPT_EXPECT_SIGN; if (strstr (line, "--no-compress")) flags |= GPGME_ENCRYPT_NO_COMPRESS; inp_fd = server->input_fd; inp_fn = server->input_filename; out_fd = server->output_fd; out_fn = server->output_filename; if (inp_fd != ASSUAN_INVALID_FD || inp_fn) { err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; } if (out_fd != ASSUAN_INVALID_FD || out_fn) { err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); return err; } } err = gt_sign_encrypt (server->gt, flags, inp_data, out_data, sign); gpgme_data_release (inp_data); gpgme_data_release (out_data); server_reset_fds (server); return err; } static const char hlp_encrypt[] = "ENCRYPT [--always-trust] [--no-encrypt-to]\n" " [--no-compress] [--prepare] [--expect-sign]\n" "\n" "Encrypt the object set by the last INPUT command to\n" "the keys specified by previous RECIPIENT commands. \n" "Write the signed and encrypted message to the object\n" "set by the last OUTPUT command."; static gpg_error_t cmd_encrypt (assuan_context_t ctx, char *line) { return _cmd_sign_encrypt (ctx, line, 0); } static const char hlp_sign_encrypt[] = "SIGN_ENCRYPT [--always-trust] [--no-encrypt-to]\n" " [--no-compress] [--prepare] [--expect-sign]\n" "\n" "Sign the object set by the last INPUT command with the\n" "keys specified by previous SIGNER commands and encrypt\n" "it to the keys specified by previous RECIPIENT\n" "commands. Write the signed and encrypted message to\n" "the object set by the last OUTPUT command."; static gpg_error_t cmd_sign_encrypt (assuan_context_t ctx, char *line) { return _cmd_sign_encrypt (ctx, line, 1); } static const char hlp_sign[] = "SIGN [--clear|--detach]\n" "\n" "Sign the object set by the last INPUT command with the\n" "keys specified by previous SIGNER commands. Write the\n" "signed message to the object set by the last OUTPUT\n" "command. With `--clear`, generate a clear text\n" "signature. With `--detach`, generate a detached\n" "signature."; static gpg_error_t cmd_sign (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; assuan_fd_t out_fd; char *out_fn; gpgme_data_t inp_data; gpgme_data_t out_data; gpgme_sig_mode_t mode = GPGME_SIG_MODE_NORMAL; if (strstr (line, "--clear")) mode = GPGME_SIG_MODE_CLEAR; if (strstr (line, "--detach")) mode = GPGME_SIG_MODE_DETACH; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; out_fd = server->output_fd; out_fn = server->output_filename; if (out_fd == ASSUAN_INVALID_FD && !out_fn) return GPG_ERR_ASS_NO_OUTPUT; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); return err; } err = gt_sign (server->gt, inp_data, out_data, mode); gpgme_data_release (inp_data); gpgme_data_release (out_data); server_reset_fds (server); return err; } static const char hlp_verify[] = "VERIFY\n" "\n" "Verify signatures on the object set by the last INPUT\n" "and MESSAGE commands. If the message was encrypted,\n" "write the plaintext to the object set by the last\n" "OUTPUT command."; static gpg_error_t cmd_verify (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; assuan_fd_t msg_fd; assuan_fd_t out_fd; char *inp_fn; char *msg_fn; char *out_fn; gpgme_data_t inp_data; gpgme_data_t msg_data = NULL; gpgme_data_t out_data = NULL; (void)line; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; msg_fd = server->message_fd; msg_fn = server->message_filename; out_fd = server->output_fd; out_fn = server->output_filename; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; if (msg_fd != ASSUAN_INVALID_FD || msg_fn) { err = server_data_obj (msg_fd, msg_fn, 0, server->message_enc, &msg_data, &server->message_stream); if (err) { gpgme_data_release (inp_data); return err; } } if (out_fd != ASSUAN_INVALID_FD || out_fn) { err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); gpgme_data_release (msg_data); return err; } } err = gt_verify (server->gt, inp_data, msg_data, out_data); gpgme_data_release (inp_data); if (msg_data) gpgme_data_release (msg_data); if (out_data) gpgme_data_release (out_data); server_reset_fds (server); return err; } static const char hlp_import[] = "IMPORT []\n" "\n" "With PATTERN, import the keys described by PATTERN.\n" "Without, read a key (or keys) from the object set by the\n" "last INPUT command."; static gpg_error_t cmd_import (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); if (line && *line) { char *fprs[2] = { line, NULL }; return gt_import_keys (server->gt, fprs); } else { gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; gpgme_data_t inp_data; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; err = gt_import (server->gt, inp_data); gpgme_data_release (inp_data); server_reset_fds (server); return err; } } static const char hlp_export[] = "EXPORT [--extern] [--minimal] [--secret [--pkcs12] [--raw]] []\n" "\n" "Export the keys described by PATTERN. Write the\n" "the output to the object set by the last OUTPUT command."; static gpg_error_t cmd_export (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t out_fd; char *out_fn; gpgme_data_t out_data; gpgme_export_mode_t mode = 0; const char *pattern[2]; out_fd = server->output_fd; out_fn = server->output_filename; if (out_fd == ASSUAN_INVALID_FD && !out_fn) return GPG_ERR_ASS_NO_OUTPUT; err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) return err; if (has_option (line, "--extern")) mode |= GPGME_EXPORT_MODE_EXTERN; if (has_option (line, "--minimal")) mode |= GPGME_EXPORT_MODE_MINIMAL; if (has_option (line, "--secret")) mode |= GPGME_EXPORT_MODE_SECRET; if (has_option (line, "--raw")) mode |= GPGME_EXPORT_MODE_RAW; if (has_option (line, "--pkcs12")) mode |= GPGME_EXPORT_MODE_PKCS12; line = skip_options (line); pattern[0] = line; pattern[1] = NULL; err = gt_export (server->gt, pattern, mode, out_data); gpgme_data_release (out_data); server_reset_fds (server); return err; } static gpg_error_t _cmd_genkey_write (gpgme_data_t data, const void *buf, size_t size) { while (size > 0) { gpgme_ssize_t writen = gpgme_data_write (data, buf, size); if (writen < 0 && errno != EAGAIN) return gpg_error_from_syserror (); else if (writen > 0) { buf = (void *) (((char *) buf) + writen); size -= writen; } } return 0; } static gpg_error_t cmd_genkey (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; assuan_fd_t out_fd; char *out_fn; gpgme_data_t inp_data; gpgme_data_t out_data = NULL; gpgme_data_t parms_data = NULL; const char *parms; (void)line; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; out_fd = server->output_fd; out_fn = server->output_filename; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; if (out_fd != ASSUAN_INVALID_FD || out_fn) { err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); return err; } } /* Convert input data. */ err = gpgme_data_new (&parms_data); if (err) goto out; do { char buf[512]; gpgme_ssize_t readn = gpgme_data_read (inp_data, buf, sizeof (buf)); if (readn < 0) { err = gpg_error_from_syserror (); goto out; } else if (readn == 0) break; err = _cmd_genkey_write (parms_data, buf, readn); if (err) goto out; } while (1); err = _cmd_genkey_write (parms_data, "", 1); if (err) goto out; parms = gpgme_data_release_and_get_mem (parms_data, NULL); parms_data = NULL; if (! parms) { err = gpg_error (GPG_ERR_GENERAL); goto out; } err = gt_genkey (server->gt, parms, out_data, NULL); server_reset_fds (server); out: gpgme_data_release (inp_data); if (out_data) gpgme_data_release (out_data); if (parms_data) gpgme_data_release (parms_data); return err; } static gpg_error_t cmd_delete (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); int allow_secret = 0; const char optstr[] = "--allow-secret"; if (!strncasecmp (line, optstr, strlen (optstr))) { allow_secret = 1; line += strlen (optstr); while (*line && !spacep (line)) line++; } return gt_delete (server->gt, line, allow_secret); } static const char hlp_keylist[] = "KEYLIST [--secret-only] []\n" "\n" "List all certificates or only those specified by PATTERNS. Each\n" "pattern shall be a percent-plus escaped certificate specification."; static gpg_error_t cmd_keylist (assuan_context_t ctx, char *line) { #define MAX_CMD_KEYLIST_PATTERN 20 struct server *server = assuan_get_pointer (ctx); gpgme_tool_t gt = server->gt; struct result_xml_state state; gpg_error_t err; int secret_only = 0; int idx, indent=2; const char *pattern[MAX_CMD_KEYLIST_PATTERN+1]; const char optstr[] = "--secret-only"; char *p; if (!strncasecmp (line, optstr, strlen (optstr))) { secret_only = 1; line += strlen (optstr); while (*line && !spacep (line)) line++; } idx = 0; for (p=line; *p; line = p) { while (*p && *p != ' ') p++; if (*p) *p++ = 0; if (*line) { if (idx+1 == DIM (pattern)) return gpg_error (GPG_ERR_TOO_MANY); strcpy_escaped_plus (line, line); pattern[idx++] = line; } } pattern[idx] = NULL; gt_write_data (gt, xml_preamble1, strlen (xml_preamble1)); gt_write_data (gt, NULL, 0); gt_write_data (gt, xml_preamble2, strlen (xml_preamble2)); gt_write_data (gt, NULL, 0); result_init (&state, indent, (result_xml_write_cb_t) gt_write_data, gt); result_xml_tag_start (&state, "keylist", NULL); err = gt_keylist_start (server->gt, pattern, secret_only); while (! err) { gpgme_key_t key; gpgme_subkey_t subkey; gpgme_user_id_t uid; err = gt_keylist_next (server->gt, &key); if (gpg_err_code (err) == GPG_ERR_EOF) { err = 0; break; } else if (! err) { result_xml_tag_start (&state, "key", NULL); result_add_value (&state, "revoked", key->revoked); result_add_value (&state, "expired", key->expired); result_add_value (&state, "disabled", key->disabled); result_add_value (&state, "invalid", key->invalid); result_add_value (&state, "can-encrypt", key->can_encrypt); result_add_value (&state, "can-sign", key->can_sign); result_add_value (&state, "can-certify", key->can_certify); result_add_value (&state, "can-authenticate", key->can_authenticate); result_add_value (&state, "is-qualified", key->is_qualified); result_add_value (&state, "secret", key->secret); result_add_protocol (&state, "protocol", key->protocol); result_xml_tag_start (&state, "issuer", NULL); result_add_string (&state, "serial", key->issuer_serial); result_add_string (&state, "name", key->issuer_name); result_xml_tag_end (&state); /* issuer */ result_add_string (&state, "chain-id", key->chain_id); result_add_validity (&state, "owner-trust", key->owner_trust); result_xml_tag_start (&state, "subkeys", NULL); subkey = key->subkeys; while (subkey) { result_xml_tag_start (&state, "subkey", NULL); /* FIXME: more data */ result_add_keyid (&state, "keyid", subkey->keyid); if (subkey->fpr) result_add_fpr (&state, "fpr", subkey->fpr); result_add_value (&state, "secret", subkey->secret); result_add_value (&state, "is_cardkey", subkey->is_cardkey); if (subkey->card_number) result_add_string (&state, "card_number", subkey->card_number); if (subkey->curve) result_add_string (&state, "curve", subkey->curve); result_xml_tag_end (&state); /* subkey */ subkey = subkey->next; } result_xml_tag_end (&state); /* subkeys */ result_xml_tag_start (&state, "uids", NULL); uid = key->uids; while (uid) { result_xml_tag_start (&state, "uid", NULL); /* FIXME: more data */ result_add_string (&state, "uid", uid->uid); result_add_string (&state, "name", uid->name); result_add_string (&state, "email", uid->email); result_add_string (&state, "comment", uid->comment); result_xml_tag_end (&state); /* uid */ uid = uid->next; } result_xml_tag_end (&state); /* uids */ result_xml_tag_end (&state); /* key */ gpgme_key_unref (key); } } result_xml_tag_end (&state); /* keylist */ gt_write_data (gt, xml_end, strlen (xml_end)); server_reset_fds (server); return err; } static const char hlp_getauditlog[] = "GETAUDITLOG [--html] [--with-help]\n" "\n" "Call the function gpgme_op_getauditlog with the given flags. Write\n" "the output to the object set by the last OUTPUT command."; static gpg_error_t cmd_getauditlog (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t out_fd; char *out_fn; gpgme_data_t out_data; unsigned int flags = 0; out_fd = server->output_fd; out_fn = server->output_filename; if (out_fd == ASSUAN_INVALID_FD && !out_fn) return GPG_ERR_ASS_NO_OUTPUT; err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) return err; if (strstr (line, "--html")) flags |= GPGME_AUDITLOG_HTML; if (strstr (line, "--with-help")) flags |= GPGME_AUDITLOG_WITH_HELP; err = gt_getauditlog (server->gt, out_data, flags); gpgme_data_release (out_data); server_reset_fds (server); return err; } static gpg_error_t cmd_vfs_mount (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); char *mount_dir; gpg_error_t err; mount_dir = strchr (line, ' '); if (mount_dir) { *(mount_dir++) = '\0'; while (*mount_dir == ' ') mount_dir++; } err = gt_vfs_mount (server->gt, line, mount_dir, 0); return err; } static gpg_error_t cmd_vfs_create (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; char *end; end = strchr (line, ' '); if (end) { *(end++) = '\0'; while (*end == ' ') end++; } err = gt_vfs_create (server->gt, line, 0); return err; } static const char hlp_passwd[] = "PASSWD \n" "\n" "Ask the backend to change the passphrase for the key\n" "specified by USER-ID."; static gpg_error_t cmd_passwd (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); return gt_passwd (server->gt, line); } static gpg_error_t cmd_result (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); (void)line; return gt_result (server->gt, GT_RESULT_ALL); } /* STRERROR */ static gpg_error_t cmd_strerror (assuan_context_t ctx, char *line) { gpg_error_t err; char buf[100]; err = atoi (line); snprintf (buf, sizeof (buf), "%s <%s>", gpgme_strerror (err), gpgme_strsource (err)); return assuan_send_data (ctx, buf, strlen (buf)); } static gpg_error_t cmd_pubkey_algo_name (assuan_context_t ctx, char *line) { gpgme_pubkey_algo_t algo; char buf[100]; algo = atoi (line); snprintf (buf, sizeof (buf), "%s", gpgme_pubkey_algo_name (algo)); return assuan_send_data (ctx, buf, strlen (buf)); } static gpg_error_t cmd_hash_algo_name (assuan_context_t ctx, char *line) { gpgme_hash_algo_t algo; char buf[100]; algo = atoi (line); snprintf (buf, sizeof (buf), "%s", gpgme_hash_algo_name (algo)); return assuan_send_data (ctx, buf, strlen (buf)); } static const char hlp_identify[] = - "IDENTIY\n" + "IDENTIFY\n" "\n" "Identify the type of data set with the INPUT command."; static gpg_error_t cmd_identify (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; gpgme_data_t inp_data; (void)line; inp_fd = server->input_fd; inp_fn = server->input_filename; if (inp_fd == ASSUAN_INVALID_FD && !inp_fn) return GPG_ERR_ASS_NO_INPUT; err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; err = gt_identify (server->gt, inp_data); gpgme_data_release (inp_data); server_reset_fds (server); return err; } static const char hlp_spawn[] = "SPAWN PGM [args]\n" "\n" "Run program PGM with stdin connected to the INPUT source;\n" "stdout and stderr to the OUTPUT source."; static gpg_error_t cmd_spawn (assuan_context_t ctx, char *line) { struct server *server = assuan_get_pointer (ctx); gpg_error_t err; assuan_fd_t inp_fd; char *inp_fn; assuan_fd_t out_fd; char *out_fn; gpgme_data_t inp_data = NULL; gpgme_data_t out_data = NULL; inp_fd = server->input_fd; inp_fn = server->input_filename; out_fd = server->output_fd; out_fn = server->output_filename; if (inp_fd != ASSUAN_INVALID_FD || inp_fn) { err = server_data_obj (inp_fd, inp_fn, 0, server->input_enc, &inp_data, &server->input_stream); if (err) return err; } if (out_fd != ASSUAN_INVALID_FD || out_fn) { err = server_data_obj (out_fd, out_fn, 1, server->output_enc, &out_data, &server->output_stream); if (err) { gpgme_data_release (inp_data); return err; } } err = gt_spawn (server->gt, line, inp_data, out_data); gpgme_data_release (inp_data); gpgme_data_release (out_data); server_reset_fds (server); return err; } /* Tell the assuan library about our commands. */ static gpg_error_t register_commands (assuan_context_t ctx) { gpg_error_t err; static struct { const char *name; assuan_handler_t handler; const char * const help; } table[] = { /* RESET, BYE are implicit. */ { "VERSION", cmd_version, hlp_version }, /* TODO: Set engine info. */ { "ENGINE", cmd_engine, hlp_engine }, { "PROTOCOL", cmd_protocol, hlp_protocol }, { "SUB_PROTOCOL", cmd_sub_protocol, hlp_sub_protocol }, { "PINENTRY_MODE", cmd_pinentry_mode, hlp_pinentry_mode }, { "ARMOR", cmd_armor, hlp_armor }, { "TEXTMODE", cmd_textmode, hlp_textmode }, { "INCLUDE_CERTS", cmd_include_certs, hlp_include_certs }, { "KEYLIST_MODE", cmd_keylist_mode, hlp_keylist_mode }, { "INPUT", cmd_input, hlp_input }, { "OUTPUT", cmd_output, hlp_output }, { "MESSAGE", cmd_message, hlp_message }, { "RECIPIENT", cmd_recipient, hlp_recipient }, { "SIGNER", cmd_signer, hlp_signer }, { "SIGNERS_CLEAR", cmd_signers_clear, hlp_signers_clear }, /* TODO: SIGNOTATION missing. */ /* TODO: Could add wait interface if we allow more than one context */ /* and add _START variants. */ /* TODO: Could add data interfaces if we allow multiple data objects. */ { "DECRYPT", cmd_decrypt, hlp_decrypt }, { "DECRYPT_VERIFY", cmd_decrypt_verify, hlp_decrypt_verify }, { "ENCRYPT", cmd_encrypt, hlp_encrypt }, { "ENCRYPT_SIGN", cmd_sign_encrypt, hlp_sign_encrypt }, { "SIGN_ENCRYPT", cmd_sign_encrypt, hlp_sign_encrypt }, { "SIGN", cmd_sign, hlp_sign }, { "VERIFY", cmd_verify, hlp_verify }, { "IMPORT", cmd_import, hlp_import }, { "EXPORT", cmd_export, hlp_export }, { "GENKEY", cmd_genkey }, { "DELETE", cmd_delete }, /* TODO: EDIT, CARD_EDIT (with INQUIRE) */ { "KEYLIST", cmd_keylist, hlp_keylist }, { "LISTKEYS", cmd_keylist, hlp_keylist }, /* TODO: TRUSTLIST, TRUSTLIST_EXT */ { "GETAUDITLOG", cmd_getauditlog, hlp_getauditlog }, /* TODO: ASSUAN */ { "VFS_MOUNT", cmd_vfs_mount }, { "MOUNT", cmd_vfs_mount }, { "VFS_CREATE", cmd_vfs_create }, { "CREATE", cmd_vfs_create }, /* TODO: GPGCONF */ { "RESULT", cmd_result }, { "STRERROR", cmd_strerror }, { "PUBKEY_ALGO_NAME", cmd_pubkey_algo_name }, { "HASH_ALGO_NAME", cmd_hash_algo_name }, { "PASSWD", cmd_passwd, hlp_passwd }, { "IDENTIFY", cmd_identify, hlp_identify }, { "SPAWN", cmd_spawn, hlp_spawn }, { NULL } }; int idx; for (idx = 0; table[idx].name; idx++) { err = assuan_register_command (ctx, table[idx].name, table[idx].handler, table[idx].help); if (err) return err; } return 0; } void gpgme_server (gpgme_tool_t gt) { gpg_error_t err; assuan_fd_t filedes[2]; struct server server; static const char hello[] = ("GPGME-Tool " VERSION " ready"); memset (&server, 0, sizeof (server)); server.input_fd = ASSUAN_INVALID_FD; server.output_fd = ASSUAN_INVALID_FD; server.message_fd = ASSUAN_INVALID_FD; server.input_enc = GPGME_DATA_ENCODING_NONE; server.output_enc = GPGME_DATA_ENCODING_NONE; server.message_enc = GPGME_DATA_ENCODING_NONE; server.gt = gt; gt->write_status = server_write_status; gt->write_status_hook = &server; gt->write_data = server_write_data; gt->write_data_hook = &server; /* We use a pipe based server so that we can work from scripts. assuan_init_pipe_server will automagically detect when we are called with a socketpair and ignore FIELDES in this case. */ #ifdef HAVE_W32CE_SYSTEM filedes[0] = ASSUAN_STDIN; filedes[1] = ASSUAN_STDOUT; #else filedes[0] = assuan_fdopen (0); filedes[1] = assuan_fdopen (1); #endif err = assuan_new (&server.assuan_ctx); if (err) log_error (1, err, "can't create assuan context"); assuan_set_pointer (server.assuan_ctx, &server); err = assuan_init_pipe_server (server.assuan_ctx, filedes); if (err) log_error (1, err, "can't initialize assuan server"); err = register_commands (server.assuan_ctx); if (err) log_error (1, err, "can't register assuan commands"); assuan_set_hello_line (server.assuan_ctx, hello); assuan_register_reset_notify (server.assuan_ctx, reset_notify); #define DBG_ASSUAN 0 if (DBG_ASSUAN) assuan_set_log_stream (server.assuan_ctx, log_stream); for (;;) { err = assuan_accept (server.assuan_ctx); if (err == -1) break; else if (err) { log_error (0, err, "assuan accept problem"); break; } err = assuan_process (server.assuan_ctx); if (err) log_error (0, err, "assuan processing failed"); } assuan_release (server.assuan_ctx); } static const char * my_strusage( int level ) { const char *p; switch (level) { case 11: p = "gpgme-tool"; break; case 13: p = PACKAGE_VERSION; break; case 14: p = "Copyright (C) 2015 g10 Code GmbH"; break; case 19: p = "Please report bugs to <" PACKAGE_BUGREPORT ">.\n"; break; case 1: case 40: p = "Usage: gpgme-tool [OPTIONS] [COMMANDS]"; break; case 41: p = "GPGME Tool -- Assuan server exposing GPGME operations\n"; break; case 42: p = "1"; /* Flag print 40 as part of 41. */ break; default: p = NULL; break; } return p; } int main (int argc, char *argv[]) { static ARGPARSE_OPTS opts[] = { ARGPARSE_c ('s', "server", "Server mode"), ARGPARSE_s_s(501, "gpg-binary", "|FILE|Use FILE for the GPG backend"), ARGPARSE_c (502, "lib-version", "Show library version"), ARGPARSE_end() }; ARGPARSE_ARGS pargs = { &argc, &argv, 0 }; enum { CMD_DEFAULT, CMD_SERVER, CMD_LIBVERSION } cmd = CMD_DEFAULT; const char *gpg_binary = NULL; struct gpgme_tool gt; gpg_error_t err; int needgt = 1; set_strusage (my_strusage); #ifdef HAVE_SETLOCALE setlocale (LC_ALL, ""); #endif gpgme_check_version (NULL); #ifdef LC_CTYPE gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL)); #endif #ifdef LC_MESSAGES gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL)); #endif log_init (); while (arg_parse (&pargs, opts)) { switch (pargs.r_opt) { case 's': cmd = CMD_SERVER; break; case 501: gpg_binary = pargs.r.ret_str; break; case 502: cmd = CMD_LIBVERSION; break; default: pargs.err = ARGPARSE_PRINT_WARNING; break; } } if (cmd == CMD_LIBVERSION) needgt = 0; if (needgt && gpg_binary) { if (access (gpg_binary, X_OK)) err = gpg_error_from_syserror (); else err = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, gpg_binary, NULL); if (err) log_error (1, err, "error witching OpenPGP engine to '%s'", gpg_binary); } if (needgt) gt_init (>); switch (cmd) { case CMD_DEFAULT: case CMD_SERVER: gpgme_server (>); break; case CMD_LIBVERSION: printf ("Version from header: %s (0x%06x)\n", GPGME_VERSION, GPGME_VERSION_NUMBER); printf ("Version from binary: %s\n", gpgme_check_version (NULL)); printf ("Copyright blurb ...:%s\n", gpgme_check_version ("\x01\x01")); break; } if (needgt) gpgme_release (gt.ctx); #ifdef HAVE_W32CE_SYSTEM /* Give the buggy ssh server time to flush the output buffers. */ Sleep (300); #endif return 0; }