Page Menu
Home
GnuPG
Search
Configure Global Search
Log In
Files
F34166210
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Size
127 KB
Subscribers
None
View Options
diff --git a/sm/ChangeLog b/sm/ChangeLog
index 34a73a298..35839a70c 100644
--- a/sm/ChangeLog
+++ b/sm/ChangeLog
@@ -1,641 +1,651 @@
+2002-07-22 Werner Koch <wk@gnupg.org>
+
+ * delete.c: New.
+ * gpgsm.c: Made --delete-key work.
+ * server.c (cmd_delkeys): New.
+ (register_commands): New command DELKEYS.
+
+ * decrypt.c (gpgsm_decrypt): Print a convenience note when RC2 is
+ used and a STATUS_ERROR with the algorithm oid.
+
2002-07-03 Werner Koch <wk@gnupg.org>
* server.c (gpgsm_status2): Insert a blank between all optional
arguments when using assuan.
* server.c (cmd_recipient): No more need for extra blank in constants.
* import.c (print_imported_status): Ditto.
* gpgsm.c (main): Ditto.
2002-07-02 Werner Koch <wk@gnupg.org>
* verify.c (gpgsm_verify): Extend the STATUS_BADSIG line with
the fingerprint.
* certpath.c (check_cert_policy): Don't use log_error to print a
warning.
* keydb.c (keydb_store_cert): Add optional ar EXISTED and changed
all callers.
* call-agent.c (learn_cb): Print info message only for real imports.
* import.c (gpgsm_import): Moved duplicated code to ...
(check_and_store): new function. Added magic to import the entire
chain. Print status only for real imports and moved printing code
to ..
(print_imported_status): New.
* call-dirmngr.c (gpgsm_dirmngr_isvalid): print status of dirmngr
call in very verbose mode.
* gpgsm.c (main): Use the same error codes for STATUS_INV_RECP as
with the server mode.
2002-06-29 Werner Koch <wk@gnupg.org>
* gpgsm.c: New option --auto-issuer-key-retrieve.
* certpath.c (find_up): Try to retrieve an issuer key from an
external source and from the ephemeral key DB.
(find_up_store_certs_cb): New.
* keydb.c (keydb_set_ephemeral): Does now return the old
state. Call the backend only when required.
* call-dirmngr.c (start_dirmngr): Use GNUPG_DEFAULT_DIRMNGR.
(lookup_status_cb): Issue status only when CTRL is not NULL.
(gpgsm_dirmngr_lookup): Document that CTRL is optional.
* call-agent.c (start_agent): Use GNUPG_DEFAULT_AGENT.
2002-06-28 Werner Koch <wk@gnupg.org>
* server.c (cmd_recipient): Add more reason codes.
2002-06-27 Werner Koch <wk@gnupg.org>
* certpath.c (gpgsm_basic_cert_check): Use
--debug-no-path-validation to also bypass this basic check.
* gpgsm.c (main): Use GNUPG_DEFAULT_HOMEDIR constant.
* call-agent.c (start_agent): Create and pass the list of FD to
keep in the child to assuan.
* call-dirmngr.c (start_dirmngr): Ditto.
2002-06-26 Werner Koch <wk@gnupg.org>
* import.c (gpgsm_import): Print an STATUS_IMPORTED.
* gpgsm.c: --debug-no-path-validation does not take an argument.
2002-06-25 Werner Koch <wk@gnupg.org>
* certdump.c (print_dn_part): Always print a leading slash,
removed NEED_DELIM arg and changed caller.
* export.c (gpgsm_export): Print LFs to FP and not stdout.
(print_short_info): Ditto. Make use of gpgsm_print_name.
* server.c (cmd_export): Use output-fd instead of data lines; this
was actually the specified way.
2002-06-24 Werner Koch <wk@gnupg.org>
* gpgsm.c: Removed duped help entry for --list-keys.
* gpgsm.c, gpgsm.h: New option --debug-no-path-validation.
* certpath.c (gpgsm_validate_path): Use it here instead of the
debug flag hack.
* certpath.c (check_cert_policy): Return No_Policy_Match if the
policy file could not be opened.
2002-06-20 Werner Koch <wk@gnupg.org>
* certlist.c (gpgsm_add_to_certlist): Fixed locating of a
certificate with the required key usage.
* gpgsm.c (main): Fixed a segv when using --outfile without an
argument.
* keylist.c (print_capabilities): Also check for non-repudiation
and data encipherment.
* certlist.c (cert_usage_p): Test for signing and encryption was
swapped. Add a case for certification usage, handle
non-repudiation and data encipherment.
(gpgsm_cert_use_cert_p): New.
(gpgsm_add_to_certlist): Added a CTRL argument and changed all
callers to pass it.
* certpath.c (gpgsm_validate_path): Use it here to print a status
message. Added a CTRL argument and changed all callers to pass it.
* decrypt.c (gpgsm_decrypt): Print a status message for wrong key
usage.
* verify.c (gpgsm_verify): Ditto.
* keydb.c (classify_user_id): Allow a colon delimited fingerprint.
2002-06-19 Werner Koch <wk@gnupg.org>
* call-agent.c (learn_cb): Use log_info instead of log_error on
successful import.
* keydb.c (keydb_set_ephemeral): New.
(keydb_store_cert): New are ephemeral, changed all callers.
* keylist.c (list_external_cb): Store cert as ephemeral.
* export.c (gpgsm_export): Kludge to export epehmeral certificates.
* gpgsm.c (main): New command --list-external-keys.
2002-06-17 Werner Koch <wk@gnupg.org>
* certreqgen.c (read_parameters): Improved error handling.
(gpgsm_genkey): Print error message.
2002-06-13 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): New option --log-file.
2002-06-12 Werner Koch <wk@gnupg.org>
* call-dirmngr.c (lookup_status_cb): New.
(gpgsm_dirmngr_lookup): Use the status CB. Add new arg CTRL and
changed caller to pass it.
* gpgsm.c (open_fwrite): New.
(main): Allow --output for --verify.
* sign.c (hash_and_copy_data): New.
(gpgsm_sign): Implemented normal (non-detached) signatures.
* gpgsm.c (main): Ditto.
* certpath.c (gpgsm_validate_path): Special error handling for
no policy match.
2002-06-10 Werner Koch <wk@gnupg.org>
* server.c (get_status_string): Add STATUS_ERROR.
* certpath.c (gpgsm_validate_path): Tweaked the error checking to
return error codes in a more sensitive way.
* verify.c (gpgsm_verify): Send status TRUST_NEVER also for a bad
CA certificate and when the certificate has been revoked. Issue
TRUST_FULLY even when the cert has expired. Append an error token
to these status lines. Issue the new generic error status when a
cert was not found and when leaving the function.
2002-06-04 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): New command --list-sigs
* keylist.c (list_cert_std): New. Use it whenever colon mode is
not used.
(list_cert_chain): New.
2002-05-31 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): Don't print the "go ahead" message for an
invalid command.
2002-05-23 Werner Koch <wk@gnupg.org>
* import.c (gpgsm_import): Add error messages.
2002-05-21 Werner Koch <wk@gnupg.org>
* keylist.c (list_internal_keys): Renamed from gpgsm_list_keys.
(list_external_keys): New.
(gpgsm_list_keys): Dispatcher for above.
* call-dirmngr.c (lookup_cb,pattern_from_strlist)
(gpgsm_dirmngr_lookup): New.
* server.c (option_handler): Handle new option --list-mode.
(do_listkeys): Handle options and actually use the mode argument.
(get_status_string): New code TRUNCATED.
* import.c (gpgsm_import): Try to identify the type of input and
handle certs-only messages.
2002-05-14 Werner Koch <wk@gnupg.org>
* gpgsm.c: New option --faked-system-time
* sign.c (gpgsm_sign): And use it here.
* certpath.c (gpgsm_validate_path): Ditto.
2002-05-03 Werner Koch <wk@gnupg.org>
* certpath.c (gpgsm_validate_path): Added EXPTIME arg and changed
all callers.
* verify.c (gpgsm_verify): Tweaked usage of log_debug and
log_error. Return EXPSIG status and add expiretime to VALIDSIG.
2002-04-26 Werner Koch <wk@gnupg.org>
* gpgsm.h (DBG_AGENT,DBG_AGENT_VALUE): Replaced by DBG_ASSUAN_*.
Changed all users.
* call-agent.c (start_agent): Be more silent without -v.
* call-dirmngr.c (start_dirmngr): Ditto.
2002-04-25 Werner Koch <wk@gnupg.org>
* call-agent.c (start_agent): Make copies of old locales and check
for setlocale.
2002-04-25 Marcus Brinkmann <marcus@g10code.de>
* call-agent.c (start_agent): Fix error handling logic so the
locale is always correctly reset.
2002-04-25 Marcus Brinkmann <marcus@g10code.de>
* server.c (option_handler): Accept display, ttyname, ttytype,
lc_ctype and lc_messages options.
* gpgsm.c (main): Allocate memory for these options.
* gpgsm.h (struct opt): Make corresponding members non-const.
2002-04-24 Marcus Brinkmann <marcus@g10code.de>
* gpgsm.h (struct opt): New members display, ttyname, ttytype,
lc_ctype, lc_messages.
* gpgsm.c (enum cmd_and_opt_values): New members oDisplay,
oTTYname, oTTYtype, oLCctype, oLCmessages.
(opts): New entries for these options.
(main): Handle these new options.
* call-agent.c (start_agent): Set the various display and tty
parameter after resetting.
2002-04-18 Werner Koch <wk@gnupg.org>
* certreqgen.c (gpgsm_genkey): Write status output on success.
2002-04-15 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): Check ksba version.
* certpath.c (find_up): New to use the authorithKeyIdentifier.
Use it in all other functions to locate the signing cert..
2002-04-11 Werner Koch <wk@gnupg.org>
* certlist.c (cert_usable_p): New.
(gpgsm_cert_use_sign_p,gpgsm_cert_use_encrypt_p): New.
(gpgsm_cert_use_verify_p,gpgsm_cert_use_decrypt_p): New.
(gpgsm_add_to_certlist): Check the key usage.
* sign.c (gpgsm_sign): Ditto.
* verify.c (gpgsm_verify): Print a message wehn an unsuitable
certificate was used.
* decrypt.c (gpgsm_decrypt): Ditto
* keylist.c (print_capabilities): Determine values from the cert.
2002-03-28 Werner Koch <wk@gnupg.org>
* keylist.c (list_cert_colon): Fixed listing of crt record; the
issuer is not at the right place. Print a chainingID.
* certpath.c (gpgsm_walk_cert_chain): Be a bit more silent on
common errors.
2002-03-21 Werner Koch <wk@gnupg.org>
* export.c: New.
* gpgsm.c: Add command --export.
* server.c (cmd_export): New.
2002-03-13 Werner Koch <wk@gnupg.org>
* decrypt.c (gpgsm_decrypt): Allow multiple recipients.
2002-03-12 Werner Koch <wk@gnupg.org>
* certpath.c (check_cert_policy): Print the policy list.
* verify.c (gpgsm_verify): Detect certs-only message.
2002-03-11 Werner Koch <wk@gnupg.org>
* import.c (gpgsm_import): Print a notice about imported certificates
when in verbose mode.
* gpgsm.c (main): Print INV_RECP status.
* server.c (cmd_recipient): Ditto.
* server.c (gpgsm_status2): New. Allows for a list of strings.
(gpgsm_status): Divert to gpgsm_status2.
* encrypt.c (gpgsm_encrypt): Don't use a default key when no
recipients are given. Print a NO_RECP status.
2002-03-06 Werner Koch <wk@gnupg.org>
* server.c (cmd_listkeys, cmd_listsecretkeys): Divert to
(do_listkeys): new. Add pattern parsing.
* keylist.c (gpgsm_list_keys): Handle selection pattern.
* gpgsm.c: New command --learn-card
* call-agent.c (learn_cb,gpgsm_agent_learn): New.
* gpgsm.c (main): Print error messages for non-implemented commands.
* base64.c (base64_reader_cb): Use case insensitive compare of the
Content-Type string to detect plain base-64.
2002-03-05 Werner Koch <wk@gnupg.org>
* gpgsm.c, gpgsm.h: Add local_user.
* sign.c (gpgsm_get_default_cert): New.
(get_default_signer): Use the new function if local_user is not
set otherwise used that value.
* encrypt.c (get_default_recipient): Removed.
(gpgsm_encrypt): Use gpgsm_get_default_cert.
* verify.c (gpgsm_verify): Better error text for a bad signature
found by comparing the hashs.
2002-02-27 Werner Koch <wk@gnupg.org>
* call-dirmngr.c, call-agent.c: Add 2 more arguments to all uses
of assuan_transact.
2002-02-25 Werner Koch <wk@gnupg.org>
* server.c (option_handler): Allow to use -2 for "send all certs
except the root cert".
* sign.c (add_certificate_list): Implement it here.
* certpath.c (gpgsm_is_root_cert): New.
2002-02-19 Werner Koch <wk@gnupg.org>
* certpath.c (check_cert_policy): New.
(gpgsm_validate_path): And call it from here.
* gpgsm.c (main): New options --policy-file,
--disable-policy-checks and --enable-policy-checks.
* gpgsm.h (opt): Added policy_file, no_policy_checks.
2002-02-18 Werner Koch <wk@gnupg.org>
* certpath.c (gpgsm_validate_path): Ask the agent to add the
certificate into the trusted list.
* call-agent.c (gpgsm_agent_marktrusted): New.
2002-02-07 Werner Koch <wk@gnupg.org>
* certlist.c (gpgsm_add_to_certlist): Check that the specified
name identifies a certificate unambiguously.
(gpgsm_find_cert): Ditto.
* server.c (cmd_listkeys): Check that the data stream is available.
(cmd_listsecretkeys): Ditto.
(has_option): New.
(cmd_sign): Fix ambiguousity in option recognition.
* gpgsm.c (main): Enable --logger-fd.
* encrypt.c (gpgsm_encrypt): Increased buffer size for better
performance.
* call-agent.c (gpgsm_agent_pksign): Check the S-Exp received from
the agent.
* keylist.c (list_cert_colon): Filter out control characters.
2002-02-06 Werner Koch <wk@gnupg.org>
* decrypt.c (gpgsm_decrypt): Bail out after an decryption error.
* server.c (reset_notify): Close input and output FDs.
(cmd_encrypt,cmd_decrypt,cmd_verify,cmd_sign.cmd_import)
(cmd_genkey): Close the FDs and release the recipient list even in
the error case.
2002-02-01 Marcus Brinkmann <marcus@g10code.de>
* sign.c (gpgsm_sign): Do not release certificate twice.
2002-01-29 Werner Koch <wk@gnupg.org>
* call-agent.c (gpgsm_agent_havekey): New.
* keylist.c (list_cert_colon): New arg HAVE_SECRET, print "crs"
when we know that the secret key is available.
(gpgsm_list_keys): New arg MODE, check whether a secret key is
available. Changed all callers.
* gpgsm.c (main): New command --list-secret-keys.
* server.c (cmd_listsecretkeys): New.
(cmd_listkeys): Return secret keys with "crs" record.
2002-01-28 Werner Koch <wk@gnupg.org>
* certreqgen.c (create_request): Store the email address in the req.
2002-01-25 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): Disable core dumps.
* sign.c (add_certificate_list): New.
(gpgsm_sign): Add the certificates to the CMS object.
* certpath.c (gpgsm_walk_cert_chain): New.
* gpgsm.h (server_control_s): Add included_certs.
* gpgsm.c: Add option --include-certs.
(gpgsm_init_default_ctrl): New.
(main): Call it.
* server.c (gpgsm_server): Ditto.
(option_handler): Support --include-certs.
2002-01-23 Werner Koch <wk@gnupg.org>
* certpath.c (gpgsm_validate_path): Print the DN of a missing issuer.
* certdump.c (gpgsm_dump_string): New.
(print_dn): Replaced by above.
2002-01-22 Werner Koch <wk@gnupg.org>
* certpath.c (unknown_criticals): New.
(allowed_ca): New.
(gpgsm_validate_path): Check validity, CA attribute, path length
and unknown critical extensions.
2002-01-21 Werner Koch <wk@gnupg.org>
* gpgsm.c: Add option --enable-crl-checks.
* call-agent.c (start_agent): Implemented socket based access.
* call-dirmngr.c (start_dirmngr): Ditto.
2002-01-20 Werner Koch <wk@gnupg.org>
* server.c (option_handler): New.
(gpgsm_server): Register it with assuan.
2002-01-19 Werner Koch <wk@gnupg.org>
* server.c (gpgsm_server): Use assuan_deinit_server and setup
assuan logging if enabled.
* call-agent.c (inq_ciphertext_cb): Don't show the session key in
an Assuan log file.
* gpgsm.c (my_strusage): Take bugreport address from configure.ac
2002-01-15 Werner Koch <wk@gnupg.org>
* import.c (gpgsm_import): Just do a basic cert check before
storing it.
* certpath.c (gpgsm_basic_cert_check): New.
* keydb.c (keydb_store_cert): New.
* import.c (store_cert): Removed and change all caller to use
the new function.
* verify.c (store_cert): Ditto.
* certlist.c (gpgsm_add_to_certlist): Validate the path
* certpath.c (gpgsm_validate_path): Check the trust list.
* call-agent.c (gpgsm_agent_istrusted): New.
2002-01-14 Werner Koch <wk@gnupg.org>
* call-dirmngr.c (inq_certificate): Changed for new interface semantic.
* certlist.c (gpgsm_find_cert): New.
2002-01-13 Werner Koch <wk@gnupg.org>
* fingerprint.c (gpgsm_get_certid): Print the serial and not the
hash after the dot.
2002-01-11 Werner Koch <wk@gnupg.org>
* call-dirmngr.c: New.
* certpath.c (gpgsm_validate_path): Check the CRL here.
* fingerprint.c (gpgsm_get_certid): New.
* gpgsm.c: New options --dirmngr-program and --disable-crl-checks.
2002-01-10 Werner Koch <wk@gnupg.org>
* base64.c (gpgsm_create_writer): Allow to set the object name
2002-01-08 Werner Koch <wk@gnupg.org>
* keydb.c (spacep): Removed because it is now in util.c
* server.c (cmd_genkey): New.
* certreqgen.c: New. The parameter handling code has been taken
from gnupg/g10/keygen.c version 1.0.6.
* call-agent.c (gpgsm_agent_genkey): New.
2002-01-02 Werner Koch <wk@gnupg.org>
* server.c (rc_to_assuan_status): Removed and changed all callers
to use map_to_assuan_status.
2001-12-20 Werner Koch <wk@gnupg.org>
* verify.c (gpgsm_verify): Implemented non-detached signature
verification. Add OUT_FP arg, initialize a writer and changed all
callers.
* server.c (cmd_verify): Pass an out_fp if one has been set.
* base64.c (base64_reader_cb): Try to detect an S/MIME body part.
* certdump.c (print_sexp): Renamed to gpgsm_dump_serial, made
global.
(print_time): Renamed to gpgsm_dump_time, made global.
(gpgsm_dump_serial): Take a real S-Expression as argument and
print the first item.
* keylist.c (list_cert_colon): Ditto.
* keydb.c (keydb_search_issuer_sn): Ditto.
* decrypt.c (print_integer_sexp): Removed and made callers
use gpgsm_dump_serial.
* verify.c (print_time): Removed, made callers use gpgsm_dump_time.
2001-12-19 Marcus Brinkmann <marcus@g10code.de>
* call-agent.c (start_agent): Add new argument to assuan_pipe_connect.
2001-12-18 Werner Koch <wk@gnupg.org>
* verify.c (print_integer_sexp): Renamed from print_integer and
print the serial number according to the S-Exp rules.
* decrypt.c (print_integer_sexp): Ditto.
2001-12-17 Werner Koch <wk@gnupg.org>
* keylist.c (list_cert_colon): Changed for new return value of
get_serial.
* keydb.c (keydb_search_issuer_sn): Ditto.
* certcheck.c (gpgsm_check_cert_sig): Likewise for other S-Exp
returingin functions.
* fingerprint.c (gpgsm_get_keygrip): Ditto.
* encrypt.c (encrypt_dek): Ditto
* certcheck.c (gpgsm_check_cms_signature): Ditto
* decrypt.c (prepare_decryption): Ditto.
* call-agent.c (gpgsm_agent_pkdecrypt): Removed arg ciphertextlen,
use KsbaSexp type and calculate the length.
* certdump.c (print_sexp): Remaned from print_integer, changed caller.
* Makefile.am: Use the LIBGCRYPT and LIBKSBA variables.
* fingerprint.c (gpgsm_get_keygrip): Use the new
gcry_pk_get_keygrip to calculate the grip - note the algorithm and
therefore the grip values changed.
2001-12-15 Werner Koch <wk@gnupg.org>
* certcheck.c (gpgsm_check_cms_signature): Removed the faked-key
kludge.
(gpgsm_create_cms_signature): Removed the commented fake key
code. This makes the function pretty simple.
* gpgsm.c (main): Renamed the default key database to "keyring.kbx".
* decrypt.c (gpgsm_decrypt): Write STATUS_DECRYPTION_*.
* sign.c (gpgsm_sign): Write a STATUS_SIG_CREATED.
2001-12-14 Werner Koch <wk@gnupg.org>
* keylist.c (list_cert_colon): Kludge to show an email address
encoded in the subject's DN.
* verify.c (gpgsm_verify): Add hash debug helpers
* sign.c (gpgsm_sign): Ditto.
* base64.c (base64_reader_cb): Reset the linelen when we need to
skip the line and adjusted test; I somehow forgot about DeMorgan.
* server.c (cmd_encrypt,cmd_decrypt,cmd_sign,cmd_verify)
(cmd_import): Close the FDs on success.
(close_message_fd): New.
(input_notify): Setting autodetect_encoding to 0 after initializing
it to 0 is pretty pointless. Easy to fix.
* gpgsm.c (main): New option --debug-wait n, so that it is
possible to attach gdb when used in server mode.
* sign.c (get_default_signer): Use keydb_classify_name here.
2001-12-14 Marcus Brinkmann <marcus@g10code.de>
* call-agent.c (LINELENGTH): Removed.
(gpgsm_agent_pksign): Use ASSUAN_LINELENGTH, not LINELENGTH.
(gpgsm_agent_pkdecrypt): Likewise.
2001-12-13 Werner Koch <wk@gnupg.org>
* keylist.c (list_cert_colon): Print alternative names of subject
and a few other values.
2001-12-12 Werner Koch <wk@gnupg.org>
* gpgsm.c (main): New options --assume-{armor,base64,binary}.
* base64.c (base64_reader_cb): Fixed non-autodetection mode.
2001-12-04 Werner Koch <wk@gnupg.org>
* call-agent.c (read_from_agent): Check for inquire responses.
(request_reply): Handle them using a new callback arg, changed all
callers.
(gpgsm_agent_pkdecrypt): New.
2001-11-27 Werner Koch <wk@gnupg.org>
* base64.c: New. Changed all other functions to use this instead
of direct creation of ksba_reader/writer.
* gpgsm.c (main): Set ctrl.auto_encoding unless --no-armor is used.
2001-11-26 Werner Koch <wk@gnupg.org>
* gpgsm.c: New option --agent-program
* call-agent.c (start_agent): Allow to override the default path
to the agent.
* keydb.c (keydb_add_resource): Create keybox
* keylist.c (gpgsm_list_keys): Fixed non-server keylisting.
* server.c (rc_to_assuan_status): New. Use it for all commands.
Copyright 2001, 2002 Free Software Foundation, Inc.
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/sm/Makefile.am b/sm/Makefile.am
index 3061cb51b..489e59ebe 100644
--- a/sm/Makefile.am
+++ b/sm/Makefile.am
@@ -1,53 +1,54 @@
# Copyright (C) 2001, 2002 Free Software Foundation, Inc.
#
# This file is part of GnuPG.
#
# GnuPG 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.
#
# GnuPG 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
## Process this file with automake to produce Makefile.in
bin_PROGRAMS = gpgsm
AM_CPPFLAGS = -I$(top_srcdir)/common -I$(top_srcdir)/intl \
$(LIBGCRYPT_CFLAGS) $(LIBKSBA_CFLAGS)
LDFLAGS = @LDFLAGS@
gpgsm_SOURCES = \
gpgsm.c gpgsm.h \
misc.c \
keydb.c keydb.h \
server.c \
call-agent.c \
call-dirmngr.c \
fingerprint.c \
base64.c \
certlist.c \
certdump.c \
certcheck.c \
certpath.c \
keylist.c \
verify.c \
sign.c \
encrypt.c \
decrypt.c \
import.c \
export.c \
+ delete.c \
certreqgen.c
gpgsm_LDADD = ../jnlib/libjnlib.a ../assuan/libassuan.a ../kbx/libkeybox.a \
../common/libcommon.a $(LIBGCRYPT_LIBS) $(LIBKSBA_LIBS)
diff --git a/sm/decrypt.c b/sm/decrypt.c
index ccbcae2a6..a793bbbef 100644
--- a/sm/decrypt.c
+++ b/sm/decrypt.c
@@ -1,487 +1,491 @@
/* decrypt.c - Decrypt a message
* Copyright (C) 2001 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#include <gcrypt.h>
#include <ksba.h>
#include "gpgsm.h"
#include "keydb.h"
#include "i18n.h"
struct decrypt_filter_parm_s {
int algo;
int mode;
int blklen;
GCRY_CIPHER_HD hd;
char iv[16];
size_t ivlen;
int any_data; /* dod we push anything through the filter at all? */
unsigned char lastblock[16]; /* to strip the padding we have to
keep this one */
char helpblock[16]; /* needed because there is no block buffering in
libgcrypt (yet) */
int helpblocklen;
};
/* decrypt the session key and fill in the parm structure. The
algo and the IV is expected to be already in PARM. */
static int
prepare_decryption (const char *hexkeygrip, KsbaConstSexp enc_val,
struct decrypt_filter_parm_s *parm)
{
char *seskey = NULL;
size_t n, seskeylen;
int rc;
rc = gpgsm_agent_pkdecrypt (hexkeygrip, enc_val,
&seskey, &seskeylen);
if (rc)
{
log_error ("error decrypting session key: %s\n", gnupg_strerror (rc));
goto leave;
}
if (DBG_CRYPTO)
log_printhex ("pkcs1 encoded session key:", seskey, seskeylen);
n=0;
if (n + 7 > seskeylen )
{
rc = seterr (Invalid_Session_Key);
goto leave;
}
/* FIXME: Actually the leading zero is required but due to the way
we encode the output in libgcrypt as an MPI we are not able to
encode that leading zero. However, when using a Smartcard we are
doing it the rightway and therefore we have to skip the zero. This
should be fixed in gpg-agent of course. */
if (!seskey[n])
n++;
if (seskey[n] != 2 ) /* wrong block type version */
{
rc = seterr (Invalid_Session_Key);
goto leave;
}
for (n++; n < seskeylen && seskey[n]; n++) /* skip the random bytes */
;
n++; /* and the zero byte */
if (n >= seskeylen )
{
rc = seterr (Invalid_Session_Key);
goto leave;
}
if (DBG_CRYPTO)
log_printhex ("session key:", seskey+n, seskeylen-n);
parm->hd = gcry_cipher_open (parm->algo, parm->mode, 0);
if (!parm->hd)
{
rc = gcry_errno ();
log_error ("error creating decryptor: %s\n", gcry_strerror (rc));
rc = map_gcry_err (rc);
goto leave;
}
rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
if (rc == GCRYERR_WEAK_KEY)
{
log_info (_("WARNING: message was encrypted with "
"a weak key in the symmetric cipher.\n"));
rc = 0;
}
if (rc)
{
log_error("key setup failed: %s\n", gcry_strerror(rc) );
rc = map_gcry_err (rc);
goto leave;
}
gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
leave:
xfree (seskey);
return rc;
}
/* This function is called by the KSBA writer just before the actual
write is done. The function must take INLEN bytes from INBUF,
decrypt it and store it inoutbuf which has a maximum size of
maxoutlen. The valid bytes in outbuf should be return in outlen.
Due to different buffer sizes or different length of input and
output, it may happen that fewer bytes are process or fewer bytes
are written. */
static KsbaError
decrypt_filter (void *arg,
const void *inbuf, size_t inlen, size_t *inused,
void *outbuf, size_t maxoutlen, size_t *outlen)
{
struct decrypt_filter_parm_s *parm = arg;
int blklen = parm->blklen;
size_t orig_inlen = inlen;
/* fixme: Should we issue an error when we have not seen one full block? */
if (!inlen)
return KSBA_Bug;
if (maxoutlen < 2*parm->blklen)
return KSBA_Bug;
/* make some space becuase we will later need an extra block at the end */
maxoutlen -= blklen;
if (parm->helpblocklen)
{
int i, j;
for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
parm->helpblock[i] = ((const char*)inbuf)[j];
inlen -= j;
if (blklen > maxoutlen)
return KSBA_Bug;
if (i < blklen)
{
parm->helpblocklen = i;
*outlen = 0;
}
else
{
parm->helpblocklen = 0;
if (parm->any_data)
{
memcpy (outbuf, parm->lastblock, blklen);
*outlen =blklen;
}
else
*outlen = 0;
gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
parm->helpblock, blklen);
parm->any_data = 1;
}
*inused = orig_inlen - inlen;
return 0;
}
if (inlen > maxoutlen)
inlen = maxoutlen;
if (inlen % blklen)
{ /* store the remainder away */
parm->helpblocklen = inlen%blklen;
inlen = inlen/blklen*blklen;
memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
}
*inused = inlen + parm->helpblocklen;
if (inlen)
{
assert (inlen >= blklen);
if (parm->any_data)
{
gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
inbuf, inlen);
memcpy (outbuf, parm->lastblock, blklen);
memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
*outlen = inlen;
}
else
{
gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
*outlen = inlen - blklen;
parm->any_data = 1;
}
}
else
*outlen = 0;
return 0;
}
/* Perform a decrypt operation. */
int
gpgsm_decrypt (CTRL ctrl, int in_fd, FILE *out_fp)
{
int rc;
KsbaError err;
Base64Context b64reader = NULL;
Base64Context b64writer = NULL;
KsbaReader reader;
KsbaWriter writer;
KsbaCMS cms = NULL;
KsbaStopReason stopreason;
KEYDB_HANDLE kh;
int recp;
FILE *in_fp = NULL;
struct decrypt_filter_parm_s dfparm;
memset (&dfparm, 0, sizeof dfparm);
kh = keydb_new (0);
if (!kh)
{
log_error (_("failed to allocated keyDB handle\n"));
rc = GNUPG_General_Error;
goto leave;
}
in_fp = fdopen ( dup (in_fd), "rb");
if (!in_fp)
{
log_error ("fdopen() failed: %s\n", strerror (errno));
rc = seterr (IO_Error);
goto leave;
}
rc = gpgsm_create_reader (&b64reader, ctrl, in_fp, &reader);
if (rc)
{
log_error ("can't create reader: %s\n", gnupg_strerror (rc));
goto leave;
}
rc = gpgsm_create_writer (&b64writer, ctrl, out_fp, &writer);
if (rc)
{
log_error ("can't create writer: %s\n", gnupg_strerror (rc));
goto leave;
}
cms = ksba_cms_new ();
if (!cms)
{
rc = seterr (Out_Of_Core);
goto leave;
}
err = ksba_cms_set_reader_writer (cms, reader, writer);
if (err)
{
log_debug ("ksba_cms_set_reader_writer failed: %s\n",
ksba_strerror (err));
rc = map_ksba_err (err);
goto leave;
}
/* parser loop */
do
{
err = ksba_cms_parse (cms, &stopreason);
if (err)
{
log_debug ("ksba_cms_parse failed: %s\n", ksba_strerror (err));
rc = map_ksba_err (err);
goto leave;
}
if (stopreason == KSBA_SR_BEGIN_DATA
|| stopreason == KSBA_SR_DETACHED_DATA)
{
int algo, mode;
const char *algoid;
int any_key = 0;
algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
algo = gcry_cipher_map_name (algoid);
mode = gcry_cipher_mode_from_oid (algoid);
if (!algo || !mode)
{
log_error ("unsupported algorithm `%s'\n", algoid? algoid:"?");
+ if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
+ log_info (_("(this is the RC2 algorithm)\n"));
+ gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
+ gnupg_error_token (rc), algoid, NULL);
rc = GNUPG_Unsupported_Algorithm;
goto leave;
}
dfparm.algo = algo;
dfparm.mode = mode;
dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
if (dfparm.blklen > sizeof (dfparm.helpblock))
return GNUPG_Bug;
rc = ksba_cms_get_content_enc_iv (cms,
dfparm.iv,
sizeof (dfparm.iv),
&dfparm.ivlen);
if (rc)
{
log_error ("error getting IV: %s\n", ksba_strerror (err));
rc = map_ksba_err (err);
goto leave;
}
for (recp=0; !any_key; recp++)
{
char *issuer;
KsbaSexp serial;
KsbaSexp enc_val;
char *hexkeygrip = NULL;
err = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
if (err == -1 && recp)
break; /* no more recipients */
if (err)
log_error ("recp %d - error getting info: %s\n",
recp, ksba_strerror (err));
else
{
KsbaCert cert = NULL;
log_debug ("recp %d - issuer: `%s'\n",
recp, issuer? issuer:"[NONE]");
log_debug ("recp %d - serial: ", recp);
gpgsm_dump_serial (serial);
log_printf ("\n");
keydb_search_reset (kh);
rc = keydb_search_issuer_sn (kh, issuer, serial);
if (rc)
{
log_error ("failed to find the certificate: %s\n",
gnupg_strerror(rc));
goto oops;
}
rc = keydb_get_cert (kh, &cert);
if (rc)
{
log_error ("failed to get cert: %s\n", gnupg_strerror (rc));
goto oops;
}
/* Just in case there is a problem with the own
certificate we print this message - should never
happen of course */
rc = gpgsm_cert_use_decrypt_p (cert);
if (rc)
{
gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
gnupg_error_token (rc), NULL);
rc = 0;
}
hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
oops:
xfree (issuer);
xfree (serial);
ksba_cert_release (cert);
}
if (!hexkeygrip)
;
else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
log_error ("recp %d - error getting encrypted session key\n",
recp);
else
{
rc = prepare_decryption (hexkeygrip, enc_val, &dfparm);
xfree (enc_val);
if (rc)
{
log_debug ("decrypting session key failed: %s\n",
gnupg_strerror (rc));
}
else
{ /* setup the bulk decrypter */
any_key = 1;
ksba_writer_set_filter (writer,
decrypt_filter,
&dfparm);
}
}
}
if (!any_key)
{
rc = GNUPG_No_Secret_Key;
goto leave;
}
}
else if (stopreason == KSBA_SR_END_DATA)
{
ksba_writer_set_filter (writer, NULL, NULL);
if (dfparm.any_data)
{ /* write the last block with padding removed */
int i, npadding = dfparm.lastblock[dfparm.blklen-1];
if (!npadding || npadding > dfparm.blklen)
{
log_error ("invalid padding with value %d\n", npadding);
rc = seterr (Invalid_Data);
goto leave;
}
rc = ksba_writer_write (writer,
dfparm.lastblock,
dfparm.blklen - npadding);
if (rc)
{
rc = map_ksba_err (rc);
goto leave;
}
for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
{
if (dfparm.lastblock[i] != npadding)
{
log_error ("inconsistent padding\n");
rc = seterr (Invalid_Data);
goto leave;
}
}
}
}
}
while (stopreason != KSBA_SR_READY);
rc = gpgsm_finish_writer (b64writer);
if (rc)
{
log_error ("write failed: %s\n", gnupg_strerror (rc));
goto leave;
}
gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
leave:
if (rc)
gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
ksba_cms_release (cms);
gpgsm_destroy_reader (b64reader);
gpgsm_destroy_writer (b64writer);
keydb_release (kh);
if (in_fp)
fclose (in_fp);
if (dfparm.hd)
gcry_cipher_close (dfparm.hd);
return rc;
}
diff --git a/sm/delete.c b/sm/delete.c
new file mode 100644
index 000000000..cd1491a86
--- /dev/null
+++ b/sm/delete.c
@@ -0,0 +1,165 @@
+/* delete.c
+ * Copyright (C) 2002 Free Software Foundation, Inc.
+ *
+ * This file is part of GnuPG.
+ *
+ * GnuPG 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.
+ *
+ * GnuPG 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 for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
+ */
+
+#include <config.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <time.h>
+#include <assert.h>
+
+#include <gcrypt.h>
+#include <ksba.h>
+
+#include "gpgsm.h"
+#include "keydb.h"
+#include "i18n.h"
+
+
+/* Delete a certificate or an secret key from a key database. */
+static int
+delete_one (CTRL ctrl, const char *username)
+{
+ int rc = 0;
+ KEYDB_SEARCH_DESC desc;
+ KEYDB_HANDLE kh = NULL;
+ KsbaCert cert = NULL;
+ int duplicates = 0;
+
+ rc = keydb_classify_name (username, &desc);
+ if (rc)
+ {
+ log_error (_("certificate `%s' not found: %s\n"),
+ username, gnupg_strerror (rc));
+ gpgsm_status2 (ctrl, STATUS_DELETE_PROBLEM, "1", NULL);
+ goto leave;
+ }
+
+ kh = keydb_new (0);
+ if (!kh)
+ {
+ log_error ("keydb_new failed\n");
+ goto leave;
+ }
+
+
+ rc = keydb_search (kh, &desc, 1);
+ if (!rc)
+ rc = keydb_get_cert (kh, &cert);
+ if (!rc)
+ {
+ char fpr[20];
+
+ gpgsm_get_fingerprint (cert, 0, fpr, NULL);
+
+ next_ambigious:
+ rc = keydb_search (kh, &desc, 1);
+ if (rc == -1)
+ rc = 0;
+ else if (!rc)
+ {
+ KsbaCert cert2 = NULL;
+ char fpr2[20];
+
+ /* We ignore all duplicated certificates which might have
+ been inserted due to program bugs. */
+ if (!keydb_get_cert (kh, &cert2))
+ {
+ gpgsm_get_fingerprint (cert2, 0, fpr2, NULL);
+ ksba_cert_release (cert2);
+ if (!memcmp (fpr, fpr2, 20))
+ {
+ duplicates++;
+ goto next_ambigious;
+ }
+ }
+ rc = GNUPG_Ambiguous_Name;
+ }
+ }
+ if (rc)
+ {
+ if (rc == -1)
+ rc = GNUPG_No_Public_Key;
+ log_error (_("certificate `%s' not found: %s\n"),
+ username, gnupg_strerror (rc));
+ gpgsm_status2 (ctrl, STATUS_DELETE_PROBLEM, "3", NULL);
+ goto leave;
+ }
+
+ /* we need to search again to get back to the right position. */
+ do
+ {
+ keydb_search_reset (kh);
+ rc = keydb_search (kh, &desc, 1);
+ if (rc)
+ {
+ log_error ("problem re-searching certificate: %s\n",
+ gnupg_strerror (rc));
+ goto leave;
+ }
+
+ rc = keydb_delete (kh);
+ if (rc)
+ goto leave;
+ if (opt.verbose)
+ {
+ if (duplicates)
+ log_info (_("duplicated certificate `%s' deleted\n"), username);
+ else
+ log_info (_("certificate `%s' deleted\n"), username);
+ }
+ }
+ while (duplicates--);
+
+ leave:
+ keydb_release (kh);
+ ksba_cert_release (cert);
+ return rc;
+}
+
+
+
+/* Delete the certificates specified by NAMES. */
+int
+gpgsm_delete (CTRL ctrl, STRLIST names)
+{
+ int rc;
+
+ if (!names)
+ {
+ log_error ("nothing to delete\n");
+ return GNUPG_No_Data;
+ }
+
+ for (; names; names=names->next )
+ {
+ rc = delete_one (ctrl, names->d);
+ if (rc)
+ {
+ log_error (_("deleting certificate \"%s\" failed: %s\n"),
+ names->d, gnupg_strerror (rc) );
+ return rc;
+ }
+ }
+
+ return 0;
+}
diff --git a/sm/fingerprint.c b/sm/fingerprint.c
index 88fe72b1e..d8b6ec4a3 100644
--- a/sm/fingerprint.c
+++ b/sm/fingerprint.c
@@ -1,260 +1,260 @@
/* fingerprint.c - Get the fingerprint
* Copyright (C) 2001 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#include <gcrypt.h>
#include <ksba.h>
#include "gpgsm.h"
/* Return the fingerprint of the certificate (we can't put this into
libksba because we need libgcrypt support). The caller must
provide an array of sufficient length or NULL so that the function
allocates the array. If r_len is not NULL, the length of the
- digest is return, well, this can also be done by using
+ digest is returned; well, this can also be done by using
gcry_md_get_algo_dlen(). If algo is 0, a SHA-1 will be used.
If there is a problem , the function does never return NULL but a
digest of all 0xff.
*/
char *
gpgsm_get_fingerprint (KsbaCert cert, int algo, char *array, int *r_len)
{
GCRY_MD_HD md;
int rc, len;
if (!algo)
algo = GCRY_MD_SHA1;
len = gcry_md_get_algo_dlen (algo);
assert (len);
if (!array)
array = xmalloc (len);
if (r_len)
*r_len = len;
md = gcry_md_open (algo, 0);
if (!md)
{
log_error ("md_open failed: %s\n", gcry_strerror (-1));
memset (array, 0xff, len); /* better return an invalid fpr than NULL */
return array;
}
rc = ksba_cert_hash (cert, 0, HASH_FNC, md);
if (rc)
{
log_error ("ksba_cert_hash failed: %s\n", ksba_strerror (rc));
gcry_md_close (md);
memset (array, 0xff, len); /* better return an invalid fpr than NULL */
return array;
}
gcry_md_final (md);
memcpy (array, gcry_md_read(md, algo), len );
return array;
}
/* Return an allocated buffer with the formatted fingerprint */
char *
gpgsm_get_fingerprint_string (KsbaCert cert, int algo)
{
unsigned char digest[MAX_DIGEST_LEN];
char *buf;
int len, i;
if (!algo)
algo = GCRY_MD_SHA1;
len = gcry_md_get_algo_dlen (algo);
assert (len <= MAX_DIGEST_LEN );
gpgsm_get_fingerprint (cert, algo, digest, NULL);
buf = xmalloc (len*3+1);
*buf = 0;
for (i=0; i < len; i++ )
sprintf (buf+strlen(buf), i? ":%02X":"%02X", digest[i]);
return buf;
}
/* Return an allocated buffer with the formatted fungerprint as one
large hexnumber */
char *
gpgsm_get_fingerprint_hexstring (KsbaCert cert, int algo)
{
unsigned char digest[MAX_DIGEST_LEN];
char *buf;
int len, i;
if (!algo)
algo = GCRY_MD_SHA1;
len = gcry_md_get_algo_dlen (algo);
assert (len <= MAX_DIGEST_LEN );
gpgsm_get_fingerprint (cert, algo, digest, NULL);
buf = xmalloc (len*3+1);
*buf = 0;
for (i=0; i < len; i++ )
sprintf (buf+strlen(buf), "%02X", digest[i]);
return buf;
}
/* Return the so called KEYGRIP which is the SHA-1 hash of the public
key parameters expressed as an canoncial encoded S-Exp. array must
be 20 bytes long. returns the array or a newly allocated one if the
passed one was NULL */
char *
gpgsm_get_keygrip (KsbaCert cert, char *array)
{
GCRY_SEXP s_pkey;
int rc;
KsbaSexp p;
size_t n;
p = ksba_cert_get_public_key (cert);
if (!p)
return NULL; /* oops */
if (DBG_X509)
log_debug ("get_keygrip for public key: %s\n", p);
n = gcry_sexp_canon_len (p, 0, NULL, NULL);
if (!n)
{
log_error ("libksba did not return a proper S-Exp\n");
return NULL;
}
rc = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
xfree (p);
if (rc)
{
log_error ("gcry_sexp_scan failed: %s\n", gcry_strerror (rc));
return NULL;
}
array = gcry_pk_get_keygrip (s_pkey, array);
gcry_sexp_release (s_pkey);
if (!array)
{
rc = seterr (General_Error);
log_error ("can't calculate keygrip\n");
return NULL;
}
if (DBG_X509)
log_printhex ("keygrip=", array, 20);
return array;
}
/* Return an allocated buffer with the keygrip of CERT in from of an
hexstring. NULL is returned in case of error */
char *
gpgsm_get_keygrip_hexstring (KsbaCert cert)
{
unsigned char grip[20];
char *buf, *p;
int i;
gpgsm_get_keygrip (cert, grip);
buf = p = xmalloc (20*2+1);
for (i=0; i < 20; i++, p += 2 )
sprintf (p, "%02X", grip[i]);
return buf;
}
/* For certain purposes we need a certificate id which has an upper
limit of the size. We use the hash of the issuer name and the
serial number for this. In most cases the serial number is not
that large and the resulting string can be passed on an assuan
command line. Everything is hexencoded with the serialnumber
delimted from the has by a dot.
The caller must free the string.
*/
char *
gpgsm_get_certid (KsbaCert cert)
{
KsbaSexp serial;
unsigned char *p;
char *endp;
unsigned char hash[20];
unsigned long n;
char *certid;
int i;
p = ksba_cert_get_issuer (cert, 0);
if (!p)
return NULL; /* Ooops: No issuer */
gcry_md_hash_buffer (GCRY_MD_SHA1, hash, p, strlen (p));
xfree (p);
serial = ksba_cert_get_serial (cert);
if (!serial)
return NULL; /* oops: no serial number */
p = serial;
if (*p != '(')
{
log_error ("Ooops: invalid serial number\n");
xfree (serial);
return NULL;
}
p++;
n = strtoul (p, &endp, 10);
p = endp;
if (*p != ':')
{
log_error ("Ooops: invalid serial number (no colon)\n");
xfree (serial);
return NULL;
}
p++;
certid = xtrymalloc ( 40 + 1 + n*2 + 1);
if (!certid)
{
xfree (serial);
return NULL; /* out of core */
}
for (i=0, endp = certid; i < 20; i++, endp += 2 )
sprintf (endp, "%02X", hash[i]);
*endp++ = '.';
for (i=0; i < n; i++, endp += 2)
sprintf (endp, "%02X", p[i]);
*endp = 0;
xfree (serial);
return certid;
}
diff --git a/sm/gpgsm.c b/sm/gpgsm.c
index f2287ef20..9efeca79f 100644
--- a/sm/gpgsm.c
+++ b/sm/gpgsm.c
@@ -1,1444 +1,1441 @@
/* gpgsm.c - GnuPG for S/MIME
* Copyright (C) 2001, 2002 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <gcrypt.h>
#include "gpgsm.h"
#include "../assuan/assuan.h" /* malloc hooks */
#include "../kbx/keybox.h" /* malloc hooks */
#include "i18n.h"
#include "keydb.h"
#include "sysutils.h"
enum cmd_and_opt_values {
aNull = 0,
oArmor = 'a',
aDetachedSign = 'b',
aSym = 'c',
aDecrypt = 'd',
aEncr = 'e',
oInteractive = 'i',
oKOption = 'k',
oDryRun = 'n',
oOutput = 'o',
oQuiet = 'q',
oRecipient = 'r',
aSign = 's',
oTextmodeShort= 't',
oUser = 'u',
oVerbose = 'v',
oCompress = 'z',
oNotation = 'N',
oBatch = 500,
aClearsign,
aStore,
aKeygen,
aSignEncr,
aSignKey,
aLSignKey,
aListPackets,
aEditKey,
aDeleteKey,
aImport,
aVerify,
aVerifyFiles,
aListKeys,
aListExternalKeys,
aListSigs,
aListSecretKeys,
aSendKeys,
aRecvKeys,
aExport,
aCheckKeys,
aServer,
aLearnCard,
oOptions,
oDebug,
oDebugAll,
oDebugWait,
oDebugNoPathValidation,
oLogFile,
oEnableSpecialFilenames,
oAgentProgram,
oDisplay,
oTTYname,
oTTYtype,
oLCctype,
oLCmessages,
oDirmngrProgram,
oFakedSystemTime,
oAssumeArmor,
oAssumeBase64,
oAssumeBinary,
oBase64,
oNoArmor,
oDisableCRLChecks,
oEnableCRLChecks,
oIncludeCerts,
oPolicyFile,
oDisablePolicyChecks,
oEnablePolicyChecks,
oAutoIssuerKeyRetrieve,
oTextmode,
oFingerprint,
oWithFingerprint,
oAnswerYes,
oAnswerNo,
oKeyring,
oSecretKeyring,
oDefaultKey,
oDefRecipient,
oDefRecipientSelf,
oNoDefRecipient,
oStatusFD,
oNoComment,
oNoVersion,
oEmitVersion,
oCompletesNeeded,
oMarginalsNeeded,
oMaxCertDepth,
oLoadExtension,
oRFC1991,
oOpenPGP,
oCipherAlgo,
oDigestAlgo,
oCompressAlgo,
oPasswdFD,
oCommandFD,
oNoVerbose,
oTrustDBName,
oNoSecmemWarn,
oNoDefKeyring,
oNoGreeting,
oNoTTY,
oNoOptions,
oNoBatch,
oHomedir,
oWithColons,
oWithKeyData,
oSkipVerify,
oCompressKeys,
oCompressSigs,
oAlwaysTrust,
oRunAsShmCP,
oSetFilename,
oSetPolicyURL,
oUseEmbeddedFilename,
oComment,
oDefaultComment,
oThrowKeyid,
oForceV3Sigs,
oForceMDC,
oS2KMode,
oS2KDigest,
oS2KCipher,
oCharset,
oNotDashEscaped,
oEscapeFrom,
oLockOnce,
oLockMultiple,
oLockNever,
oKeyServer,
oEncryptTo,
oNoEncryptTo,
oLoggerFD,
oUtf8Strings,
oNoUtf8Strings,
oDisableCipherAlgo,
oDisablePubkeyAlgo,
oAllowNonSelfsignedUID,
oAllowFreeformUID,
oNoLiteral,
oSetFilesize,
oHonorHttpProxy,
oFastListMode,
oListOnly,
oIgnoreTimeConflict,
oNoRandomSeedFile,
oNoAutoKeyRetrieve,
oUseAgent,
oMergeOnly,
oTryAllSecrets,
oTrustedKey,
oEmuMDEncodeBug,
aDummy
};
static ARGPARSE_OPTS opts[] = {
{ 300, NULL, 0, N_("@Commands:\n ") },
{ aSign, "sign", 256, N_("|[file]|make a signature")},
{ aClearsign, "clearsign", 256, N_("|[file]|make a clear text signature") },
{ aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
{ aEncr, "encrypt", 256, N_("encrypt data")},
{ aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
{ aDecrypt, "decrypt", 256, N_("decrypt data (default)")},
{ aVerify, "verify" , 256, N_("verify a signature")},
{ aVerifyFiles, "verify-files" , 256, "@" },
{ aListKeys, "list-keys", 256, N_("list keys")},
{ aListExternalKeys, "list-external-keys", 256, N_("list external keys")},
{ aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
{ aListSigs, "list-sigs", 256, N_("list certificate chain")},
{ aListSigs, "check-sigs",256, "@"},
{ oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
{ aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
{ aKeygen, "gen-key", 256, N_("generate a new key pair")},
{ aDeleteKey, "delete-key",256, N_("remove key from the public keyring")},
{ aSendKeys, "send-keys" , 256, N_("export keys to a key server") },
{ aRecvKeys, "recv-keys" , 256, N_("import keys from a key server") },
{ aImport, "import", 256 , N_("import certificates")},
{ aExport, "export", 256 , N_("export certificates")},
{ aLearnCard, "learn-card", 256 ,N_("register a smartcard")},
{ aServer, "server", 256, N_("run in server mode")},
{ oLogFile, "log-file" ,2, N_("use a log file for the server")},
{ 301, NULL, 0, N_("@\nOptions:\n ") },
{ oArmor, "armor", 0, N_("create ascii armored output")},
{ oArmor, "armour", 0, "@" },
{ oBase64, "base64", 0, N_("create base-64 encoded output")},
{ oAssumeArmor, "assume-armor", 0, N_("assume input is in PEM format")},
{ oAssumeBase64, "assume-base64", 0,
N_("assume input is in base-64 format")},
{ oAssumeBinary, "assume-binary", 0,
N_("assume input is in binary format")},
{ oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
{ oDisableCRLChecks, "disable-crl-checks", 0, N_("never consult a CRL")},
{ oEnableCRLChecks, "enable-crl-checks", 0, "@"},
{ oIncludeCerts, "include-certs", 1,
N_("|N|number of certificates to include") },
{ oPolicyFile, "policy-file", 2,
N_("|FILE|take policy information from FILE") },
{ oDisablePolicyChecks, "disable-policy-checks", 0,
N_("do not check certificate policies")},
{ oEnablePolicyChecks, "enable-policy-checks", 0, "@"},
{ oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve", 0,
N_("fetch missing issuer certificates")},
#if 0
{ oDefRecipient, "default-recipient" ,2,
N_("|NAME|use NAME as default recipient")},
{ oDefRecipientSelf, "default-recipient-self" ,0,
N_("use the default key as default recipient")},
{ oNoDefRecipient, "no-default-recipient", 0, "@" },
{ oEncryptTo, "encrypt-to", 2, "@" },
{ oNoEncryptTo, "no-encrypt-to", 0, "@" },
#endif
{ oUser, "local-user",2, N_("use this user-id to sign or decrypt")},
#if 0
{ oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
{ oTextmodeShort, NULL, 0, "@"},
{ oTextmode, "textmode", 0, N_("use canonical text mode")},
#endif
{ oOutput, "output", 2, N_("use as output file")},
{ oVerbose, "verbose", 0, N_("verbose") },
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
{ oNoTTY, "no-tty", 0, N_("don't use the terminal at all") },
#if 0
{ oForceV3Sigs, "force-v3-sigs", 0, N_("force v3 signatures") },
{ oForceMDC, "force-mdc", 0, N_("always use a MDC for encryption") },
#endif
{ oDryRun, "dry-run", 0, N_("do not make any changes") },
/*{ oInteractive, "interactive", 0, N_("prompt before overwriting") }, */
/*{ oUseAgent, "use-agent",0, N_("use the gpg-agent")},*/
{ oBatch, "batch", 0, N_("batch mode: never ask")},
{ oAnswerYes, "yes", 0, N_("assume yes on most questions")},
{ oAnswerNo, "no", 0, N_("assume no on most questions")},
{ oKeyring, "keyring" ,2, N_("add this keyring to the list of keyrings")},
{ oSecretKeyring, "secret-keyring" ,2, N_("add this secret keyring to the list")},
{ oDefaultKey, "default-key" ,2, N_("|NAME|use NAME as default secret key")},
{ oKeyServer, "keyserver",2, N_("|HOST|use this keyserver to lookup keys")},
{ oCharset, "charset" , 2, N_("|NAME|set terminal charset to NAME") },
{ oOptions, "options" , 2, N_("read options from file")},
{ oDebug, "debug" ,4|16, "@"},
{ oDebugAll, "debug-all" ,0, "@"},
{ oDebugWait, "debug-wait" ,1, "@"},
{ oDebugNoPathValidation, "debug-no-path-validation" ,0, "@"},
{ oStatusFD, "status-fd" ,1, N_("|FD|write status info to this FD") },
{ aDummy, "no-comment", 0, "@"},
{ aDummy, "completes-needed", 1, "@"},
{ aDummy, "marginals-needed", 1, "@"},
{ oMaxCertDepth, "max-cert-depth", 1, "@" },
{ aDummy, "trusted-key", 2, "@"},
{ oLoadExtension, "load-extension" ,2,
N_("|FILE|load extension module FILE")},
{ aDummy, "rfc1991", 0, "@"},
{ aDummy, "openpgp", 0, "@"},
{ aDummy, "s2k-mode", 1, "@"},
{ aDummy, "s2k-digest-algo",2, "@"},
{ aDummy, "s2k-cipher-algo",2, "@"},
{ oCipherAlgo, "cipher-algo", 2 , N_("|NAME|use cipher algorithm NAME")},
{ oDigestAlgo, "digest-algo", 2 ,
N_("|NAME|use message digest algorithm NAME")},
#if 0
{ oCompressAlgo, "compress-algo", 1 , N_("|N|use compress algorithm N")},
#endif
{ aDummy, "throw-keyid", 0, "@"},
{ aDummy, "notation-data", 2, "@"},
{ 302, NULL, 0, N_(
"@\n(See the man page for a complete listing of all commands and options)\n"
)},
{ 303, NULL, 0, N_("@\nExamples:\n\n"
" -se -r Bob [file] sign and encrypt for user Bob\n"
" --clearsign [file] make a clear text signature\n"
" --detach-sign [file] make a detached signature\n"
" --list-keys [names] show keys\n"
" --fingerprint [names] show fingerprints\n" ) },
/* hidden options */
{ oNoVerbose, "no-verbose", 0, "@"},
{ oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
{ oTrustDBName, "trustdb-name", 2, "@" },
{ oNoSecmemWarn, "no-secmem-warning", 0, "@" },
{ oNoArmor, "no-armor", 0, "@"},
{ oNoArmor, "no-armour", 0, "@"},
{ oNoDefKeyring, "no-default-keyring", 0, "@" },
{ oNoGreeting, "no-greeting", 0, "@" },
{ oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
{ oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
{ oAgentProgram, "agent-program", 2 , "@" },
{ oDisplay, "display", 2, "@" },
{ oTTYname, "ttyname", 2, "@" },
{ oTTYtype, "ttytype", 2, "@" },
{ oLCctype, "lc-ctype", 2, "@" },
{ oLCmessages, "lc-messages", 2, "@" },
{ oDirmngrProgram, "dirmngr-program", 2 , "@" },
{ oFakedSystemTime, "faked-system-time", 4, "@" }, /* (epoch time) */
{ oNoBatch, "no-batch", 0, "@" },
{ oWithColons, "with-colons", 0, "@"},
{ oWithKeyData,"with-key-data", 0, "@"},
{ aListKeys, "list-key", 0, "@" }, /* alias */
{ aListSigs, "list-sig", 0, "@" }, /* alias */
{ aListSigs, "check-sig",0, "@" }, /* alias */
{ oSkipVerify, "skip-verify",0, "@" },
{ oCompressKeys, "compress-keys",0, "@"},
{ oCompressSigs, "compress-sigs",0, "@"},
{ oAlwaysTrust, "always-trust", 0, "@"},
{ oNoVersion, "no-version", 0, "@"},
{ oLockOnce, "lock-once", 0, "@" },
{ oLockMultiple, "lock-multiple", 0, "@" },
{ oLockNever, "lock-never", 0, "@" },
{ oLoggerFD, "logger-fd",1, "@" },
{ oWithFingerprint, "with-fingerprint", 0, "@" },
{ oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
{ oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
{ oHonorHttpProxy,"honor-http-proxy", 0, "@" },
{ oListOnly, "list-only", 0, "@"},
{ oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
{ oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
{0} };
int gpgsm_errors_seen = 0;
/* It is possible that we are currentlu running under setuid permissions */
static int maybe_setuid = 1;
/* Option --enable-special-filenames */
static int allow_special_filenames;
static char *build_list (const char *text,
const char *(*mapf)(int), int (*chkf)(int));
static void set_cmd (enum cmd_and_opt_values *ret_cmd,
enum cmd_and_opt_values new_cmd );
static int check_special_filename (const char *fname);
static int open_read (const char *filename);
static FILE *open_fwrite (const char *filename);
static int
our_pk_test_algo (int algo)
{
return 1;
}
static int
our_cipher_test_algo (int algo)
{
return 1;
}
static int
our_md_test_algo (int algo)
{
return 1;
}
static const char *
my_strusage( int level )
{
static char *digests, *pubkeys, *ciphers;
const char *p;
switch (level)
{
case 11: p = "gpgsm (GnuPG)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
break;
case 1:
case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
break;
case 41:
p = _("Syntax: gpgsm [options] [files]\n"
"sign, check, encrypt or decrypt using the S/MIME protocol\n"
"default operation depends on the input data\n");
break;
case 31: p = "\nHome: "; break;
case 32: p = opt.homedir; break;
case 33: p = _("\nSupported algorithms:\n"); break;
case 34:
if (!ciphers)
ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
our_cipher_test_algo );
p = ciphers;
break;
case 35:
if (!pubkeys)
pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
our_pk_test_algo );
p = pubkeys;
break;
case 36:
if (!digests)
digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
p = digests;
break;
default: p = NULL; break;
}
return p;
}
static char *
build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
{
int i;
size_t n=strlen(text)+2;
char *list, *p;
if (maybe_setuid) {
gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
}
for (i=1; i < 110; i++ )
if (!chkf(i))
n += strlen(mapf(i)) + 2;
list = xmalloc (21 + n);
*list = 0;
for (p=NULL, i=1; i < 110; i++)
{
if (!chkf(i))
{
if( !p )
p = stpcpy (list, text );
else
p = stpcpy (p, ", ");
p = stpcpy (p, mapf(i) );
}
}
if (p)
p = stpcpy(p, "\n" );
return list;
}
static void
i18n_init(void)
{
#ifdef USE_SIMPLE_GETTEXT
set_gettext_file (PACKAGE);
#else
# ifdef ENABLE_NLS
# ifdef HAVE_LC_MESSAGES
setlocale (LC_TIME, "");
setlocale (LC_MESSAGES, "");
# else
setlocale (LC_ALL, "" );
# endif
bindtextdomain (PACKAGE, GNUPG_LOCALEDIR);
textdomain (PACKAGE);
# endif
#endif
}
static void
wrong_args (const char *text)
{
fputs (_("usage: gpgsm [options] "), stderr);
fputs (text, stderr);
putc ('\n', stderr);
gpgsm_exit (2);
}
static void
set_debug(void)
{
if (opt.debug & DBG_MPI_VALUE)
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
if (opt.debug & DBG_CRYPTO_VALUE )
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
}
static void
set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
{
enum cmd_and_opt_values cmd = *ret_cmd;
if (!cmd || cmd == new_cmd)
cmd = new_cmd;
else if ( cmd == aSign && new_cmd == aEncr )
cmd = aSignEncr;
else if ( cmd == aEncr && new_cmd == aSign )
cmd = aSignEncr;
else if ( (cmd == aSign && new_cmd == aClearsign)
|| (cmd == aClearsign && new_cmd == aSign) )
cmd = aClearsign;
else
{
log_error(_("conflicting commands\n"));
gpgsm_exit(2);
}
*ret_cmd = cmd;
}
int
main ( int argc, char **argv)
{
ARGPARSE_ARGS pargs;
int orig_argc;
char **orig_argv;
const char *fname;
/* char *username;*/
int may_coredump;
STRLIST sl, remusr= NULL, locusr=NULL;
STRLIST nrings=NULL;
int detached_sig = 0;
FILE *configfp = NULL;
char *configname = NULL;
unsigned configlineno;
int parse_debug = 0;
int default_config =1;
int default_keyring = 1;
char *logfile = NULL;
int greeting = 0;
int nogreeting = 0;
int debug_wait = 0;
int use_random_seed = 1;
int with_fpr = 0;
char *def_digest_string = NULL;
enum cmd_and_opt_values cmd = 0;
struct server_control_s ctrl;
CERTLIST recplist = NULL;
/* trap_unaligned ();*/
set_strusage (my_strusage);
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
/* Please note that we may running SUID(ROOT), so be very CAREFUL
when adding any stuff between here and the call to secmem_init()
somewhere after the option parsing */
log_set_prefix ("gpgsm", 1);
/* check that the libraries are suitable. Do it here because the
option parse may need services of the library */
if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
{
log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
}
if (!ksba_check_version (NEED_LIBKSBA_VERSION) )
{
log_fatal( _("libksba is too old (need %s, have %s)\n"),
NEED_LIBKSBA_VERSION, ksba_check_version (NULL) );
}
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
may_coredump = disable_core_dumps ();
/* Fixme: init_signals();*/
create_dotlock (NULL); /* register locking cleanup */
i18n_init();
opt.def_cipher_algoid = "1.2.840.113549.3.7"; /*des-EDE3-CBC*/
#ifdef __MINGW32__
opt.homedir = read_w32_registry_string ( NULL,
"Software\\GNU\\GnuPG", "HomeDir" );
#else
opt.homedir = getenv ("GNUPGHOME");
#endif
if (!opt.homedir || !*opt.homedir )
opt.homedir = GNUPG_DEFAULT_HOMEDIR;
/* first check whether we have a config file on the commandline */
orig_argc = argc;
orig_argv = argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
while (arg_parse( &pargs, opts))
{
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
parse_debug++;
else if (pargs.r_opt == oOptions)
{ /* yes there is one, so we do not try the default one but
read the config file when it is encountered at the
commandline */
default_config = 0;
}
else if (pargs.r_opt == oNoOptions)
default_config = 0; /* --no-options */
else if (pargs.r_opt == oHomedir)
opt.homedir = pargs.r.ret_str;
}
/* initialize the secure memory. */
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
maybe_setuid = 0;
/*
Now we are now working under our real uid
*/
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
/* Setup a default control structure for command line mode */
memset (&ctrl, 0, sizeof ctrl);
gpgsm_init_default_ctrl (&ctrl);
ctrl.no_server = 1;
ctrl.status_fd = -1; /* not status output */
ctrl.autodetect_encoding = 1;
/* set the default option file */
if (default_config )
configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
/* cet the default policy file */
opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
argc = orig_argc;
argv = orig_argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags = 1; /* do not remove the args */
next_pass:
if (configname) {
configlineno = 0;
configfp = fopen (configname, "r");
if (!configfp)
{
if (default_config)
{
if (parse_debug)
log_info (_("NOTE: no default option file `%s'\n"), configname);
}
else
{
log_error (_("option file `%s': %s\n"), configname, strerror(errno));
gpgsm_exit(2);
}
xfree(configname);
configname = NULL;
}
if (parse_debug && configname)
log_info (_("reading options from `%s'\n"), configname);
default_config = 0;
}
while (optfile_parse (configfp, configname, &configlineno, &pargs, opts))
{
switch (pargs.r_opt)
{
case aServer:
opt.batch = 1;
set_cmd (&cmd, aServer);
break;
case aCheckKeys: set_cmd (&cmd, aCheckKeys); break;
case aImport: set_cmd (&cmd, aImport); break;
case aSendKeys: set_cmd (&cmd, aSendKeys); break;
case aRecvKeys: set_cmd (&cmd, aRecvKeys); break;
case aExport: set_cmd (&cmd, aExport); break;
case aListKeys: set_cmd (&cmd, aListKeys); break;
case aListExternalKeys: set_cmd (&cmd, aListExternalKeys); break;
case aListSecretKeys: set_cmd (&cmd, aListSecretKeys); break;
case aListSigs: set_cmd (&cmd, aListSigs); break;
case aLearnCard: set_cmd (&cmd, aLearnCard); break;
case aDeleteKey:
set_cmd (&cmd, aDeleteKey);
- greeting=1;
+ /*greeting=1;*/
break;
case aDetachedSign:
detached_sig = 1;
set_cmd (&cmd, aSign );
break;
case aSym: set_cmd (&cmd, aSym); break;
case aDecrypt: set_cmd (&cmd, aDecrypt); break;
case aEncr: set_cmd (&cmd, aEncr); break;
case aSign: set_cmd (&cmd, aSign ); break;
case aKeygen: set_cmd (&cmd, aKeygen); greeting=1; break;
case aClearsign: set_cmd (&cmd, aClearsign); break;
case aVerify: set_cmd (&cmd, aVerify); break;
/* output encoding selection */
case oArmor:
ctrl.create_pem = 1;
break;
case oBase64:
ctrl.create_pem = 0;
ctrl.create_base64 = 1;
break;
case oNoArmor:
ctrl.create_pem = 0;
ctrl.create_base64 = 0;
break;
/* Input encoding selection */
case oAssumeArmor:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 1;
ctrl.is_base64 = 0;
break;
case oAssumeBase64:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 0;
ctrl.is_base64 = 1;
break;
case oAssumeBinary:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 0;
ctrl.is_base64 = 0;
break;
case oDisableCRLChecks:
opt.no_crl_check = 1;
break;
case oEnableCRLChecks:
opt.no_crl_check = 0;
break;
case oIncludeCerts: ctrl.include_certs = pargs.r.ret_int; break;
case oPolicyFile:
xfree (opt.policy_file);
if (*pargs.r.ret_str)
opt.policy_file = xstrdup (pargs.r.ret_str);
else
opt.policy_file = NULL;
break;
case oDisablePolicyChecks:
opt.no_policy_check = 1;
break;
case oEnablePolicyChecks:
opt.no_policy_check = 0;
break;
case oAutoIssuerKeyRetrieve:
opt.auto_issuer_key_retrieve = 1;
break;
case oOutput: opt.outfile = pargs.r.ret_str; break;
case oQuiet: opt.quiet = 1; break;
case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
case oDryRun: opt.dry_run = 1; break;
case oVerbose:
opt.verbose++;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
break;
case oNoVerbose:
opt.verbose = 0;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
break;
case oLogFile: logfile = pargs.r.ret_str; break;
case oBatch:
opt.batch = 1;
greeting = 0;
break;
case oNoBatch: opt.batch = 0; break;
case oAnswerYes: opt.answer_yes = 1; break;
case oAnswerNo: opt.answer_no = 1; break;
case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
case oDebug: opt.debug |= pargs.r.ret_ulong; break;
case oDebugAll: opt.debug = ~0; break;
case oDebugWait: debug_wait = pargs.r.ret_int; break;
case oDebugNoPathValidation: opt.no_path_validation = 1; break;
case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
case oWithFingerprint:
with_fpr=1; /*fall thru*/
case oFingerprint:
opt.fingerprint++;
break;
case oOptions:
/* config files may not be nested (silently ignore them) */
if (!configfp)
{
xfree(configname);
configname = xstrdup (pargs.r.ret_str);
goto next_pass;
}
break;
case oNoOptions: break; /* no-options */
case oHomedir: opt.homedir = pargs.r.ret_str; break;
case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
case oDisplay: opt.display = xstrdup (pargs.r.ret_str); break;
case oTTYname: opt.ttyname = xstrdup (pargs.r.ret_str); break;
case oTTYtype: opt.ttytype = xstrdup (pargs.r.ret_str); break;
case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
case oFakedSystemTime:
gnupg_set_time ( (time_t)pargs.r.ret_ulong, 0);
break;
case oNoDefKeyring: default_keyring = 0; break;
case oNoGreeting: nogreeting = 1; break;
case oDefaultKey:
/* fixme:opt.def_secret_key = pargs.r.ret_str;*/
break;
case oDefRecipient:
if (*pargs.r.ret_str)
opt.def_recipient = xstrdup (pargs.r.ret_str);
break;
case oDefRecipientSelf:
xfree (opt.def_recipient);
opt.def_recipient = NULL;
opt.def_recipient_self = 1;
break;
case oNoDefRecipient:
xfree (opt.def_recipient);
opt.def_recipient = NULL;
opt.def_recipient_self = 0;
break;
case oWithKeyData: opt.with_key_data=1; /* fall thru */
case oWithColons: ctrl.with_colons = 1; break;
case oSkipVerify: opt.skip_verify=1; break;
case oNoEncryptTo: /*fixme: opt.no_encrypt_to = 1;*/ break;
case oEncryptTo: /* store the recipient in the second list */
sl = add_to_strlist (&remusr, pargs.r.ret_str);
sl->flags = 1;
break;
case oRecipient: /* store the recipient */
add_to_strlist ( &remusr, pargs.r.ret_str);
break;
case oTextmodeShort: /*fixme:opt.textmode = 2;*/ break;
case oTextmode: /*fixme:opt.textmode=1;*/ break;
case oUser: /* store the local users */
opt.local_user = pargs.r.ret_str;
add_to_strlist ( &locusr, pargs.r.ret_str);
break;
case oNoSecmemWarn:
gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
break;
case oCipherAlgo:
opt.def_cipher_algoid = pargs.r.ret_str;
break;
case oDisableCipherAlgo:
{
int algo = gcry_cipher_map_name (pargs.r.ret_str);
gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
}
break;
case oDisablePubkeyAlgo:
{
int algo = gcry_pk_map_name (pargs.r.ret_str);
gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
}
break;
case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
case oNoRandomSeedFile: use_random_seed = 0; break;
case oEnableSpecialFilenames: allow_special_filenames =1; break;
case aDummy:
break;
default:
pargs.err = configfp? 1:2;
break;
}
}
if (configfp)
{
fclose (configfp);
configfp = NULL;
xfree (configname);
configname = NULL;
goto next_pass;
}
xfree (configname);
configname = NULL;
if (log_get_errorcount(0))
gpgsm_exit(2);
if (nogreeting)
greeting = 0;
if (greeting)
{
fprintf(stderr, "%s %s; %s\n",
strusage(11), strusage(13), strusage(14) );
fprintf(stderr, "%s\n", strusage(15) );
}
# ifdef IS_DEVELOPMENT_VERSION
if (!opt.batch)
{
log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
log_info ("It is only intended for test purposes and should NOT be\n");
log_info ("used in a production environment or with production keys!\n");
}
# endif
if (may_coredump && !opt.quiet)
log_info (_("WARNING: program may create a core file!\n"));
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, 1|2|4);
}
if (gnupg_faked_time_p ())
{
log_info (_("WARNING: running with faked system time: "));
gpgsm_dump_time (gnupg_get_time ());
log_printf ("\n");
}
/*FIXME if (opt.batch) */
/* tty_batchmode (1); */
gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
set_debug ();
/* FIXME: should set filenames of libgcrypt explicitly
* gpg_opt_homedir = opt.homedir; */
/* must do this after dropping setuid, because the mapping functions
may try to load an module and we may have disabled an algorithm */
if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
|| !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
log_error (_("selected cipher algorithm is invalid\n"));
if (def_digest_string)
{
opt.def_digest_algo = gcry_md_map_name (def_digest_string);
xfree (def_digest_string);
def_digest_string = NULL;
if (our_md_test_algo(opt.def_digest_algo) )
log_error (_("selected digest algorithm is invalid\n"));
}
if (log_get_errorcount(0))
gpgsm_exit(2);
/* set the random seed file */
if (use_random_seed) {
char *p = make_filename (opt.homedir, "random_seed", NULL);
#if 0
#warning set_random_seed_file not yet available in Libgcrypt
set_random_seed_file(p);
#endif
xfree(p);
}
if (!cmd && opt.fingerprint && !with_fpr)
set_cmd (&cmd, aListKeys);
if (!nrings && default_keyring) /* add default keybox */
keydb_add_resource ("pubring.kbx", 0, 0);
for (sl = nrings; sl; sl = sl->next)
keydb_add_resource (sl->d, 0, 0);
FREE_STRLIST(nrings);
for (sl = remusr; sl; sl = sl->next)
{
int rc = gpgsm_add_to_certlist (&ctrl, sl->d, &recplist);
if (rc)
{
log_error (_("can't encrypt to `%s': %s\n"),
sl->d, gnupg_strerror (rc));
gpgsm_status2 (&ctrl, STATUS_INV_RECP,
rc == -1? "1":
rc == GNUPG_Ambiguous_Name? "2":
rc == GNUPG_Wrong_Key_Usage? "3":
rc == GNUPG_Certificate_Revoked? "4":
rc == GNUPG_Certificate_Expired? "5":
rc == GNUPG_No_CRL_Known? "6":
rc == GNUPG_CRL_Too_Old? "7":
rc == GNUPG_No_Policy_Match? "8":
"0",
sl->d, NULL);
}
}
if (log_get_errorcount(0))
gpgsm_exit(1); /* must stop for invalid recipients */
fname = argc? *argv : NULL;
switch (cmd)
{
case aServer:
if (debug_wait)
{
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
sleep (debug_wait);
log_debug ("... okay\n");
}
gpgsm_server ();
break;
case aEncr: /* encrypt the given file */
if (!argc)
gpgsm_encrypt (&ctrl, recplist, 0, stdout); /* from stdin */
else if (argc == 1)
gpgsm_encrypt (&ctrl, recplist, open_read (*argv), stdout); /* from file */
else
wrong_args (_("--encrypt [datafile]"));
break;
case aSign: /* sign the given file */
/* FIXME: W we don't handle --output yet. We should also allow
to concatenate multiple files for signing because that is
what gpg does.*/
if (!argc)
gpgsm_sign (&ctrl, 0, detached_sig, stdout); /* create from stdin */
else if (argc == 1)
gpgsm_sign (&ctrl, open_read (*argv),
detached_sig, stdout); /* from file */
else
wrong_args (_("--sign [datafile]"));
break;
#if 0
sl = NULL;
if (detached_sig)
{ /* sign all files */
for (; argc; argc--, argv++ )
add_to_strlist ( &sl, *argv );
}
else
{
if (argc > 1 )
wrong_args (_("--sign [filename]"));
if (argc)
{
sl = xcalloc (1, sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
}
if ( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
log_error ("signing failed: %s\n", gpg_errstr(rc) );
free_strlist(sl);
#endif
break;
case aSignEncr: /* sign and encrypt the given file */
log_error ("this command has not yet been implemented\n");
#if 0
if (argc > 1)
wrong_args(_("--sign --encrypt [filename]"));
if (argc)
{
sl = xcalloc( 1, sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
else
sl = NULL;
if ( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
log_error ("%s: sign+encrypt failed: %s\n",
print_fname_stdin(fname), gpg_errstr(rc) );
free_strlist(sl);
#endif
break;
case aClearsign: /* make a clearsig */
log_error ("this command has not yet been implemented\n");
#if 0
if (argc > 1)
wrong_args (_("--clearsign [filename]"));
if ( (rc = clearsign_file(fname, locusr, NULL)) )
log_error ("%s: clearsign failed: %s\n",
print_fname_stdin(fname), gpg_errstr(rc) );
#endif
break;
case aVerify:
{
FILE *fp = NULL;
if (argc == 2 && opt.outfile)
log_info ("option --output ignored for a detached signature\n");
else if (opt.outfile)
fp = open_fwrite (opt.outfile);
if (!argc)
gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
else if (argc == 1)
gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
else if (argc == 2) /* detached signature (sig, detached) */
gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
else
wrong_args (_("--verify [signature [detached_data]]"));
if (fp && fp != stdout)
fclose (fp);
}
break;
case aVerifyFiles:
log_error ("this command has not yet been implemented\n");
/* if ((rc = verify_files( argc, argv ))) */
/* log_error ("verify files failed: %s\n", gpg_errstr(rc) ); */
break;
case aDecrypt:
if (!argc)
gpgsm_decrypt (&ctrl, 0, stdout); /* from stdin */
else if (argc == 1)
gpgsm_decrypt (&ctrl, open_read (*argv), stdout); /* from file */
else
wrong_args (_("--decrypt [filename]"));
break;
case aDeleteKey:
- if (argc != 1)
- wrong_args(_("--delete-key user-id"));
- log_error ("this command has not yet been implemented\n");
-/* username = make_username (fname); */
-/* if( (rc = delete_key(username)) ) */
-/* log_error ("%s: delete key failed: %s\n", username, gpg_errstr(rc) ); */
-/* xfree(username); */
+ for (sl=NULL; argc; argc--, argv++)
+ add_to_strlist (&sl, *argv);
+ gpgsm_delete (&ctrl, sl);
+ free_strlist(sl);
break;
case aListSigs:
ctrl.with_chain = 1;
case aListKeys:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_list_keys (&ctrl, sl, stdout, (0 | (1<<6)));
free_strlist(sl);
break;
case aListExternalKeys:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_list_keys (&ctrl, sl, stdout, (0 | (1<<7)));
free_strlist(sl);
break;
case aListSecretKeys:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_list_keys (&ctrl, sl, stdout, (2 | (1<<6)));
free_strlist(sl);
break;
case aKeygen: /* generate a key */
log_error ("this function is not yet available from the commandline\n");
/* if (opt.batch) */
/* { */
/* if (argc > 1) */
/* wrong_args("--gen-key [parameterfile]"); */
/* generate_keypair (argc? *argv : NULL); */
/* } */
/* else */
/* { */
/* if (argc) */
/* wrong_args ("--gen-key"); */
/* generate_keypair(NULL); */
/* } */
break;
case aImport:
if (!argc)
gpgsm_import (&ctrl, 0);
else
{
for (; argc; argc--, argv++)
gpgsm_import (&ctrl, open_read (*argv));
}
break;
case aExport:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_export (&ctrl, sl, stdout);
free_strlist(sl);
break;
case aSendKeys:
case aRecvKeys:
log_error ("this command has not yet been implemented\n");
/* sl = NULL; */
/* for ( ; argc; argc--, argv++ ) */
/* add_to_strlist (&sl, *argv); */
/* if ( cmd == aSendKeys ) */
/* ldap_export (sl); */
/* else if (cmd == aRecvKeys ) */
/* ldap_import (sl); */
/* else */
/* export_pubkeys (sl, (cmd == aExport)); */
/* free_strlist (sl); */
break;
case aLearnCard:
if (argc)
wrong_args ("--learn-card");
else
{
int rc = gpgsm_agent_learn ();
if (rc)
log_error ("error learning card: %s\n", gnupg_strerror (rc));
}
break;
default:
log_error ("invalid command\n");
#if 0
if (argc > 1)
wrong_args(_("[filename]"));
/* Issue some output for the unix newbie */
if ( !fname && !opt.outfile && isatty( fileno(stdin) )
&& isatty (fileno(stdout) ) && isatty (fileno(stderr) ) )
log_info (_("Go ahead and type your message ...\n"));
if ( !(a = iobuf_open(fname)) )
log_error (_("can't open `%s'\n"), print_fname_stdin(fname));
else
{
if (!opt.no_armor)
iobuf_close(a);
}
#endif
break;
}
/* cleanup */
gpgsm_release_certlist (recplist);
FREE_STRLIST(remusr);
FREE_STRLIST(locusr);
gpgsm_exit(0);
return 8; /*NEVER REACHED*/
}
void
gpgsm_exit (int rc)
{
#if 0
#warning no update_random_seed_file
update_random_seed_file();
#endif
#if 0
/* at this time a bit annoying */
if (opt.debug & DBG_MEMSTAT_VALUE)
{
gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
}
if (opt.debug)
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
#endif
gcry_control (GCRYCTL_TERM_SECMEM );
rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
exit (rc);
}
void
gpgsm_init_default_ctrl (struct server_control_s *ctrl)
{
ctrl->include_certs = 1; /* only include the signer's cert */
}
/* Check whether the filename has the form "-&nnnn", where n is a
non-zero number. Returns this number or -1 if it is not the case. */
static int
check_special_filename (const char *fname)
{
if (allow_special_filenames
&& fname && *fname == '-' && fname[1] == '&' ) {
int i;
fname += 2;
for (i=0; isdigit (fname[i]); i++ )
;
if ( !fname[i] )
return atoi (fname);
}
return -1;
}
/* Open the FILENAME for read and return the filedescriptor. Stop
with an error message in case of problems. "-" denotes stdin and
if special filenames are allowed the given fd is opened instead. */
static int
open_read (const char *filename)
{
int fd;
if (filename[0] == '-' && !filename[1])
return 0; /* stdin */
fd = check_special_filename (filename);
if (fd != -1)
return fd;
fd = open (filename, O_RDONLY);
if (fd == -1)
{
log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
gpgsm_exit (2);
}
return fd;
}
/* Open FILENAME for fwrite and return the stream. Stop with an error
message in case of problems. "-" denotes stdout and if special
filenames are allowed the given fd is opened instead. Caller must
close the returned stream unless it is stdout. */
static FILE *
open_fwrite (const char *filename)
{
int fd;
FILE *fp;
if (filename[0] == '-' && !filename[1])
return stdout;
fd = check_special_filename (filename);
if (fd != -1)
{
fp = fdopen (dup (fd), "wb");
if (!fp)
{
log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
fp = fopen (filename, "wb");
if (!fp)
{
log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
diff --git a/sm/gpgsm.h b/sm/gpgsm.h
index efa98dee5..0d5294b44 100644
--- a/sm/gpgsm.h
+++ b/sm/gpgsm.h
@@ -1,253 +1,256 @@
/* gpgsm.h - Global definitions for GpgSM
* Copyright (C) 2001 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#ifndef GPGSM_H
#define GPGSM_H
#include <ksba.h>
#include "../common/util.h"
#include "../common/errors.h"
#define MAX_DIGEST_LEN 24
/* A large struct name "opt" to keep global flags */
struct {
unsigned int debug; /* debug flags (DBG_foo_VALUE) */
int verbose; /* verbosity level */
int quiet; /* be as quiet as possible */
int batch; /* run in batch mode, i.e w/o any user interaction */
int answer_yes; /* assume yes on most questions */
int answer_no; /* assume no on most questions */
int dry_run; /* don't change any persistent data */
const char *homedir; /* configuration directory name */
const char *agent_program;
char *display;
char *ttyname;
char *ttytype;
char *lc_ctype;
char *lc_messages;
const char *dirmngr_program;
char *outfile; /* name of output file */
int with_key_data;/* include raw key in the column delimted output */
int fingerprint; /* list fingerprints in all key listings */
int armor; /* force base64 armoring (see also ctrl.with_base64) */
int no_armor; /* don't try to figure out whether data is base64 armored*/
const char *def_cipher_algoid; /* cipher algorithm to use if
nothing else is specified */
int def_digest_algo; /* Ditto for hash algorithm */
int def_compress_algo; /* Ditto for compress algorithm */
char *def_recipient; /* userID of the default recipient */
int def_recipient_self; /* The default recipient is the default key */
char *local_user; /* NULL or argument to -u */
int always_trust; /* Trust the given keys even if there is no
valid certification path */
int skip_verify; /* do not check signatures on data */
int lock_once; /* Keep lock once they are set */
int ignore_time_conflict; /* Ignore certain time conflicts */
int no_crl_check; /* Don't do a CRL check */
char *policy_file; /* full pathname of policy file */
int no_policy_check; /* ignore certificate policies */
int no_path_validation; /* Bypass all cert path validity tests */
int auto_issuer_key_retrieve; /* try to retrieve a missing issuer key. */
} opt;
#define DBG_X509_VALUE 1 /* debug x.509 data reading/writing */
#define DBG_MPI_VALUE 2 /* debug mpi details */
#define DBG_CRYPTO_VALUE 4 /* debug low level crypto */
#define DBG_MEMORY_VALUE 32 /* debug memory allocation stuff */
#define DBG_CACHE_VALUE 64 /* debug the caching */
#define DBG_MEMSTAT_VALUE 128 /* show memory statistics */
#define DBG_HASHING_VALUE 512 /* debug hashing operations */
#define DBG_ASSUAN_VALUE 1024 /* debug assuan communication */
#define DBG_X509 (opt.debug & DBG_X509_VALUE)
#define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE)
#define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE)
#define DBG_CACHE (opt.debug & DBG_CACHE_VALUE)
#define DBG_HASHING (opt.debug & DBG_HASHING_VALUE)
#define DBG_ASSUAN (opt.debug & DBG_ASSUAN_VALUE)
struct server_local_s;
/* Note that the default values for this are set by
gpgsm_init_default_ctrl() */
struct server_control_s {
int no_server; /* we are not running under server control */
int status_fd; /* only for non-server mode */
struct server_local_s *server_local;
int with_colons; /* use column delimited output format */
int with_chain; /* include the certifying certs in a listing */
int autodetect_encoding; /* try to detect the input encoding */
int is_pem; /* Is in PEM format */
int is_base64; /* is in plain base-64 format */
int create_base64; /* Create base64 encoded output */
int create_pem; /* create PEM output */
const char *pem_name; /* PEM name to use */
int include_certs; /* -1 to send all certificates in the chain
along with a signature or the number of
certificates up the chain (0 = none, 1 = only
signer) */
};
typedef struct server_control_s *CTRL;
/* data structure used in base64.c */
typedef struct base64_context_s *Base64Context;
struct certlist_s {
struct certlist_s *next;
KsbaCert cert;
};
typedef struct certlist_s *CERTLIST;
/*-- gpgsm.c --*/
void gpgsm_exit (int rc);
void gpgsm_init_default_ctrl (struct server_control_s *ctrl);
/*-- server.c --*/
void gpgsm_server (void);
void gpgsm_status (CTRL ctrl, int no, const char *text);
void gpgsm_status2 (CTRL ctrl, int no, ...);
/*-- fingerprint --*/
char *gpgsm_get_fingerprint (KsbaCert cert, int algo, char *array, int *r_len);
char *gpgsm_get_fingerprint_string (KsbaCert cert, int algo);
char *gpgsm_get_fingerprint_hexstring (KsbaCert cert, int algo);
char *gpgsm_get_keygrip (KsbaCert cert, char *array);
char *gpgsm_get_keygrip_hexstring (KsbaCert cert);
char *gpgsm_get_certid (KsbaCert cert);
/*-- base64.c --*/
int gpgsm_create_reader (Base64Context *ctx,
CTRL ctrl, FILE *fp, KsbaReader *r_reader);
void gpgsm_destroy_reader (Base64Context ctx);
int gpgsm_create_writer (Base64Context *ctx,
CTRL ctrl, FILE *fp, KsbaWriter *r_writer);
int gpgsm_finish_writer (Base64Context ctx);
void gpgsm_destroy_writer (Base64Context ctx);
/*-- certdump.c --*/
void gpgsm_print_serial (FILE *fp, KsbaConstSexp p);
void gpgsm_print_time (FILE *fp, time_t t);
void gpgsm_print_name (FILE *fp, const char *string);
void gpgsm_dump_cert (const char *text, KsbaCert cert);
void gpgsm_dump_serial (KsbaConstSexp p);
void gpgsm_dump_time (time_t t);
void gpgsm_dump_string (const char *string);
/*-- certcheck.c --*/
int gpgsm_check_cert_sig (KsbaCert issuer_cert, KsbaCert cert);
int gpgsm_check_cms_signature (KsbaCert cert, KsbaConstSexp sigval,
GCRY_MD_HD md, int hash_algo);
/* fixme: move create functions to another file */
int gpgsm_create_cms_signature (KsbaCert cert, GCRY_MD_HD md, int mdalgo,
char **r_sigval);
/*-- certpath.c --*/
int gpgsm_walk_cert_chain (KsbaCert start, KsbaCert *r_next);
int gpgsm_is_root_cert (KsbaCert cert);
int gpgsm_validate_path (CTRL ctrl, KsbaCert cert, time_t *r_exptime);
int gpgsm_basic_cert_check (KsbaCert cert);
/*-- certlist.c --*/
int gpgsm_cert_use_sign_p (KsbaCert cert);
int gpgsm_cert_use_encrypt_p (KsbaCert cert);
int gpgsm_cert_use_verify_p (KsbaCert cert);
int gpgsm_cert_use_decrypt_p (KsbaCert cert);
int gpgsm_cert_use_cert_p (KsbaCert cert);
int gpgsm_add_to_certlist (CTRL ctrl, const char *name, CERTLIST *listaddr);
void gpgsm_release_certlist (CERTLIST list);
int gpgsm_find_cert (const char *name, KsbaCert *r_cert);
/*-- keylist.c --*/
void gpgsm_list_keys (CTRL ctrl, STRLIST names, FILE *fp, unsigned int mode);
/*-- import.c --*/
int gpgsm_import (CTRL ctrl, int in_fd);
/*-- export.c --*/
void gpgsm_export (CTRL ctrl, STRLIST names, FILE *fp);
+/*-- delete.c --*/
+int gpgsm_delete (CTRL ctrl, STRLIST names);
+
/*-- verify.c --*/
int gpgsm_verify (CTRL ctrl, int in_fd, int data_fd, FILE *out_fp);
/*-- sign.c --*/
int gpgsm_get_default_cert (KsbaCert *r_cert);
int gpgsm_sign (CTRL ctrl, int data_fd, int detached, FILE *out_fp);
/*-- encrypt.c --*/
int gpgsm_encrypt (CTRL ctrl, CERTLIST recplist, int in_fd, FILE *out_fp);
/*-- decrypt.c --*/
int gpgsm_decrypt (CTRL ctrl, int in_fd, FILE *out_fp);
/*-- certreqgen.c --*/
int gpgsm_genkey (CTRL ctrl, int in_fd, FILE *out_fp);
/*-- call-agent.c --*/
int gpgsm_agent_pksign (const char *keygrip,
unsigned char *digest,
size_t digestlen,
int digestalgo,
char **r_buf, size_t *r_buflen);
int gpgsm_agent_pkdecrypt (const char *keygrip,
KsbaConstSexp ciphertext,
char **r_buf, size_t *r_buflen);
int gpgsm_agent_genkey (KsbaConstSexp keyparms, KsbaSexp *r_pubkey);
int gpgsm_agent_istrusted (KsbaCert cert);
int gpgsm_agent_havekey (const char *hexkeygrip);
int gpgsm_agent_marktrusted (KsbaCert cert);
int gpgsm_agent_learn (void);
/*-- call-dirmngr.c --*/
int gpgsm_dirmngr_isvalid (KsbaCert cert);
int gpgsm_dirmngr_lookup (CTRL ctrl, STRLIST names,
void (*cb)(void*, KsbaCert), void *cb_value);
#endif /*GPGSM_H*/
diff --git a/sm/server.c b/sm/server.c
index 5f490b5a9..0e30ae873 100644
--- a/sm/server.c
+++ b/sm/server.c
@@ -1,962 +1,1006 @@
/* server.c - Server mode and main entry point
* Copyright (C) 2001, 2002 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <unistd.h>
#include "gpgsm.h"
#include "../assuan/assuan.h"
#define set_error(e,t) assuan_set_error (ctx, ASSUAN_ ## e, (t))
/* The filepointer for status message used in non-server mode */
static FILE *statusfp;
/* Data used to assuciate an Assuan context with local server data */
struct server_local_s {
ASSUAN_CONTEXT assuan_ctx;
int message_fd;
int list_internal;
int list_external;
CERTLIST recplist;
};
/* note, that it is sufficient to allocate the target string D as
long as the source string S, i.e.: strlen(s)+1; */
static void
strcpy_escaped_plus (char *d, const unsigned 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)));
}
static void
close_message_fd (CTRL ctrl)
{
if (ctrl->server_local->message_fd != -1)
{
close (ctrl->server_local->message_fd);
ctrl->server_local->message_fd = -1;
}
}
static int
option_handler (ASSUAN_CONTEXT ctx, const char *key, const char *value)
{
CTRL ctrl = assuan_get_pointer (ctx);
if (!strcmp (key, "include-certs"))
{
int i = *value? atoi (value) : -1;
if (ctrl->include_certs < -2)
return ASSUAN_Parameter_Error;
ctrl->include_certs = i;
}
else if (!strcmp (key, "display"))
{
if (opt.display)
free (opt.display);
opt.display = strdup (value);
if (!opt.display)
return ASSUAN_Out_Of_Core;
}
else if (!strcmp (key, "ttyname"))
{
if (opt.ttyname)
free (opt.ttyname);
opt.ttyname = strdup (value);
if (!opt.ttyname)
return ASSUAN_Out_Of_Core;
}
else if (!strcmp (key, "ttytype"))
{
if (opt.ttytype)
free (opt.ttytype);
opt.ttytype = strdup (value);
if (!opt.ttytype)
return ASSUAN_Out_Of_Core;
}
else if (!strcmp (key, "lc-ctype"))
{
if (opt.lc_ctype)
free (opt.lc_ctype);
opt.lc_ctype = strdup (value);
if (!opt.lc_ctype)
return ASSUAN_Out_Of_Core;
}
else if (!strcmp (key, "lc-messages"))
{
if (opt.lc_messages)
free (opt.lc_messages);
opt.lc_messages = strdup (value);
if (!opt.lc_messages)
return ASSUAN_Out_Of_Core;
}
else if (!strcmp (key, "list-mode"))
{
int i = *value? atoi (value) : 0;
if (!i || i == 1) /* default and mode 1 */
{
ctrl->server_local->list_internal = 1;
ctrl->server_local->list_external = 0;
}
else if (i == 2)
{
ctrl->server_local->list_internal = 0;
ctrl->server_local->list_external = 1;
}
else if (i == 3)
{
ctrl->server_local->list_internal = 1;
ctrl->server_local->list_external = 1;
}
else
return ASSUAN_Parameter_Error;
}
else
return ASSUAN_Invalid_Option;
return 0;
}
static void
reset_notify (ASSUAN_CONTEXT ctx)
{
CTRL ctrl = assuan_get_pointer (ctx);
gpgsm_release_certlist (ctrl->server_local->recplist);
ctrl->server_local->recplist = NULL;
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
}
static void
input_notify (ASSUAN_CONTEXT ctx, const char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
ctrl->autodetect_encoding = 0;
ctrl->is_pem = 0;
ctrl->is_base64 = 0;
if (strstr (line, "--armor"))
ctrl->is_pem = 1;
else if (strstr (line, "--base64"))
ctrl->is_base64 = 1;
else if (strstr (line, "--binary"))
;
else
ctrl->autodetect_encoding = 1;
}
static void
output_notify (ASSUAN_CONTEXT ctx, const char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
ctrl->create_pem = 0;
ctrl->create_base64 = 0;
if (strstr (line, "--armor"))
ctrl->create_pem = 1;
else if (strstr (line, "--base64"))
ctrl->create_base64 = 1; /* just the raw output */
}
/* RECIPIENT <userID>
Set the recipient for the encryption. <userID> should be the
internal representation of the key; the server may accept any other
way of specification [we will support this]. If this is a valid and
trusted recipient the server does respond with OK, otherwise the
return is an ERR with the reason why the recipient can't be used,
the encryption will then not be done for this recipient. IF the
policy is not to encrypt at all if not all recipients are valid, the
client has to take care of this. All RECIPIENT commands are
cumulative until a RESET or an successful ENCRYPT command. */
static int
cmd_recipient (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int rc;
rc = gpgsm_add_to_certlist (ctrl, line, &ctrl->server_local->recplist);
if (rc)
gpgsm_status2 (ctrl, STATUS_INV_RECP,
rc == -1? "1":
rc == GNUPG_Ambiguous_Name? "2":
rc == GNUPG_Wrong_Key_Usage? "3":
rc == GNUPG_Certificate_Revoked? "4":
rc == GNUPG_Certificate_Expired? "5":
rc == GNUPG_No_CRL_Known? "6":
rc == GNUPG_CRL_Too_Old? "7":
rc == GNUPG_No_Policy_Match? "8":
"0",
line, NULL);
return map_to_assuan_status (rc);
}
/* ENCRYPT
Do the actual encryption process. Takes the plaintext from the INPUT
command, writes to the ciphertext to the file descriptor set with
the OUTPUT command, take the recipients form all the recipients set
so far. If this command fails the clients should try to delete all
output currently done or otherwise mark it as invalid. GPGSM does
ensure that there won't be any security problem with leftover data
on the output in this case.
This command should in general not fail, as all necessary checks
have been done while setting the recipients. The input and output
pipes are closed. */
static int
cmd_encrypt (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int inp_fd, out_fd;
FILE *out_fp;
int rc;
inp_fd = assuan_get_input_fd (ctx);
if (inp_fd == -1)
return set_error (No_Input, NULL);
out_fd = assuan_get_output_fd (ctx);
if (out_fd == -1)
return set_error (No_Output, NULL);
out_fp = fdopen ( dup(out_fd), "w");
if (!out_fp)
return set_error (General_Error, "fdopen() failed");
rc = gpgsm_encrypt (assuan_get_pointer (ctx),
ctrl->server_local->recplist,
inp_fd, out_fp);
fclose (out_fp);
gpgsm_release_certlist (ctrl->server_local->recplist);
ctrl->server_local->recplist = NULL;
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
/* DECRYPT
This performs the decrypt operation after doing some check on the
internal state. (e.g. that only needed data has been set). Because
it utilizes the GPG-Agent for the session key decryption, there is
no need to ask the client for a protecting passphrase - GpgAgent
does take care of this by requesting this from the user. */
static int
cmd_decrypt (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int inp_fd, out_fd;
FILE *out_fp;
int rc;
inp_fd = assuan_get_input_fd (ctx);
if (inp_fd == -1)
return set_error (No_Input, NULL);
out_fd = assuan_get_output_fd (ctx);
if (out_fd == -1)
return set_error (No_Output, NULL);
out_fp = fdopen ( dup(out_fd), "w");
if (!out_fp)
return set_error (General_Error, "fdopen() failed");
rc = gpgsm_decrypt (ctrl, inp_fd, out_fp);
fclose (out_fp);
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
/* VERIFY
This does a verify operation on the message send to the input-FD.
The result is written out using status lines. If an output FD was
given, the signed text will be written to that.
If the signature is a detached one, the server will inquire about
the signed material and the client must provide it.
*/
static int
cmd_verify (ASSUAN_CONTEXT ctx, char *line)
{
int rc;
CTRL ctrl = assuan_get_pointer (ctx);
int fd = assuan_get_input_fd (ctx);
int out_fd = assuan_get_output_fd (ctx);
FILE *out_fp = NULL;
if (fd == -1)
return set_error (No_Input, NULL);
if (out_fd != -1)
{
out_fp = fdopen ( dup(out_fd), "w");
if (!out_fp)
return set_error (General_Error, "fdopen() failed");
}
rc = gpgsm_verify (assuan_get_pointer (ctx), fd,
ctrl->server_local->message_fd, out_fp);
if (out_fp)
fclose (out_fp);
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
/* SIGN [--detached]
Sign the data set with the INPUT command and write it to the sink
set by OUTPUT. With "--detached" specified, a detached signature is
created (surprise). */
static int
cmd_sign (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int inp_fd, out_fd;
FILE *out_fp;
int detached;
int rc;
inp_fd = assuan_get_input_fd (ctx);
if (inp_fd == -1)
return set_error (No_Input, NULL);
out_fd = assuan_get_output_fd (ctx);
if (out_fd == -1)
return set_error (No_Output, NULL);
detached = has_option (line, "--detached");
out_fp = fdopen ( dup(out_fd), "w");
if (!out_fp)
return set_error (General_Error, "fdopen() failed");
rc = gpgsm_sign (assuan_get_pointer (ctx), inp_fd, detached, out_fp);
fclose (out_fp);
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
/* IMPORT
Import the certificates read form the input-fd, return status
message for each imported one. The import checks the validity of
the certificate but not of the path. It is possible to import
expired certificates. */
static int
cmd_import (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int rc;
int fd = assuan_get_input_fd (ctx);
if (fd == -1)
return set_error (No_Input, NULL);
rc = gpgsm_import (assuan_get_pointer (ctx), fd);
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
static int
cmd_export (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int fd = assuan_get_output_fd (ctx);
FILE *out_fp;
char *p;
STRLIST list, sl;
if (fd == -1)
return set_error (No_Output, NULL);
/* break the line down into an STRLIST */
list = NULL;
for (p=line; *p; line = p)
{
while (*p && *p != ' ')
p++;
if (*p)
*p++ = 0;
if (*line)
{
sl = xtrymalloc (sizeof *sl + strlen (line));
if (!sl)
{
free_strlist (list);
return ASSUAN_Out_Of_Core;
}
sl->flags = 0;
strcpy_escaped_plus (sl->d, line);
sl->next = list;
list = sl;
}
}
out_fp = fdopen ( dup(fd), "w");
if (!out_fp)
{
free_strlist (list);
return set_error (General_Error, "fdopen() failed");
}
gpgsm_export (ctrl, list, out_fp);
fclose (out_fp);
free_strlist (list);
/* close and reset the fd */
close_message_fd (ctrl);
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return 0;
}
+static int
+cmd_delkeys (ASSUAN_CONTEXT ctx, char *line)
+{
+ CTRL ctrl = assuan_get_pointer (ctx);
+ char *p;
+ STRLIST list, sl;
+ int rc;
+
+ /* break the line down into an STRLIST */
+ list = NULL;
+ for (p=line; *p; line = p)
+ {
+ while (*p && *p != ' ')
+ p++;
+ if (*p)
+ *p++ = 0;
+ if (*line)
+ {
+ sl = xtrymalloc (sizeof *sl + strlen (line));
+ if (!sl)
+ {
+ free_strlist (list);
+ return ASSUAN_Out_Of_Core;
+ }
+ sl->flags = 0;
+ strcpy_escaped_plus (sl->d, line);
+ sl->next = list;
+ list = sl;
+ }
+ }
+
+ rc = gpgsm_delete (ctrl, list);
+ free_strlist (list);
+
+ /* close and reset the fd */
+ close_message_fd (ctrl);
+ assuan_close_input_fd (ctx);
+ assuan_close_output_fd (ctx);
+
+ return map_to_assuan_status (rc);
+}
+
+
/* MESSAGE FD=<n>
Set the file descriptor to read a message which is used with
detached signatures */
static int
cmd_message (ASSUAN_CONTEXT ctx, char *line)
{
char *endp;
int fd;
CTRL ctrl = assuan_get_pointer (ctx);
if (strncmp (line, "FD=", 3))
return set_error (Syntax_Error, "FD=<n> expected");
line += 3;
if (!digitp (line))
return set_error (Syntax_Error, "number required");
fd = strtoul (line, &endp, 10);
if (*endp)
return set_error (Syntax_Error, "garbage found");
if (fd == -1)
return set_error (No_Input, NULL);
ctrl->server_local->message_fd = fd;
return 0;
}
static int
do_listkeys (ASSUAN_CONTEXT ctx, char *line, int mode)
{
CTRL ctrl = assuan_get_pointer (ctx);
FILE *fp = assuan_get_data_fp (ctx);
char *p;
STRLIST list, sl;
unsigned int listmode;
if (!fp)
return set_error (General_Error, "no data stream");
/* break the line down into an STRLIST */
list = NULL;
for (p=line; *p; line = p)
{
while (*p && *p != ' ')
p++;
if (*p)
*p++ = 0;
if (*line)
{
sl = xtrymalloc (sizeof *sl + strlen (line));
if (!sl)
{
free_strlist (list);
return ASSUAN_Out_Of_Core;
}
sl->flags = 0;
strcpy_escaped_plus (sl->d, line);
sl->next = list;
list = sl;
}
}
ctrl->with_colons = 1;
listmode = mode;
if (ctrl->server_local->list_internal)
listmode |= (1<<6);
if (ctrl->server_local->list_external)
listmode |= (1<<7);
gpgsm_list_keys (assuan_get_pointer (ctx), list, fp, listmode);
free_strlist (list);
return 0;
}
static int
cmd_listkeys (ASSUAN_CONTEXT ctx, char *line)
{
return do_listkeys (ctx, line, 3);
}
static int
cmd_listsecretkeys (ASSUAN_CONTEXT ctx, char *line)
{
return do_listkeys (ctx, line, 2);
}
/* GENKEY
Read the parameters in native format from the input fd and write a
certificate request to the output.
*/
static int
cmd_genkey (ASSUAN_CONTEXT ctx, char *line)
{
CTRL ctrl = assuan_get_pointer (ctx);
int inp_fd, out_fd;
FILE *out_fp;
int rc;
inp_fd = assuan_get_input_fd (ctx);
if (inp_fd == -1)
return set_error (No_Input, NULL);
out_fd = assuan_get_output_fd (ctx);
if (out_fd == -1)
return set_error (No_Output, NULL);
out_fp = fdopen ( dup(out_fd), "w");
if (!out_fp)
return set_error (General_Error, "fdopen() failed");
rc = gpgsm_genkey (ctrl, inp_fd, out_fp);
fclose (out_fp);
/* close and reset the fds */
assuan_close_input_fd (ctx);
assuan_close_output_fd (ctx);
return map_to_assuan_status (rc);
}
/* Tell the assuan library about our commands */
static int
register_commands (ASSUAN_CONTEXT ctx)
{
static struct {
const char *name;
int cmd_id;
int (*handler)(ASSUAN_CONTEXT, char *line);
} table[] = {
{ "RECIPIENT", 0, cmd_recipient },
{ "ENCRYPT", 0, cmd_encrypt },
{ "DECRYPT", 0, cmd_decrypt },
{ "VERIFY", 0, cmd_verify },
{ "SIGN", 0, cmd_sign },
{ "IMPORT", 0, cmd_import },
{ "EXPORT", 0, cmd_export },
{ "", ASSUAN_CMD_INPUT, NULL },
{ "", ASSUAN_CMD_OUTPUT, NULL },
{ "MESSAGE", 0, cmd_message },
{ "LISTKEYS", 0, cmd_listkeys },
{ "LISTSECRETKEYS", 0, cmd_listsecretkeys },
{ "GENKEY", 0, cmd_genkey },
+ { "DELKEYS", 0, cmd_delkeys },
{ NULL }
};
int i, j, rc;
for (i=j=0; table[i].name; i++)
{
rc = assuan_register_command (ctx,
table[i].cmd_id? table[i].cmd_id
: (ASSUAN_CMD_USER + j++),
table[i].name, table[i].handler);
if (rc)
return rc;
}
return 0;
}
/* Startup the server */
void
gpgsm_server (void)
{
int rc;
int filedes[2];
ASSUAN_CONTEXT ctx;
struct server_control_s ctrl;
memset (&ctrl, 0, sizeof ctrl);
gpgsm_init_default_ctrl (&ctrl);
/* For now we use a simple pipe based server so that we can work
from scripts. We will later add options to run as a daemon and
wait for requests on a Unix domain socket */
filedes[0] = 0;
filedes[1] = 1;
rc = assuan_init_pipe_server (&ctx, filedes);
if (rc)
{
log_error ("failed to initialize the server: %s\n",
assuan_strerror(rc));
gpgsm_exit (2);
}
rc = register_commands (ctx);
if (rc)
{
log_error ("failed to the register commands with Assuan: %s\n",
assuan_strerror(rc));
gpgsm_exit (2);
}
assuan_set_hello_line (ctx, "GNU Privacy Guard's S/M server ready");
assuan_register_reset_notify (ctx, reset_notify);
assuan_register_input_notify (ctx, input_notify);
assuan_register_output_notify (ctx, output_notify);
assuan_register_option_handler (ctx, option_handler);
assuan_set_pointer (ctx, &ctrl);
ctrl.server_local = xcalloc (1, sizeof *ctrl.server_local);
ctrl.server_local->assuan_ctx = ctx;
ctrl.server_local->message_fd = -1;
ctrl.server_local->list_internal = 1;
ctrl.server_local->list_external = 0;
if (DBG_ASSUAN)
assuan_set_log_stream (ctx, log_get_stream ());
for (;;)
{
rc = assuan_accept (ctx);
if (rc == -1)
{
break;
}
else if (rc)
{
log_info ("Assuan accept problem: %s\n", assuan_strerror (rc));
break;
}
rc = assuan_process (ctx);
if (rc)
{
log_info ("Assuan processing failed: %s\n", assuan_strerror (rc));
continue;
}
}
gpgsm_release_certlist (ctrl.server_local->recplist);
ctrl.server_local->recplist = NULL;
assuan_deinit_server (ctx);
}
static const char *
get_status_string ( int no )
{
const char *s;
switch (no)
{
case STATUS_ENTER : s = "ENTER"; break;
case STATUS_LEAVE : s = "LEAVE"; break;
case STATUS_ABORT : s = "ABORT"; break;
case STATUS_GOODSIG: s = "GOODSIG"; break;
case STATUS_SIGEXPIRED: s = "SIGEXPIRED"; break;
case STATUS_KEYREVOKED: s = "KEYREVOKED"; break;
case STATUS_BADSIG : s = "BADSIG"; break;
case STATUS_ERRSIG : s = "ERRSIG"; break;
case STATUS_BADARMOR : s = "BADARMOR"; break;
case STATUS_RSA_OR_IDEA : s= "RSA_OR_IDEA"; break;
case STATUS_TRUST_UNDEFINED: s = "TRUST_UNDEFINED"; break;
case STATUS_TRUST_NEVER : s = "TRUST_NEVER"; break;
case STATUS_TRUST_MARGINAL : s = "TRUST_MARGINAL"; break;
case STATUS_TRUST_FULLY : s = "TRUST_FULLY"; break;
case STATUS_TRUST_ULTIMATE : s = "TRUST_ULTIMATE"; break;
case STATUS_GET_BOOL : s = "GET_BOOL"; break;
case STATUS_GET_LINE : s = "GET_LINE"; break;
case STATUS_GET_HIDDEN : s = "GET_HIDDEN"; break;
case STATUS_GOT_IT : s = "GOT_IT"; break;
case STATUS_SHM_INFO : s = "SHM_INFO"; break;
case STATUS_SHM_GET : s = "SHM_GET"; break;
case STATUS_SHM_GET_BOOL : s = "SHM_GET_BOOL"; break;
case STATUS_SHM_GET_HIDDEN : s = "SHM_GET_HIDDEN"; break;
case STATUS_NEED_PASSPHRASE: s = "NEED_PASSPHRASE"; break;
case STATUS_VALIDSIG : s = "VALIDSIG"; break;
case STATUS_SIG_ID : s = "SIG_ID"; break;
case STATUS_ENC_TO : s = "ENC_TO"; break;
case STATUS_NODATA : s = "NODATA"; break;
case STATUS_BAD_PASSPHRASE : s = "BAD_PASSPHRASE"; break;
case STATUS_NO_PUBKEY : s = "NO_PUBKEY"; break;
case STATUS_NO_SECKEY : s = "NO_SECKEY"; break;
case STATUS_NEED_PASSPHRASE_SYM: s = "NEED_PASSPHRASE_SYM"; break;
case STATUS_DECRYPTION_FAILED: s = "DECRYPTION_FAILED"; break;
case STATUS_DECRYPTION_OKAY: s = "DECRYPTION_OKAY"; break;
case STATUS_MISSING_PASSPHRASE: s = "MISSING_PASSPHRASE"; break;
case STATUS_GOOD_PASSPHRASE : s = "GOOD_PASSPHRASE"; break;
case STATUS_GOODMDC : s = "GOODMDC"; break;
case STATUS_BADMDC : s = "BADMDC"; break;
case STATUS_ERRMDC : s = "ERRMDC"; break;
case STATUS_IMPORTED : s = "IMPORTED"; break;
case STATUS_IMPORT_RES : s = "IMPORT_RES"; break;
case STATUS_FILE_START : s = "FILE_START"; break;
case STATUS_FILE_DONE : s = "FILE_DONE"; break;
case STATUS_FILE_ERROR : s = "FILE_ERROR"; break;
case STATUS_BEGIN_DECRYPTION:s = "BEGIN_DECRYPTION"; break;
case STATUS_END_DECRYPTION : s = "END_DECRYPTION"; break;
case STATUS_BEGIN_ENCRYPTION:s = "BEGIN_ENCRYPTION"; break;
case STATUS_END_ENCRYPTION : s = "END_ENCRYPTION"; break;
case STATUS_DELETE_PROBLEM : s = "DELETE_PROBLEM"; break;
case STATUS_PROGRESS : s = "PROGRESS"; break;
case STATUS_SIG_CREATED : s = "SIG_CREATED"; break;
case STATUS_SESSION_KEY : s = "SESSION_KEY"; break;
case STATUS_NOTATION_NAME : s = "NOTATION_NAME" ; break;
case STATUS_NOTATION_DATA : s = "NOTATION_DATA" ; break;
case STATUS_POLICY_URL : s = "POLICY_URL" ; break;
case STATUS_BEGIN_STREAM : s = "BEGIN_STREAM"; break;
case STATUS_END_STREAM : s = "END_STREAM"; break;
case STATUS_KEY_CREATED : s = "KEY_CREATED"; break;
case STATUS_UNEXPECTED : s = "UNEXPECTED"; break;
case STATUS_INV_RECP : s = "INV_RECP"; break;
case STATUS_NO_RECP : s = "NO_RECP"; break;
case STATUS_ALREADY_SIGNED : s = "ALREADY_SIGNED"; break;
case STATUS_EXPSIG : s = "EXPSIG"; break;
case STATUS_EXPKEYSIG : s = "EXPKEYSIG"; break;
case STATUS_TRUNCATED : s = "TRUNCATED"; break;
case STATUS_ERROR : s = "ERROR"; break;
default: s = "?"; break;
}
return s;
}
void
gpgsm_status2 (CTRL ctrl, int no, ...)
{
va_list arg_ptr;
const char *text;
va_start (arg_ptr, no);
if (ctrl->no_server)
{
if (ctrl->status_fd == -1)
return; /* no status wanted */
if (!statusfp)
{
if (ctrl->status_fd == 1)
statusfp = stdout;
else if (ctrl->status_fd == 2)
statusfp = stderr;
else
statusfp = fdopen (ctrl->status_fd, "w");
if (!statusfp)
{
log_fatal ("can't open fd %d for status output: %s\n",
ctrl->status_fd, strerror(errno));
}
}
fputs ("[GNUPG:] ", statusfp);
fputs (get_status_string (no), statusfp);
while ( (text = va_arg (arg_ptr, const char*) ))
{
putc ( ' ', statusfp );
for (; *text; text++)
{
if (*text == '\n')
fputs ( "\\n", statusfp );
else if (*text == '\r')
fputs ( "\\r", statusfp );
else
putc ( *(const byte *)text, statusfp );
}
}
putc ('\n', statusfp);
fflush (statusfp);
}
else
{
ASSUAN_CONTEXT ctx = ctrl->server_local->assuan_ctx;
char buf[950], *p;
size_t n;
p = buf;
n = 0;
while ( (text = va_arg (arg_ptr, const char *)) )
{
if (n)
{
*p++ = ' ';
n++;
}
for ( ; *text && n < DIM (buf)-2; n++)
*p++ = *text++;
}
*p = 0;
assuan_write_status (ctx, get_status_string (no), buf);
}
va_end (arg_ptr);
}
void
gpgsm_status (CTRL ctrl, int no, const char *text)
{
gpgsm_status2 (ctrl, no, text, NULL);
}
#if 0
/*
* Write a status line with a buffer using %XX escapes. If WRAP is >
* 0 wrap the line after this length. If STRING is not NULL it will
* be prepended to the buffer, no escaping is done for string.
* A wrap of -1 forces spaces not to be encoded as %20.
*/
void
write_status_text_and_buffer ( int no, const char *string,
const char *buffer, size_t len, int wrap )
{
const char *s, *text;
int esc, first;
int lower_limit = ' ';
size_t n, count, dowrap;
if( !statusfp )
return; /* not enabled */
if (wrap == -1) {
lower_limit--;
wrap = 0;
}
text = get_status_string (no);
count = dowrap = first = 1;
do {
if (dowrap) {
fprintf (statusfp, "[GNUPG:] %s ", text );
count = dowrap = 0;
if (first && string) {
fputs (string, statusfp);
count += strlen (string);
}
first = 0;
}
for (esc=0, s=buffer, n=len; n && !esc; s++, n-- ) {
if ( *s == '%' || *(const byte*)s <= lower_limit
|| *(const byte*)s == 127 )
esc = 1;
if ( wrap && ++count > wrap ) {
dowrap=1;
break;
}
}
if (esc) {
s--; n++;
}
if (s != buffer)
fwrite (buffer, s-buffer, 1, statusfp );
if ( esc ) {
fprintf (statusfp, "%%%02X", *(const byte*)s );
s++; n--;
}
buffer = s;
len = n;
if ( dowrap && len )
putc ( '\n', statusfp );
} while ( len );
putc ('\n',statusfp);
fflush (statusfp);
}
#endif
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Fri, Dec 12, 11:37 AM (1 d, 22 h)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
4d/55/658313f451976fa16b5969e8d933
Attached To
rG GnuPG
Event Timeline
Log In to Comment