diff --git a/g10/call-agent.c b/g10/call-agent.c index 8f4e44b32..7c21a9a84 100644 --- a/g10/call-agent.c +++ b/g10/call-agent.c @@ -1,3205 +1,3212 @@ /* call-agent.c - Divert GPG operations to the agent. * Copyright (C) 2001-2003, 2006-2011, 2013 Free Software Foundation, Inc. * Copyright (C) 2013-2015 Werner Koch * Copyright (C) 2020 g10 Code GmbH * * 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 3 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, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "call-agent.h" #include "../common/status.h" #include "../common/shareddefs.h" #include "../common/host2net.h" #include "../common/ttyio.h" #define CONTROL_D ('D' - 'A' + 1) static assuan_context_t agent_ctx = NULL; static int did_early_card_test; struct confirm_parm_s { char *desc; char *ok; char *notok; }; struct default_inq_parm_s { ctrl_t ctrl; assuan_context_t ctx; struct { u32 *keyid; u32 *mainkeyid; int pubkey_algo; } keyinfo; struct confirm_parm_s *confirm; }; struct cipher_parm_s { struct default_inq_parm_s *dflt; assuan_context_t ctx; unsigned char *ciphertext; size_t ciphertextlen; }; struct writecert_parm_s { struct default_inq_parm_s *dflt; const unsigned char *certdata; size_t certdatalen; }; struct writekey_parm_s { struct default_inq_parm_s *dflt; const unsigned char *keydata; size_t keydatalen; }; struct genkey_parm_s { struct default_inq_parm_s *dflt; const char *keyparms; const char *passphrase; }; struct import_key_parm_s { struct default_inq_parm_s *dflt; const void *key; size_t keylen; }; struct cache_nonce_parm_s { char **cache_nonce_addr; char **passwd_nonce_addr; }; static gpg_error_t learn_status_cb (void *opaque, const char *line); /* If RC is not 0, write an appropriate status message. */ static void status_sc_op_failure (int rc) { switch (gpg_err_code (rc)) { case 0: break; case GPG_ERR_CANCELED: case GPG_ERR_FULLY_CANCELED: write_status_text (STATUS_SC_OP_FAILURE, "1"); break; case GPG_ERR_BAD_PIN: write_status_text (STATUS_SC_OP_FAILURE, "2"); break; default: write_status (STATUS_SC_OP_FAILURE); break; } } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct default_inq_parm_s *parm = opaque; const char *s; if (has_leading_keyword (line, "PINENTRY_LAUNCHED")) { err = gpg_proxy_pinentry_notify (parm->ctrl, line); if (err) log_error (_("failed to proxy %s inquiry to client\n"), "PINENTRY_LAUNCHED"); /* We do not pass errors to avoid breaking other code. */ } else if ((has_leading_keyword (line, "PASSPHRASE") || has_leading_keyword (line, "NEW_PASSPHRASE")) && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK) { if (have_static_passphrase ()) { s = get_static_passphrase (); err = assuan_send_data (parm->ctx, s, strlen (s)); } else { char *pw; char buf[32]; if (parm->keyinfo.keyid) emit_status_need_passphrase (parm->ctrl, parm->keyinfo.keyid, parm->keyinfo.mainkeyid, parm->keyinfo.pubkey_algo); snprintf (buf, sizeof (buf), "%u", 100); write_status_text (STATUS_INQUIRE_MAXLEN, buf); pw = cpr_get_hidden ("passphrase.enter", _("Enter passphrase: ")); cpr_kill_prompt (); if (*pw == CONTROL_D && !pw[1]) err = gpg_error (GPG_ERR_CANCELED); else err = assuan_send_data (parm->ctx, pw, strlen (pw)); xfree (pw); } } else if ((s = has_leading_keyword (line, "CONFIRM")) && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK && parm->confirm) { int ask = atoi (s); int yes; if (ask) { yes = cpr_get_answer_is_yes (NULL, parm->confirm->desc); if (yes) err = assuan_send_data (parm->ctx, NULL, 0); else err = gpg_error (GPG_ERR_NOT_CONFIRMED); } else { tty_printf ("%s", parm->confirm->desc); err = assuan_send_data (parm->ctx, NULL, 0); } } else log_debug ("ignoring gpg-agent inquiry '%s'\n", line); return err; } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername, int mode) { return warn_server_version_mismatch (ctx, servername, mode, write_status_strings2, NULL, !opt.quiet); } #define FLAG_FOR_CARD_SUPPRESS_ERRORS 2 /* Try to connect to the agent via socket or fork it off and work by pipes. Handle the server's initial greeting */ static int start_agent (ctrl_t ctrl, int flag_for_card) { int rc; (void)ctrl; /* Not yet used. */ /* Fixme: We need a context for each thread or serialize the access to the agent. */ if (agent_ctx) rc = 0; else { rc = start_new_gpg_agent (&agent_ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, opt.lc_ctype, opt.lc_messages, opt.session_env, opt.autostart, opt.verbose, DBG_IPC, NULL, NULL); if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT) { static int shown; if (!shown) { shown = 1; log_info (_("no gpg-agent running in this session\n")); } } else if (!rc && !(rc = warn_version_mismatch (agent_ctx, GPG_AGENT_NAME, 0))) { /* Tell the agent that we support Pinentry notifications. No error checking so that it will work also with older agents. */ assuan_transact (agent_ctx, "OPTION allow-pinentry-notify", NULL, NULL, NULL, NULL, NULL, NULL); /* Tell the agent about what version we are aware. This is here used to indirectly enable GPG_ERR_FULLY_CANCELED. */ assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0", NULL, NULL, NULL, NULL, NULL, NULL); /* Pass on the pinentry mode. */ if (opt.pinentry_mode) { char *tmp = xasprintf ("OPTION pinentry-mode=%s", str_pinentry_mode (opt.pinentry_mode)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) { log_error ("setting pinentry mode '%s' failed: %s\n", str_pinentry_mode (opt.pinentry_mode), gpg_strerror (rc)); write_status_error ("set_pinentry_mode", rc); } } /* Pass on the request origin. */ if (opt.request_origin) { char *tmp = xasprintf ("OPTION pretend-request-origin=%s", str_request_origin (opt.request_origin)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) { log_error ("setting request origin '%s' failed: %s\n", str_request_origin (opt.request_origin), gpg_strerror (rc)); write_status_error ("set_request_origin", rc); } } /* In DE_VS mode under Windows we require that the JENT RNG * is active. */ #ifdef HAVE_W32_SYSTEM if (!rc && opt.compliance == CO_DE_VS) { if (assuan_transact (agent_ctx, "GETINFO jent_active", NULL, NULL, NULL, NULL, NULL, NULL)) { rc = gpg_error (GPG_ERR_FORBIDDEN); log_error (_("%s is not compliant with %s mode\n"), GPG_AGENT_NAME, gnupg_compliance_option_string (opt.compliance)); write_status_error ("random-compliance", rc); } } #endif /*HAVE_W32_SYSTEM*/ } } if (!rc && flag_for_card && !did_early_card_test) { /* Request the serial number of the card for an early test. */ struct agent_card_info_s info; memset (&info, 0, sizeof info); if (!(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS)) rc = warn_version_mismatch (agent_ctx, SCDAEMON_NAME, 2); if (!rc) rc = assuan_transact (agent_ctx, opt.flags.use_only_openpgp_card? "SCD SERIALNO openpgp" : "SCD SERIALNO", NULL, NULL, NULL, NULL, learn_status_cb, &info); if (rc && !(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS)) { switch (gpg_err_code (rc)) { case GPG_ERR_NOT_SUPPORTED: case GPG_ERR_NO_SCDAEMON: write_status_text (STATUS_CARDCTRL, "6"); break; case GPG_ERR_OBJ_TERM_STATE: write_status_text (STATUS_CARDCTRL, "7"); break; default: write_status_text (STATUS_CARDCTRL, "4"); log_info ("selecting card failed: %s\n", gpg_strerror (rc)); break; } } if (!rc && is_status_enabled () && info.serialno) { char *buf; buf = xasprintf ("3 %s", info.serialno); write_status_text (STATUS_CARDCTRL, buf); xfree (buf); } agent_release_card_info (&info); if (!rc) did_early_card_test = 1; } return rc; } /* Return a new malloced string by unescaping the string S. Escaping is percent escaping and '+'/space mapping. A binary nul will silently be replaced by a 0xFF. Function returns NULL to indicate an out of memory status. */ static char * unescape_status_string (const unsigned char *s) { return percent_plus_unescape (s, 0xff); } /* Take a 20 or 32 byte hexencoded string and put it into the provided * FPRLEN byte long buffer FPR in binary format. Returns the actual * used length of the FPR buffer or 0 on error. */ static unsigned int unhexify_fpr (const char *hexstr, unsigned char *fpr, unsigned int fprlen) { const char *s; int n; for (s=hexstr, n=0; hexdigitp (s); s++, n++) ; if ((*s && *s != ' ') || !(n == 40 || n == 64)) return 0; /* no fingerprint (invalid or wrong length). */ for (s=hexstr, n=0; *s && n < fprlen; s += 2, n++) fpr[n] = xtoi_2 (s); return (n == 20 || n == 32)? n : 0; } /* Take the serial number from LINE and return it verbatim in a newly allocated string. We make sure that only hex characters are returned. */ static char * store_serialno (const char *line) { const char *s; char *p; for (s=line; hexdigitp (s); s++) ; p = xtrymalloc (s + 1 - line); if (p) { memcpy (p, line, s-line); p[s-line] = 0; } return p; } /* This is a dummy data line callback. */ static gpg_error_t dummy_data_cb (void *opaque, const void *buffer, size_t length) { (void)opaque; (void)buffer; (void)length; return 0; } /* A simple callback used to return the serialnumber of a card. */ static gpg_error_t get_serialno_cb (void *opaque, const char *line) { char **serialno = opaque; const char *keyword = line; const char *s; int keywordlen, n; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { if (*serialno) return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */ for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1)|| !(spacep (s) || !*s) ) return gpg_error (GPG_ERR_ASS_PARAMETER); *serialno = xtrymalloc (n+1); if (!*serialno) return out_of_core (); memcpy (*serialno, line, n); (*serialno)[n] = 0; } return 0; } /* Release the card info structure INFO. */ void agent_release_card_info (struct agent_card_info_s *info) { int i; if (!info) return; xfree (info->reader); info->reader = NULL; xfree (info->manufacturer_name); info->manufacturer_name = NULL; xfree (info->serialno); info->serialno = NULL; xfree (info->apptype); info->apptype = NULL; xfree (info->disp_name); info->disp_name = NULL; xfree (info->disp_lang); info->disp_lang = NULL; xfree (info->pubkey_url); info->pubkey_url = NULL; xfree (info->login_data); info->login_data = NULL; info->cafpr1len = info->cafpr2len = info->cafpr3len = 0; info->fpr1len = info->fpr2len = info->fpr3len = 0; for (i=0; i < DIM(info->private_do); i++) { xfree (info->private_do[i]); info->private_do[i] = NULL; } for (i=0; i < DIM(info->supported_keyalgo); i++) { free_strlist (info->supported_keyalgo[i]); info->supported_keyalgo[i] = NULL; } } static gpg_error_t learn_status_cb (void *opaque, const char *line) { struct agent_card_info_s *parm = opaque; const char *keyword = line; int keywordlen; int i; char *endp; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 6 && !memcmp (keyword, "READER", keywordlen)) { xfree (parm->reader); parm->reader = unescape_status_string (line); } else if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { xfree (parm->serialno); parm->serialno = store_serialno (line); parm->is_v2 = (strlen (parm->serialno) >= 16 && (xtoi_2 (parm->serialno+12) == 0 /* Yubikey */ || xtoi_2 (parm->serialno+12) >= 2)); } else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen)) { xfree (parm->apptype); parm->apptype = unescape_status_string (line); } + else if (keywordlen == 10 && !memcmp (keyword, "APPVERSION", keywordlen)) + { + unsigned int val = 0; + + sscanf (line, "%x", &val); + parm->appversion = val; + } else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen)) { xfree (parm->disp_name); parm->disp_name = unescape_status_string (line); } else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen)) { xfree (parm->disp_lang); parm->disp_lang = unescape_status_string (line); } else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen)) { parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0; } else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen)) { xfree (parm->pubkey_url); parm->pubkey_url = unescape_status_string (line); } else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen)) { xfree (parm->login_data); parm->login_data = unescape_status_string (line); } else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen)) { parm->sig_counter = strtoul (line, NULL, 0); } else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen)) { char *p, *buf; buf = p = unescape_status_string (line); if (buf) { while (spacep (p)) p++; parm->chv1_cached = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; for (i=0; *p && i < 3; i++) { parm->chvmaxlen[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } for (i=0; *p && i < 3; i++) { parm->chvretry[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } xfree (buf); } } else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen)) { char *p, *p2, *buf; int abool; buf = p = unescape_status_string (line); if (buf) { for (p = strtok (buf, " "); p; p = strtok (NULL, " ")) { p2 = strchr (p, '='); if (p2) { *p2++ = 0; abool = (*p2 == '1'); if (!strcmp (p, "ki")) parm->extcap.ki = abool; else if (!strcmp (p, "aac")) parm->extcap.aac = abool; else if (!strcmp (p, "bt")) parm->extcap.bt = abool; else if (!strcmp (p, "kdf")) parm->extcap.kdf = abool; else if (!strcmp (p, "si")) parm->status_indicator = strtoul (p2, NULL, 10); } } xfree (buf); } } else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->fpr1len = unhexify_fpr (line, parm->fpr1, sizeof parm->fpr1); else if (no == 2) parm->fpr2len = unhexify_fpr (line, parm->fpr2, sizeof parm->fpr2); else if (no == 3) parm->fpr3len = unhexify_fpr (line, parm->fpr3, sizeof parm->fpr3); } else if (keywordlen == 8 && !memcmp (keyword, "KEY-TIME", keywordlen)) { int no = atoi (line); while (* line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->fpr1time = strtoul (line, NULL, 10); else if (no == 2) parm->fpr2time = strtoul (line, NULL, 10); else if (no == 3) parm->fpr3time = strtoul (line, NULL, 10); } else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { const char *hexgrp = line; int no; while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (strncmp (line, "OPENPGP.", 8)) ; else if ((no = atoi (line+8)) == 1) unhexify_fpr (hexgrp, parm->grp1, sizeof parm->grp1); else if (no == 2) unhexify_fpr (hexgrp, parm->grp2, sizeof parm->grp2); else if (no == 3) unhexify_fpr (hexgrp, parm->grp3, sizeof parm->grp3); } else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->cafpr1len = unhexify_fpr (line, parm->cafpr1,sizeof parm->cafpr1); else if (no == 2) parm->cafpr2len = unhexify_fpr (line, parm->cafpr2,sizeof parm->cafpr2); else if (no == 3) parm->cafpr3len = unhexify_fpr (line, parm->cafpr3,sizeof parm->cafpr3); } else if (keywordlen == 8 && !memcmp (keyword, "KEY-ATTR", keywordlen)) { int keyno = 0; int algo = PUBKEY_ALGO_RSA; int n = 0; sscanf (line, "%d %d %n", &keyno, &algo, &n); keyno--; if (keyno < 0 || keyno >= DIM (parm->key_attr)) return 0; parm->key_attr[keyno].algo = algo; if (algo == PUBKEY_ALGO_RSA) parm->key_attr[keyno].nbits = strtoul (line+n+3, NULL, 10); else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA) parm->key_attr[keyno].curve = openpgp_is_curve_supported (line + n, NULL, NULL); } else if (keywordlen == 12 && !memcmp (keyword, "PRIVATE-DO-", 11) && strchr("1234", keyword[11])) { int no = keyword[11] - '1'; log_assert (no >= 0 && no <= 3); xfree (parm->private_do[no]); parm->private_do[no] = unescape_status_string (line); } else if (keywordlen == 12 && !memcmp (keyword, "MANUFACTURER", 12)) { xfree (parm->manufacturer_name); parm->manufacturer_name = NULL; parm->manufacturer_id = strtoul (line, &endp, 0); while (endp && spacep (endp)) endp++; if (endp && *endp) parm->manufacturer_name = xstrdup (endp); } else if (keywordlen == 3 && !memcmp (keyword, "KDF", 3)) { unsigned char *data = unescape_status_string (line); if (data[2] != 0x03) parm->kdf_do_enabled = 0; else if (data[22] != 0x85) parm->kdf_do_enabled = 1; else parm->kdf_do_enabled = 2; xfree (data); } else if (keywordlen == 5 && !memcmp (keyword, "UIF-", 4) && strchr("123", keyword[4])) { unsigned char *data; int no = keyword[4] - '1'; log_assert (no >= 0 && no <= 2); data = unescape_status_string (line); parm->uif[no] = (data[0] != 0xff); xfree (data); } else if (keywordlen == 13 && !memcmp (keyword, "KEY-ATTR-INFO", 13)) { if (!strncmp (line, "OPENPGP.", 8)) { int no; line += 8; no = atoi (line); if (no >= 1 && no <= 3) { no--; line++; while (spacep (line)) line++; append_to_strlist (&parm->supported_keyalgo[no], xstrdup (line)); } } /* Skip when it's not "OPENPGP.[123]". */ } return 0; } /* Call the scdaemon to learn about a smartcard. Note that in * contradiction to the function's name, gpg-agent's LEARN command is * used and not the low-level "SCD LEARN". * Used by: * card-util.c * keyedit_menu * card_store_key_with_backup (Woth force to remove secret key data) */ int agent_scd_learn (struct agent_card_info_s *info, int force) { int rc; struct default_inq_parm_s parm; struct agent_card_info_s dummyinfo; if (!info) info = &dummyinfo; memset (info, 0, sizeof *info); memset (&parm, 0, sizeof parm); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, force ? "LEARN --sendinfo --force" : "LEARN --sendinfo", dummy_data_cb, NULL, default_inq_cb, &parm, learn_status_cb, info); /* Also try to get the key attributes. */ if (!rc) agent_scd_getattr ("KEY-ATTR", info); if (info == &dummyinfo) agent_release_card_info (info); return rc; } struct keypairinfo_cb_parm_s { keypair_info_t kpinfo; keypair_info_t *kpinfo_tail; }; /* Callback for the agent_scd_keypairinfo function. */ static gpg_error_t scd_keypairinfo_status_cb (void *opaque, const char *line) { struct keypairinfo_cb_parm_s *parm = opaque; gpg_error_t err = 0; const char *keyword = line; int keywordlen; char *line_buffer = NULL; keypair_info_t kpi = NULL; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { /* The format of such a line is: * KEYPAIRINFO [usage] [keytime] [algostr] */ const char *fields[4]; int nfields; const char *hexgrp, *keyref, *usage; time_t atime; u32 keytime; line_buffer = xtrystrdup (line); if (!line_buffer) { err = gpg_error_from_syserror (); goto leave; } if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 2) goto leave; /* not enough args - invalid status line - ignore */ hexgrp = fields[0]; keyref = fields[1]; if (nfields > 2) usage = fields[2]; else usage = ""; if (nfields > 3) { atime = parse_timestamp (fields[3], NULL); if (atime == (time_t)(-1)) atime = 0; keytime = atime; } else keytime = 0; kpi = xtrycalloc (1, sizeof *kpi); if (!kpi) { err = gpg_error_from_syserror (); goto leave; } if (*hexgrp == 'X' && !hexgrp[1]) *kpi->keygrip = 0; /* No hexgrip. */ else if (strlen (hexgrp) == 2*KEYGRIP_LEN) mem2str (kpi->keygrip, hexgrp, sizeof kpi->keygrip); else { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } if (!*keyref) { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } kpi->idstr = xtrystrdup (keyref); if (!kpi->idstr) { err = gpg_error_from_syserror (); goto leave; } /* Parse and set the usage. */ for (; *usage; usage++) { switch (*usage) { case 's': kpi->usage |= GCRY_PK_USAGE_SIGN; break; case 'c': kpi->usage |= GCRY_PK_USAGE_CERT; break; case 'a': kpi->usage |= GCRY_PK_USAGE_AUTH; break; case 'e': kpi->usage |= GCRY_PK_USAGE_ENCR; break; } } kpi->keytime = keytime; /* Append to the list. */ *parm->kpinfo_tail = kpi; parm->kpinfo_tail = &kpi->next; kpi = NULL; } leave: free_keypair_info (kpi); xfree (line_buffer); return err; } /* Read the keypairinfo lines of the current card directly from * scdaemon. The list is returned as a string made up of the keygrip, * a space and the keyref. The flags of the string carry the usage * bits. If KEYREF is not NULL, only a single string is returned * which matches the given keyref. */ gpg_error_t agent_scd_keypairinfo (ctrl_t ctrl, const char *keyref, keypair_info_t *r_list) { gpg_error_t err; struct keypairinfo_cb_parm_s parm; struct default_inq_parm_s inq_parm; char line[ASSUAN_LINELENGTH]; *r_list = NULL; err= start_agent (ctrl, 1); if (err) return err; memset (&inq_parm, 0, sizeof inq_parm); inq_parm.ctx = agent_ctx; parm.kpinfo = NULL; parm.kpinfo_tail = &parm.kpinfo; if (keyref) snprintf (line, DIM(line), "SCD READKEY --info-only %s", keyref); else snprintf (line, DIM(line), "SCD LEARN --keypairinfo"); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inq_parm, scd_keypairinfo_status_cb, &parm); if (!err && !parm.kpinfo) err = gpg_error (GPG_ERR_NO_DATA); if (err) free_keypair_info (parm.kpinfo); else *r_list = parm.kpinfo; return err; } /* Send an APDU to the current card. On success the status word is * stored at R_SW unless R_SQ is NULL. With HEXAPDU being NULL only a * RESET command is send to scd. HEXAPDU may also be one of theseo * special strings: * * "undefined" :: Send the command "SCD SERIALNO undefined" * "lock" :: Send the command "SCD LOCK --wait" * "trylock" :: Send the command "SCD LOCK" * "unlock" :: Send the command "SCD UNLOCK" * "reset-keep-lock" :: Send the command "SCD RESET --keep-lock" * * Used by: * card-util.c */ gpg_error_t agent_scd_apdu (const char *hexapdu, unsigned int *r_sw) { gpg_error_t err; /* Start the agent but not with the card flag so that we do not autoselect the openpgp application. */ err = start_agent (NULL, 0); if (err) return err; if (!hexapdu) { err = assuan_transact (agent_ctx, "SCD RESET", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "reset-keep-lock")) { err = assuan_transact (agent_ctx, "SCD RESET --keep-lock", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "lock")) { err = assuan_transact (agent_ctx, "SCD LOCK --wait", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "trylock")) { err = assuan_transact (agent_ctx, "SCD LOCK", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "unlock")) { err = assuan_transact (agent_ctx, "SCD UNLOCK", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "undefined")) { err = assuan_transact (agent_ctx, "SCD SERIALNO undefined", NULL, NULL, NULL, NULL, NULL, NULL); } else { char line[ASSUAN_LINELENGTH]; membuf_t mb; unsigned char *data; size_t datalen; init_membuf (&mb, 256); snprintf (line, DIM(line), "SCD APDU %s", hexapdu); err = assuan_transact (agent_ctx, line, put_membuf_cb, &mb, NULL, NULL, NULL, NULL); if (!err) { data = get_membuf (&mb, &datalen); if (!data) err = gpg_error_from_syserror (); else if (datalen < 2) /* Ooops */ err = gpg_error (GPG_ERR_CARD); else { *r_sw = buf16_to_uint (data+datalen-2); } xfree (data); } } return err; } int agent_keytotpm (ctrl_t ctrl, const char *hexgrip) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; snprintf(line, DIM(line), "KEYTOTPM %s\n", hexgrip); rc = start_agent (ctrl, 0); if (rc) return rc; parm.ctx = agent_ctx; parm.ctrl = ctrl; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); if (rc) log_log (GPGRT_LOGLVL_ERROR, _("error from TPM: %s\n"), gpg_strerror (rc)); return rc; } /* Used by: * card_store_subkey * card_store_key_with_backup */ int agent_keytocard (const char *hexgrip, int keyno, int force, const char *serialno, const char *timestamp) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); snprintf (line, DIM(line), "KEYTOCARD %s%s %s OPENPGP.%d %s", force?"--force ": "", hexgrip, serialno, keyno, timestamp); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); if (rc) return rc; return rc; } /* Object used with the agent_scd_getattr_one. */ struct getattr_one_parm_s { const char *keyword; /* Keyword to look for. */ char *data; /* Malloced and unescaped data. */ gpg_error_t err; /* Error code or 0 on success. */ }; /* Callback for agent_scd_getattr_one. */ static gpg_error_t getattr_one_status_cb (void *opaque, const char *line) { struct getattr_one_parm_s *parm = opaque; const char *s; if (parm->data) return 0; /* We want only the first occurrence. */ if ((s=has_leading_keyword (line, parm->keyword))) { parm->data = percent_plus_unescape (s, 0xff); if (!parm->data) parm->err = gpg_error_from_syserror (); } return 0; } /* Simplified version of agent_scd_getattr. This function returns * only the first occurrence of the attribute NAME and stores it at * R_VALUE. A nul in the result is silennly replaced by 0xff. On * error NULL is stored at R_VALUE. */ gpg_error_t agent_scd_getattr_one (const char *name, char **r_value) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inqparm; struct getattr_one_parm_s parm; *r_value = NULL; if (!*name) return gpg_error (GPG_ERR_INV_VALUE); memset (&inqparm, 0, sizeof inqparm); inqparm.ctx = agent_ctx; memset (&parm, 0, sizeof parm); parm.keyword = name; /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); stpcpy (stpcpy (line, "SCD GETATTR "), name); err = start_agent (NULL, 1); if (err) return err; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inqparm, getattr_one_status_cb, &parm); if (!err && parm.err) err = parm.err; else if (!err && !parm.data) err = gpg_error (GPG_ERR_NO_DATA); if (!err) *r_value = parm.data; else xfree (parm.data); return err; } /* Call the agent to retrieve a data object. This function returns * the data in the same structure as used by the learn command. It is * allowed to update such a structure using this command. * * Used by: * build_sk_list * enum_secret_keys * get_signature_count * card-util.c * generate_keypair (KEY-ATTR) * card_store_key_with_backup (SERIALNO) * generate_card_subkeypair (KEY-ATTR) */ int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); if (!*name) return gpg_error (GPG_ERR_INV_VALUE); /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); stpcpy (stpcpy (line, "SCD GETATTR "), name); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, learn_status_cb, info); if (!rc && !strcmp (name, "KEY-FPR")) { /* Let the agent create the shadow keys if not yet done. */ if (info->fpr1len) assuan_transact (agent_ctx, "READKEY --card --no-data -- $SIGNKEYID", NULL, NULL, NULL, NULL, NULL, NULL); if (info->fpr2len) assuan_transact (agent_ctx, "READKEY --card --no-data -- $ENCRKEYID", NULL, NULL, NULL, NULL, NULL, NULL); } return rc; } /* Send an setattr command to the SCdaemon. * Used by: * card-util.c */ gpg_error_t agent_scd_setattr (const char *name, const void *value_arg, size_t valuelen) { gpg_error_t err; const unsigned char *value = value_arg; char line[ASSUAN_LINELENGTH]; char *p; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); if (!*name || !valuelen) return gpg_error (GPG_ERR_INV_VALUE); /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); p = stpcpy (stpcpy (line, "SCD SETATTR "), name); *p++ = ' '; for (; valuelen; value++, valuelen--) { if (p >= line + DIM(line)-5 ) return gpg_error (GPG_ERR_TOO_LARGE); if (*value < ' ' || *value == '+' || *value == '%') { sprintf (p, "%%%02X", *value); p += 3; } else if (*value == ' ') *p++ = '+'; else *p++ = *value; } *p = 0; err = start_agent (NULL, 1); if (!err) { parm.ctx = agent_ctx; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); } status_sc_op_failure (err); return err; } /* Handle a CERTDATA inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the END command. */ static gpg_error_t inq_writecert_parms (void *opaque, const char *line) { int rc; struct writecert_parm_s *parm = opaque; if (has_leading_keyword (line, "CERTDATA")) { rc = assuan_send_data (parm->dflt->ctx, parm->certdata, parm->certdatalen); } else rc = default_inq_cb (parm->dflt, line); return rc; } /* Send a WRITECERT command to the SCdaemon. * Used by: * card-util.c */ int agent_scd_writecert (const char *certidstr, const unsigned char *certdata, size_t certdatalen) { int rc; char line[ASSUAN_LINELENGTH]; struct writecert_parm_s parms; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; memset (&parms, 0, sizeof parms); snprintf (line, DIM(line), "SCD WRITECERT %s", certidstr); dfltparm.ctx = agent_ctx; parms.dflt = &dfltparm; parms.certdata = certdata; parms.certdatalen = certdatalen; rc = assuan_transact (agent_ctx, line, NULL, NULL, inq_writecert_parms, &parms, NULL, NULL); return rc; } /* Status callback for the SCD GENKEY command. */ static gpg_error_t scd_genkey_cb (void *opaque, const char *line) { u32 *createtime = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen)) { *createtime = (u32)strtoul (line, NULL, 10); } else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen)) { write_status_text (STATUS_PROGRESS, line); } return 0; } /* Send a GENKEY command to the SCdaemon. If *CREATETIME is not 0, * the value will be passed to SCDAEMON with --timestamp option so that * the key is created with this. Otherwise, timestamp was generated by * SCDEAMON. On success, creation time is stored back to * CREATETIME. * Used by: * gen_card_key */ int agent_scd_genkey (int keyno, int force, u32 *createtime) { int rc; char line[ASSUAN_LINELENGTH]; gnupg_isotime_t tbuf; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; if (*createtime) epoch2isotime (tbuf, *createtime); else *tbuf = 0; snprintf (line, DIM(line), "SCD GENKEY %s%s %s %d", *tbuf? "--timestamp=":"", tbuf, force? "--force":"", keyno); dfltparm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, scd_genkey_cb, createtime); status_sc_op_failure (rc); return rc; } /* Return the serial number of the card or an appropriate error. The * serial number is returned as a hexstring. With DEMAND the active * card is switched to the card with that serialno. * Used by: * card-util.c * build_sk_list * enum_secret_keys */ int agent_scd_serialno (char **r_serialno, const char *demand) { int err; char *serialno = NULL; char line[ASSUAN_LINELENGTH]; if (r_serialno) *r_serialno = NULL; err = start_agent (NULL, (1 | FLAG_FOR_CARD_SUPPRESS_ERRORS)); if (err) return err; if (!demand) strcpy (line, "SCD SERIALNO"); else snprintf (line, DIM(line), "SCD SERIALNO --demand=%s", demand); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, get_serialno_cb, &serialno); if (err) { xfree (serialno); return err; } if (r_serialno) *r_serialno = serialno; else xfree (serialno); return 0; } /* Send a READCERT command to the SCdaemon. * Used by: * card-util.c */ int agent_scd_readcert (const char *certidstr, void **r_buf, size_t *r_buflen) { int rc; char line[ASSUAN_LINELENGTH]; membuf_t data; size_t len; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); *r_buf = NULL; rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; init_membuf (&data, 2048); snprintf (line, DIM(line), "SCD READCERT %s", certidstr); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } *r_buf = get_membuf (&data, r_buflen); if (!*r_buf) return gpg_error (GPG_ERR_ENOMEM); return 0; } /* Callback for the agent_scd_readkey function. */ static gpg_error_t readkey_status_cb (void *opaque, const char *line) { u32 *keytimep = opaque; gpg_error_t err = 0; const char *args; char *line_buffer = NULL; /* FIXME: Get that info from the KEYPAIRINFO line. */ if ((args = has_leading_keyword (line, "KEYPAIRINFO")) && !*keytimep) { /* The format of such a line is: * KEYPAIRINFO [usage] [keytime] * * Note that we use only the first valid KEYPAIRINFO line. More * lines are possible if a second card carries the same key. */ const char *fields[4]; int nfields; time_t atime; line_buffer = xtrystrdup (line); if (!line_buffer) { err = gpg_error_from_syserror (); goto leave; } if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 4) goto leave; /* not enough args - ignore */ if (nfields > 3) { atime = parse_timestamp (fields[3], NULL); if (atime == (time_t)(-1)) atime = 0; *keytimep = atime; } else *keytimep = 0; } leave: xfree (line_buffer); return err; } /* This is a variant of agent_readkey which sends a READKEY command * directly Scdaemon. On success a new s-expression is stored at * R_RESULT. If R_KEYTIME is not NULL the key cresation time of an * OpenPGP card is stored there - if that is not known 0 is stored. * In the latter case it is allowed to pass NULL for R_RESULT. */ gpg_error_t agent_scd_readkey (ctrl_t ctrl, const char *keyrefstr, gcry_sexp_t *r_result, u32 *r_keytime) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; unsigned char *buf; size_t len, buflen; struct default_inq_parm_s dfltparm; u32 keytime; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctx = agent_ctx; if (r_result) *r_result = NULL; if (r_keytime) *r_keytime = 0; err = start_agent (ctrl, 1); if (err) return err; init_membuf (&data, 1024); snprintf (line, DIM(line), "SCD READKEY --info%s -- %s", r_result? "":"-only", keyrefstr); keytime = 0; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, readkey_status_cb, &keytime); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &buflen); if (!buf) return gpg_error_from_syserror (); if (r_result) err = gcry_sexp_new (r_result, buf, buflen, 0); else err = 0; xfree (buf); if (!err && r_keytime) *r_keytime = keytime; return err; } struct card_cardlist_parm_s { int error; strlist_t list; }; /* Callback function for agent_card_cardlist. */ static gpg_error_t card_cardlist_cb (void *opaque, const char *line) { struct card_cardlist_parm_s *parm = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { const char *s; int n; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1) || *s) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); else add_to_strlist (&parm->list, line); } return 0; } /* Return a list of currently available cards. * Used by: * card-util.c * skclist.c */ int agent_scd_cardlist (strlist_t *result) { int err; char line[ASSUAN_LINELENGTH]; struct card_cardlist_parm_s parm; memset (&parm, 0, sizeof parm); *result = NULL; err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS); if (err) return err; strcpy (line, "SCD GETINFO card_list"); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, card_cardlist_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_strlist (parm.list); return 0; } struct card_keyinfo_parm_s { int error; keypair_info_t list; }; /* Callback function for agent_card_keylist. */ static gpg_error_t card_keyinfo_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct card_keyinfo_parm_s *parm = opaque; const char *keyword = line; int keywordlen; keypair_info_t keyinfo = NULL; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 7 && !memcmp (keyword, "KEYINFO", keywordlen)) { const char *s; int n; keypair_info_t *l_p = &parm->list; while ((*l_p)) l_p = &(*l_p)->next; keyinfo = xtrycalloc (1, sizeof *keyinfo); if (!keyinfo) goto alloc_error; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (n != 40) goto parm_error; memcpy (keyinfo->keygrip, line, 40); keyinfo->keygrip[40] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (*line++ != 'T') goto parm_error; if (!*line) goto parm_error; while (spacep (line)) line++; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n) goto parm_error; keyinfo->serialno = xtrymalloc (n+1); if (!keyinfo->serialno) goto alloc_error; memcpy (keyinfo->serialno, line, n); keyinfo->serialno[n] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (!*line) goto parm_error; keyinfo->idstr = xtrystrdup (line); if (!keyinfo->idstr) goto alloc_error; *l_p = keyinfo; } return err; alloc_error: xfree (keyinfo); if (!parm->error) parm->error = gpg_error_from_syserror (); return 0; parm_error: xfree (keyinfo); if (!parm->error) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); return 0; } /* Free a keypair info list. */ void free_keypair_info (keypair_info_t l) { keypair_info_t l_next; for (; l; l = l_next) { l_next = l->next; xfree (l->serialno); xfree (l->idstr); xfree (l); } } /* Call the scdaemon to check if a key of KEYGRIP is available, or retrieve list of available keys on cards. With CAP, we can limit keys with specified capability. On success, the allocated structure is stored at RESULT. On error, an error code is returned and NULL is stored at RESULT. */ gpg_error_t agent_scd_keyinfo (const char *keygrip, int cap, keypair_info_t *result) { int err; struct card_keyinfo_parm_s parm; char line[ASSUAN_LINELENGTH]; char *list_option; *result = NULL; switch (cap) { case 0: list_option = "--list"; break; case GCRY_PK_USAGE_SIGN: list_option = "--list=sign"; break; case GCRY_PK_USAGE_ENCR: list_option = "--list=encr"; break; case GCRY_PK_USAGE_AUTH: list_option = "--list=auth"; break; default: return gpg_error (GPG_ERR_INV_VALUE); } memset (&parm, 0, sizeof parm); snprintf (line, sizeof line, "SCD KEYINFO %s", keygrip ? keygrip : list_option); err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS); if (err) return err; err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, card_keyinfo_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_keypair_info (parm.list); return err; } /* Change the PIN of an OpenPGP card or reset the retry counter. * CHVNO 1: Change the PIN * 2: For v1 cards: Same as 1. * For v2 cards: Reset the PIN using the Reset Code. * 3: Change the admin PIN * 101: Set a new PIN and reset the retry counter * 102: For v1 cars: Same as 101. * For v2 cards: Set a new Reset Code. * SERIALNO is not used. * Used by: * card-util.c */ int agent_scd_change_pin (int chvno, const char *serialno) { int rc; char line[ASSUAN_LINELENGTH]; const char *reset = ""; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); (void)serialno; if (chvno >= 100) reset = "--reset"; chvno %= 100; rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "SCD PASSWD %s %d", reset, chvno); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); status_sc_op_failure (rc); return rc; } /* Perform a CHECKPIN operation. SERIALNO should be the serial * number of the card - optionally followed by the fingerprint; * however the fingerprint is ignored here. * Used by: * card-util.c */ int agent_scd_checkpin (const char *serialno) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "SCD CHECKPIN %s", serialno); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); status_sc_op_failure (rc); return rc; } /* Note: All strings shall be UTF-8. On success the caller needs to free the string stored at R_PASSPHRASE. On error NULL will be stored at R_PASSPHRASE and an appropriate error code returned. Only called from passphrase.c:passphrase_get - see there for more comments on this ugly API. */ gpg_error_t agent_get_passphrase (const char *cache_id, const char *err_msg, const char *prompt, const char *desc_msg, int newsymkey, int repeat, int check, char **r_passphrase) { int rc; char line[ASSUAN_LINELENGTH]; char *arg1 = NULL; char *arg2 = NULL; char *arg3 = NULL; char *arg4 = NULL; membuf_t data; struct default_inq_parm_s dfltparm; int have_newsymkey; memset (&dfltparm, 0, sizeof dfltparm); *r_passphrase = NULL; rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; /* Check that the gpg-agent understands the repeat option. */ if (assuan_transact (agent_ctx, "GETINFO cmd_has_option GET_PASSPHRASE repeat", NULL, NULL, NULL, NULL, NULL, NULL)) return gpg_error (GPG_ERR_NOT_SUPPORTED); have_newsymkey = !(assuan_transact (agent_ctx, "GETINFO cmd_has_option GET_PASSPHRASE newsymkey", NULL, NULL, NULL, NULL, NULL, NULL)); if (cache_id && *cache_id) if (!(arg1 = percent_plus_escape (cache_id))) goto no_mem; if (err_msg && *err_msg) if (!(arg2 = percent_plus_escape (err_msg))) goto no_mem; if (prompt && *prompt) if (!(arg3 = percent_plus_escape (prompt))) goto no_mem; if (desc_msg && *desc_msg) if (!(arg4 = percent_plus_escape (desc_msg))) goto no_mem; /* CHECK && REPEAT or NEWSYMKEY is here an indication that a new * passphrase for symmetric encryption is requested; if the agent * supports this we enable the modern API by also passing --newsymkey. */ snprintf (line, DIM(line), "GET_PASSPHRASE --data --repeat=%d%s%s -- %s %s %s %s", repeat, ((repeat && check) || newsymkey)? " --check":"", (have_newsymkey && newsymkey)? " --newsymkey":"", arg1? arg1:"X", arg2? arg2:"X", arg3? arg3:"X", arg4? arg4:"X"); xfree (arg1); xfree (arg2); xfree (arg3); xfree (arg4); init_membuf_secure (&data, 64); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (rc) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); *r_passphrase = get_membuf (&data, NULL); if (!*r_passphrase) rc = gpg_error_from_syserror (); } return rc; no_mem: rc = gpg_error_from_syserror (); xfree (arg1); xfree (arg2); xfree (arg3); xfree (arg4); return rc; } gpg_error_t agent_clear_passphrase (const char *cache_id) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); if (!cache_id || !*cache_id) return 0; rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "CLEAR_PASSPHRASE %s", cache_id); return assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); } /* Ask the agent to pop up a confirmation dialog with the text DESC and an okay and cancel button. */ gpg_error_t gpg_agent_get_confirmation (const char *desc) { int rc; char *tmp; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; tmp = percent_plus_escape (desc); if (!tmp) return gpg_error_from_syserror (); snprintf (line, DIM(line), "GET_CONFIRMATION %s", tmp); xfree (tmp); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); return rc; } /* Return the S2K iteration count as computed by gpg-agent. On error * print a warning and return a default value. */ unsigned long agent_get_s2k_count (void) { gpg_error_t err; membuf_t data; char *buf; unsigned long count = 0; err = start_agent (NULL, 0); if (err) goto leave; init_membuf (&data, 32); err = assuan_transact (agent_ctx, "GETINFO s2k_count", put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); buf = get_membuf (&data, NULL); if (!buf) err = gpg_error_from_syserror (); else { count = strtoul (buf, NULL, 10); xfree (buf); } } leave: if (err || count < 65536) { /* Don't print an error if an older agent is used. */ if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER) log_error (_("problem with the agent: %s\n"), gpg_strerror (err)); /* Default to 65536 which was used up to 2.0.13. */ count = 65536; } return count; } struct keyinfo_data_parm_s { char *serialno; int is_smartcard; int passphrase_cached; int cleartext; int card_available; }; static gpg_error_t keyinfo_status_cb (void *opaque, const char *line) { struct keyinfo_data_parm_s *data = opaque; char *s; if ((s = has_leading_keyword (line, "KEYINFO")) && data) { /* Parse the arguments: * 0 1 2 3 4 5 * * * 6 7 8 * */ const char *fields[9]; if (split_fields (s, fields, DIM (fields)) == 9) { data->is_smartcard = (fields[1][0] == 'T'); if (data->is_smartcard && !data->serialno && strcmp (fields[2], "-")) data->serialno = xtrystrdup (fields[2]); /* '1' for cached */ data->passphrase_cached = (fields[4][0] == '1'); /* 'P' for protected, 'C' for clear */ data->cleartext = (fields[5][0] == 'C'); /* 'A' for card is available */ data->card_available = (fields[8][0] == 'A'); } } return 0; } /* Ask the agent whether a secret key for the given public key is available. Returns 0 if not available. Bigger value is preferred. */ int agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *hexgrip; struct keyinfo_data_parm_s keyinfo; memset (&keyinfo, 0, sizeof keyinfo); err = start_agent (ctrl, 0); if (err) return err; err = hexkeygrip_from_pk (pk, &hexgrip); if (err) return err; snprintf (line, sizeof line, "KEYINFO %s", hexgrip); xfree (hexgrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, keyinfo_status_cb, &keyinfo); xfree (keyinfo.serialno); if (err) return 0; if (keyinfo.card_available) return 4; if (keyinfo.passphrase_cached) return 3; if (keyinfo.is_smartcard) return 2; return 1; } /* Ask the agent whether a secret key is available for any of the keys (primary or sub) in KEYBLOCK. Returns 0 if available. */ gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *p; kbnode_t kbctx, node; int nkeys; /* (always zero in secret_keygrips mode) */ unsigned char grip[KEYGRIP_LEN]; const unsigned char *s; unsigned int n; err = start_agent (ctrl, 0); if (err) return err; /* If we have not yet issued a "HAVEKEY --list" do that now. We use * a more or less arbitray limit of 1000 keys. */ if (ctrl && !ctrl->secret_keygrips && !ctrl->no_more_secret_keygrips) { membuf_t data; init_membuf (&data, 4096); err = assuan_transact (agent_ctx, "HAVEKEY --list=1000", put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) xfree (get_membuf (&data, NULL)); else { ctrl->secret_keygrips = get_membuf (&data, &ctrl->secret_keygrips_len); if (!ctrl->secret_keygrips) err = gpg_error_from_syserror (); if ((ctrl->secret_keygrips_len % 20)) { err = gpg_error (GPG_ERR_INV_DATA); xfree (ctrl->secret_keygrips); ctrl->secret_keygrips = NULL; } } if (err) { log_info ("problem with fast path key listing: %s - ignored\n", gpg_strerror (err)); err = 0; } /* We want to do this only once. */ ctrl->no_more_secret_keygrips = 1; } err = gpg_error (GPG_ERR_NO_SECKEY); /* Just in case no key was found in KEYBLOCK. */ p = stpcpy (line, "HAVEKEY"); for (kbctx=NULL, nkeys=0; (node = walk_kbnode (keyblock, &kbctx, 0)); ) if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { if (ctrl && ctrl->secret_keygrips) { /* We got an array with all secret keygrips. Check this. */ err = keygrip_from_pk (node->pkt->pkt.public_key, grip); if (err) return err; for (s=ctrl->secret_keygrips, n = 0; n < ctrl->secret_keygrips_len; s += 20, n += 20) { if (!memcmp (s, grip, 20)) return 0; } err = gpg_error (GPG_ERR_NO_SECKEY); /* Keep on looping over the keyblock. Never bump nkeys. */ } else { if (nkeys && ((p - line) + 41) > (ASSUAN_LINELENGTH - 2)) { err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err != gpg_err_code (GPG_ERR_NO_SECKEY)) break; /* Seckey available or unexpected error - ready. */ p = stpcpy (line, "HAVEKEY"); nkeys = 0; } err = keygrip_from_pk (node->pkt->pkt.public_key, grip); if (err) return err; *p++ = ' '; bin2hex (grip, 20, p); p += 40; nkeys++; } } if (!err && nkeys) err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); return err; } /* Return the serial number for a secret key. If the returned serial number is NULL, the key is not stored on a smartcard. Caller needs to free R_SERIALNO. if r_cleartext is not NULL, the referenced int will be set to 1 if the agent's copy of the key is stored in the clear, or 0 otherwise */ gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct keyinfo_data_parm_s keyinfo; memset (&keyinfo, 0,sizeof keyinfo); *r_serialno = NULL; err = start_agent (ctrl, 0); if (err) return err; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, keyinfo_status_cb, &keyinfo); if (!err && keyinfo.serialno) { /* Sanity check for bad characters. */ if (strpbrk (keyinfo.serialno, ":\n\r")) err = GPG_ERR_INV_VALUE; } if (err) xfree (keyinfo.serialno); else { *r_serialno = keyinfo.serialno; if (r_cleartext) *r_cleartext = keyinfo.cleartext; } return err; } /* Status callback for agent_import_key, agent_export_key and agent_genkey. */ static gpg_error_t cache_nonce_status_cb (void *opaque, const char *line) { struct cache_nonce_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "CACHE_NONCE"))) { if (parm->cache_nonce_addr) { xfree (*parm->cache_nonce_addr); *parm->cache_nonce_addr = xtrystrdup (s); } } else if ((s = has_leading_keyword (line, "PASSWD_NONCE"))) { if (parm->passwd_nonce_addr) { xfree (*parm->passwd_nonce_addr); *parm->passwd_nonce_addr = xtrystrdup (s); } } else if ((s = has_leading_keyword (line, "PROGRESS"))) { if (opt.enable_progress_filter) write_status_text (STATUS_PROGRESS, s); } return 0; } /* Handle a KEYPARMS inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the end */ static gpg_error_t inq_genkey_parms (void *opaque, const char *line) { struct genkey_parm_s *parm = opaque; gpg_error_t err; if (has_leading_keyword (line, "KEYPARAM")) { err = assuan_send_data (parm->dflt->ctx, parm->keyparms, strlen (parm->keyparms)); } else if (has_leading_keyword (line, "NEWPASSWD") && parm->passphrase) { err = assuan_send_data (parm->dflt->ctx, parm->passphrase, strlen (parm->passphrase)); } else err = default_inq_cb (parm->dflt, line); return err; } /* Call the agent to generate a new key. KEYPARMS is the usual S-expression giving the parameters of the key. gpg-agent passes it gcry_pk_genkey. If NO_PROTECTION is true the agent is advised not to protect the generated key. If NO_PROTECTION is not set and PASSPHRASE is not NULL the agent is requested to protect the key with that passphrase instead of asking for one. TIMESTAMP is the creation time of the key or zero. */ gpg_error_t agent_genkey (ctrl_t ctrl, char **cache_nonce_addr, char **passwd_nonce_addr, const char *keyparms, int no_protection, const char *passphrase, time_t timestamp, gcry_sexp_t *r_pubkey) { gpg_error_t err; struct genkey_parm_s gk_parm; struct cache_nonce_parm_s cn_parm; struct default_inq_parm_s dfltparm; membuf_t data; size_t len; unsigned char *buf; char timestamparg[16 + 16]; /* The 2nd 16 is sizeof(gnupg_isotime_t) */ char line[ASSUAN_LINELENGTH]; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_pubkey = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; /* Do not use our cache of secret keygrips anymore - this command * would otherwise requiring to update that cache. */ if (ctrl && ctrl->secret_keygrips) { xfree (ctrl->secret_keygrips); ctrl->secret_keygrips = 0; } if (timestamp) { strcpy (timestamparg, " --timestamp="); epoch2isotime (timestamparg+13, timestamp); } else *timestamparg = 0; if (passwd_nonce_addr && *passwd_nonce_addr) ; /* A RESET would flush the passwd nonce cache. */ else { err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } init_membuf (&data, 1024); gk_parm.dflt = &dfltparm; gk_parm.keyparms = keyparms; gk_parm.passphrase = passphrase; snprintf (line, sizeof line, "GENKEY%s%s%s%s%s%s", *timestamparg? timestamparg : "", no_protection? " --no-protection" : passphrase ? " --inq-passwd" : /* */ "", passwd_nonce_addr && *passwd_nonce_addr? " --passwd-nonce=":"", passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"", cache_nonce_addr && *cache_nonce_addr? " ":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:""); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, inq_genkey_parms, &gk_parm, cache_nonce_status_cb, &cn_parm); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) err = gpg_error_from_syserror (); else { err = gcry_sexp_sscan (r_pubkey, NULL, buf, len); xfree (buf); } return err; } /* Call the agent to read the public key part for a given keygrip. * Values from FROMCARD: * 0 - Standard * 1 - The key is read from the current card * via the agent and a stub file is created. */ gpg_error_t agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip, unsigned char **r_pubkey) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_pubkey = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; err = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (fromcard) snprintf (line, DIM(line), "READKEY --card -- %s", hexkeygrip); else snprintf (line, DIM(line), "READKEY -- %s", hexkeygrip); init_membuf (&data, 1024); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); if (!gcry_sexp_canon_len (buf, len, NULL, NULL)) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } *r_pubkey = buf; return 0; } /* Call the agent to do a sign operation using the key identified by the hex string KEYGRIP. DESC is a description of the key to be displayed if the agent needs to ask for the PIN. DIGEST and DIGESTLEN is the hash value to sign and DIGESTALGO the algorithm id used to compute the digest. If CACHE_NONCE is used the agent is advised to first try a passphrase associated with that nonce. */ gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *keygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, unsigned char *digest, size_t digestlen, int digestalgo, gcry_sexp_t *r_sigval) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; *r_sigval = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (digestlen*2 + 50 > DIM(line)) return gpg_error (GPG_ERR_GENERAL); err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; snprintf (line, DIM(line), "SIGKEY %s", keygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, sizeof line, "SETHASH %d ", digestalgo); bin2hex (digest, digestlen, line + strlen (line)); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; init_membuf (&data, 1024); snprintf (line, sizeof line, "PKSIGN%s%s", cache_nonce? " -- ":"", cache_nonce? cache_nonce:""); if (DBG_CLOCK) log_clock ("enter signing"); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (DBG_CLOCK) log_clock ("leave signing"); if (err) xfree (get_membuf (&data, NULL)); else { unsigned char *buf; size_t len; buf = get_membuf (&data, &len); if (!buf) err = gpg_error_from_syserror (); else { err = gcry_sexp_sscan (r_sigval, NULL, buf, len); xfree (buf); } } return err; } /* Handle a CIPHERTEXT inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the END. */ static gpg_error_t inq_ciphertext_cb (void *opaque, const char *line) { struct cipher_parm_s *parm = opaque; int rc; if (has_leading_keyword (line, "CIPHERTEXT")) { assuan_begin_confidential (parm->ctx); rc = assuan_send_data (parm->dflt->ctx, parm->ciphertext, parm->ciphertextlen); assuan_end_confidential (parm->ctx); } else rc = default_inq_cb (parm->dflt, line); return rc; } /* Check whether there is any padding info from the agent. */ static gpg_error_t padding_info_cb (void *opaque, const char *line) { int *r_padding = opaque; const char *s; if ((s=has_leading_keyword (line, "PADDING"))) { *r_padding = atoi (s); } return 0; } /* Call the agent to do a decrypt operation using the key identified by the hex string KEYGRIP and the input data S_CIPHERTEXT. On the success the decoded value is stored verbatim at R_BUF and its length at R_BUF; the callers needs to release it. KEYID, MAINKEYID and PUBKEY_ALGO are used to construct additional promots or status messages. The padding information is stored at R_PADDING with -1 for not known. */ gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, gcry_sexp_t s_ciphertext, unsigned char **r_buf, size_t *r_buflen, int *r_padding) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; size_t n, len; char *p, *buf, *endp; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; if (!keygrip || strlen(keygrip) != 40 || !s_ciphertext || !r_buf || !r_buflen || !r_padding) return gpg_error (GPG_ERR_INV_VALUE); *r_buf = NULL; *r_padding = -1; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; snprintf (line, sizeof line, "SETKEY %s", keygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } init_membuf_secure (&data, 1024); { struct cipher_parm_s parm; parm.dflt = &dfltparm; parm.ctx = agent_ctx; err = make_canon_sexp (s_ciphertext, &parm.ciphertext, &parm.ciphertextlen); if (err) return err; err = assuan_transact (agent_ctx, "PKDECRYPT", put_membuf_cb, &data, inq_ciphertext_cb, &parm, padding_info_cb, r_padding); xfree (parm.ciphertext); } if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); if (len == 0 || *buf != '(') { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } if (len < 12 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)" */ { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } while (buf[len-1] == 0) len--; if (buf[len-1] != ')') return gpg_error (GPG_ERR_INV_SEXP); len--; /* Drop the final close-paren. */ p = buf + 8; /* Skip leading parenthesis and the value tag. */ len -= 8; /* Count only the data of the second part. */ n = strtoul (p, &endp, 10); if (!n || *endp != ':') { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } endp++; if (endp-p+n > len) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */ } memmove (buf, endp, n); *r_buflen = n; *r_buf = buf; return 0; } /* Retrieve a key encryption key from the agent. With FOREXPORT true the key shall be used for export, with false for import. On success the new key is stored at R_KEY and its length at R_KEKLEN. */ gpg_error_t agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_kek = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "KEYWRAP_KEY %s", forexport? "--export":"--import"); init_membuf_secure (&data, 64); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_kek = buf; *r_keklen = len; return 0; } /* Handle the inquiry for an IMPORT_KEY command. */ static gpg_error_t inq_import_key_parms (void *opaque, const char *line) { struct import_key_parm_s *parm = opaque; gpg_error_t err; if (has_leading_keyword (line, "KEYDATA")) { err = assuan_send_data (parm->dflt->ctx, parm->key, parm->keylen); } else err = default_inq_cb (parm->dflt, line); return err; } /* Call the agent to import a key into the agent. */ gpg_error_t agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr, const void *key, size_t keylen, int unattended, int force, u32 *keyid, u32 *mainkeyid, int pubkey_algo, u32 timestamp) { gpg_error_t err; struct import_key_parm_s parm; struct cache_nonce_parm_s cn_parm; char timestamparg[16 + 16]; /* The 2nd 16 is sizeof(gnupg_isotime_t) */ char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; /* Do not use our cache of secret keygrips anymore - this command * would otherwise requiring to update that cache. */ if (ctrl && ctrl->secret_keygrips) { xfree (ctrl->secret_keygrips); ctrl->secret_keygrips = 0; } if (timestamp) { strcpy (timestamparg, " --timestamp="); epoch2isotime (timestamparg+13, timestamp); } else *timestamparg = 0; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } parm.dflt = &dfltparm; parm.key = key; parm.keylen = keylen; snprintf (line, sizeof line, "IMPORT_KEY%s%s%s%s%s", *timestamparg? timestamparg : "", unattended? " --unattended":"", force? " --force":"", cache_nonce_addr && *cache_nonce_addr? " ":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:""); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, NULL, NULL, inq_import_key_parms, &parm, cache_nonce_status_cb, &cn_parm); return err; } /* Receive a secret key from the agent. HEXKEYGRIP is the hexified keygrip, DESC a prompt to be displayed with the agent's passphrase question (needs to be plus+percent escaped). if OPENPGP_PROTECTED is not zero, ensure that the key material is returned in RFC 4880-compatible passphrased-protected form. If CACHE_NONCE_ADDR is not NULL the agent is advised to first try a passphrase associated with that nonce. On success the key is stored as a canonical S-expression at R_RESULT and R_RESULTLEN. */ gpg_error_t agent_export_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int openpgp_protected, char **cache_nonce_addr, unsigned char **r_result, size_t *r_resultlen, u32 *keyid, u32 *mainkeyid, int pubkey_algo) { gpg_error_t err; struct cache_nonce_parm_s cn_parm; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; *r_result = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, DIM(line), "EXPORT_KEY %s%s%s %s", openpgp_protected ? "--openpgp ":"", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", hexkeygrip); init_membuf_secure (&data, 1024); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, cache_nonce_status_cb, &cn_parm); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_result = buf; *r_resultlen = len; return 0; } /* Status callback for handling confirmation. */ static gpg_error_t confirm_status_cb (void *opaque, const char *line) { struct confirm_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "SETDESC"))) { xfree (parm->desc); parm->desc = unescape_status_string (s); } else if ((s = has_leading_keyword (line, "SETOK"))) { xfree (parm->ok); parm->ok = unescape_status_string (s); } else if ((s = has_leading_keyword (line, "SETNOTOK"))) { xfree (parm->notok); parm->notok = unescape_status_string (s); } return 0; } /* Ask the agent to delete the key identified by HEXKEYGRIP. If DESC is not NULL, display DESC instead of the default description message. If FORCE is true the agent is advised not to ask for confirmation. */ gpg_error_t agent_delete_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int force) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; struct confirm_parm_s confirm_parm; memset (&confirm_parm, 0, sizeof confirm_parm); memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.confirm = &confirm_parm; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, DIM(line), "DELETE_KEY%s %s", force? " --force":"", hexkeygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, confirm_status_cb, &confirm_parm); xfree (confirm_parm.desc); xfree (confirm_parm.ok); xfree (confirm_parm.notok); return err; } /* Ask the agent to change the passphrase of the key identified by * HEXKEYGRIP. If DESC is not NULL, display DESC instead of the * default description message. If CACHE_NONCE_ADDR is not NULL the * agent is advised to first try a passphrase associated with that * nonce. If PASSWD_NONCE_ADDR is not NULL the agent will try to use * the passphrase associated with that nonce for the new passphrase. * If VERIFY is true the passphrase is only verified. */ gpg_error_t agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int verify, char **cache_nonce_addr, char **passwd_nonce_addr) { gpg_error_t err; struct cache_nonce_parm_s cn_parm; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } if (verify) snprintf (line, DIM(line), "PASSWD %s%s --verify %s", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", hexkeygrip); else snprintf (line, DIM(line), "PASSWD %s%s %s%s %s", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", passwd_nonce_addr && *passwd_nonce_addr? "--passwd-nonce=":"", passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"", hexkeygrip); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = passwd_nonce_addr; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, cache_nonce_status_cb, &cn_parm); return err; } /* Return the version reported by gpg-agent. */ gpg_error_t agent_get_version (ctrl_t ctrl, char **r_version) { gpg_error_t err; err = start_agent (ctrl, 0); if (err) return err; err = get_assuan_server_version (agent_ctx, 0, r_version); return err; } diff --git a/g10/call-agent.h b/g10/call-agent.h index efea7ec4a..a4cbc3162 100644 --- a/g10/call-agent.h +++ b/g10/call-agent.h @@ -1,249 +1,250 @@ /* call-agent.h - Divert operations to the agent * Copyright (C) 2003 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 3 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, see . */ #ifndef GNUPG_G10_CALL_AGENT_H #define GNUPG_G10_CALL_AGENT_H struct key_attr { int algo; /* Algorithm identifier. */ union { unsigned int nbits; /* Supported keysize. */ const char *curve; /* Name of curve. */ }; }; struct agent_card_info_s { int error; /* private. */ char *reader; /* Reader information. */ char *apptype; /* Malloced application type string. */ + unsigned int appversion; /* Version of the application. */ unsigned int manufacturer_id; char *manufacturer_name; /* malloced. */ char *serialno; /* malloced hex string. */ char *disp_name; /* malloced. */ char *disp_lang; /* malloced. */ int disp_sex; /* 0 = unspecified, 1 = male, 2 = female */ char *pubkey_url; /* malloced. */ char *login_data; /* malloced. */ char *private_do[4]; /* malloced. */ char cafpr1len; /* Length of the CA-fingerprint or 0 if invalid. */ char cafpr2len; char cafpr3len; char cafpr1[20]; char cafpr2[20]; char cafpr3[20]; unsigned char fpr1len; /* Length of the fingerprint or 0 if invalid. */ unsigned char fpr2len; unsigned char fpr3len; char fpr1[20]; char fpr2[20]; char fpr3[20]; u32 fpr1time; u32 fpr2time; u32 fpr3time; char grp1[20]; /* The keygrip for OPENPGP.1 */ char grp2[20]; /* The keygrip for OPENPGP.2 */ char grp3[20]; /* The keygrip for OPENPGP.3 */ unsigned long sig_counter; int chv1_cached; /* True if a PIN is not required for each signing. Note that the gpg-agent might cache it anyway. */ int is_v2; /* True if this is a v2 card. */ int chvmaxlen[3]; /* Maximum allowed length of a CHV. */ int chvretry[3]; /* Allowed retries for the CHV; 0 = blocked. */ struct key_attr key_attr[3]; struct { unsigned int ki:1; /* Key import available. */ unsigned int aac:1; /* Algorithm attributes are changeable. */ unsigned int kdf:1; /* KDF object to support PIN hashing available. */ unsigned int bt:1; /* Button for confirmation available. */ } extcap; unsigned int status_indicator; int kdf_do_enabled; /* Non-zero if card has a KDF object, 0 if not. */ int uif[3]; /* True if User Interaction Flag is on. */ strlist_t supported_keyalgo[3]; }; /* Object to store information from the KEYPAIRINFO or the KEYINFO * status lines. */ struct keypair_info_s { struct keypair_info_s *next; char keygrip[2 * KEYGRIP_LEN + 1]; /* Stored in hex. */ char *serialno; /* NULL or the malloced serialno. */ char *idstr; /* Malloced keyref (e.g. "OPENPGP.1") */ unsigned int usage; /* Key usage flags. */ u32 keytime; /* Key creation time from the card's DO. */ int algo; /* Helper to store the pubkey algo. */ }; typedef struct keypair_info_s *keypair_info_t; /* Release the card info structure. */ void agent_release_card_info (struct agent_card_info_s *info); /* Return card info. */ int agent_scd_learn (struct agent_card_info_s *info, int force); /* Get the keypariinfo directly from scdaemon. */ gpg_error_t agent_scd_keypairinfo (ctrl_t ctrl, const char *keyref, keypair_info_t *r_list); /* Return list of cards. */ int agent_scd_cardlist (strlist_t *result); /* Free a keypair info list. */ void free_keypair_info (keypair_info_t l); /* Return card key information. */ gpg_error_t agent_scd_keyinfo (const char *keygrip, int cap, keypair_info_t *result); /* Return the serial number, possibly select by DEMAND. */ int agent_scd_serialno (char **r_serialno, const char *demand); /* Send an APDU to the card. */ gpg_error_t agent_scd_apdu (const char *hexapdu, unsigned int *r_sw); /* Get attribute NAME from the card and store at R_VALUE. */ gpg_error_t agent_scd_getattr_one (const char *name, char **r_value); /* Update INFO with the attribute NAME. */ int agent_scd_getattr (const char *name, struct agent_card_info_s *info); /* send the KEYTOTPM command */ int agent_keytotpm (ctrl_t ctrl, const char *hexgrip); /* Send the KEYTOCARD command. */ int agent_keytocard (const char *hexgrip, int keyno, int force, const char *serialno, const char *timestamp); /* Send a SETATTR command to the SCdaemon. */ gpg_error_t agent_scd_setattr (const char *name, const void *value, size_t valuelen); /* Send a WRITECERT command to the SCdaemon. */ int agent_scd_writecert (const char *certidstr, const unsigned char *certdata, size_t certdatalen); /* Send a GENKEY command to the SCdaemon. */ int agent_scd_genkey (int keyno, int force, u32 *createtime); /* Send a READCERT command to the SCdaemon. */ int agent_scd_readcert (const char *certidstr, void **r_buf, size_t *r_buflen); /* Send a READKEY command to the SCdaemon. */ gpg_error_t agent_scd_readkey (ctrl_t ctrl, const char *keyrefstr, gcry_sexp_t *r_result, u32 *r_keytime); /* Change the PIN of an OpenPGP card or reset the retry counter. */ int agent_scd_change_pin (int chvno, const char *serialno); /* Send the CHECKPIN command to the SCdaemon. */ int agent_scd_checkpin (const char *serialno); /* Send the GET_PASSPHRASE command to the agent. */ gpg_error_t agent_get_passphrase (const char *cache_id, const char *err_msg, const char *prompt, const char *desc_msg, int newsymkey, int repeat, int check, char **r_passphrase); /* Send the CLEAR_PASSPHRASE command to the agent. */ gpg_error_t agent_clear_passphrase (const char *cache_id); /* Present the prompt DESC and ask the user to confirm. */ gpg_error_t gpg_agent_get_confirmation (const char *desc); /* Return the S2K iteration count as computed by gpg-agent. */ unsigned long agent_get_s2k_count (void); /* Check whether a secret key for public key PK is available. Returns 0 if not available, positive value if the secret key is available. */ int agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk); /* Ask the agent whether a secret key is available for any of the keys (primary or sub) in KEYBLOCK. Returns 0 if available. */ gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock); /* Return infos about the secret key with HEXKEYGRIP. */ gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext); /* Generate a new key. */ gpg_error_t agent_genkey (ctrl_t ctrl, char **cache_nonce_addr, char **passwd_nonce_addr, const char *keyparms, int no_protection, const char *passphrase, time_t timestamp, gcry_sexp_t *r_pubkey); /* Read a public key. FROMCARD may be 0, 1, or 2. */ gpg_error_t agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip, unsigned char **r_pubkey); /* Create a signature. */ gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *hexkeygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, unsigned char *digest, size_t digestlen, int digestalgo, gcry_sexp_t *r_sigval); /* Decrypt a ciphertext. */ gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, gcry_sexp_t s_ciphertext, unsigned char **r_buf, size_t *r_buflen, int *r_padding); /* Retrieve a key encryption key. */ gpg_error_t agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen); /* Send a key to the agent. */ gpg_error_t agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr, const void *key, size_t keylen, int unattended, int force, u32 *keyid, u32 *mainkeyid, int pubkey_algo, u32 timestamp); /* Receive a key from the agent. */ gpg_error_t agent_export_key (ctrl_t ctrl, const char *keygrip, const char *desc, int openpgp_protected, char **cache_nonce_addr, unsigned char **r_result, size_t *r_resultlen, u32 *keyid, u32 *mainkeyid, int pubkey_algo); /* Delete a key from the agent. */ gpg_error_t agent_delete_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int force); /* Change the passphrase of a key. */ gpg_error_t agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int verify, char **cache_nonce_addr, char **passwd_nonce_addr); /* Get the version reported by gpg-agent. */ gpg_error_t agent_get_version (ctrl_t ctrl, char **r_version); #endif /*GNUPG_G10_CALL_AGENT_H*/ diff --git a/g10/card-util.c b/g10/card-util.c index f3ede6d46..a5f1f7bb7 100644 --- a/g10/card-util.c +++ b/g10/card-util.c @@ -1,2566 +1,2594 @@ /* card-util.c - Utility functions for the OpenPGP card. * Copyright (C) 2003-2005, 2009 Free Software Foundation, Inc. * Copyright (C) 2003-2005, 2009 Werner Koch * * 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 3 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, see . */ #include #include #include #include #include #ifdef HAVE_LIBREADLINE # define GNUPG_LIBREADLINE_H_INCLUDED # include #endif /*HAVE_LIBREADLINE*/ #if GNUPG_MAJOR_VERSION != 1 # include "gpg.h" #endif /*GNUPG_MAJOR_VERSION != 1*/ #include "../common/util.h" #include "../common/i18n.h" #include "../common/ttyio.h" #include "../common/status.h" #include "options.h" #include "main.h" #include "keyserver-internal.h" #if GNUPG_MAJOR_VERSION == 1 # include "cardglue.h" #else /*GNUPG_MAJOR_VERSION!=1*/ # include "call-agent.h" #endif /*GNUPG_MAJOR_VERSION!=1*/ #define CONTROL_D ('D' - 'A' + 1) static void write_sc_op_status (gpg_error_t err) { switch (gpg_err_code (err)) { case 0: write_status (STATUS_SC_OP_SUCCESS); break; #if GNUPG_MAJOR_VERSION != 1 case GPG_ERR_CANCELED: case GPG_ERR_FULLY_CANCELED: write_status_text (STATUS_SC_OP_FAILURE, "1"); break; case GPG_ERR_BAD_PIN: write_status_text (STATUS_SC_OP_FAILURE, "2"); break; default: write_status (STATUS_SC_OP_FAILURE); break; #endif /* GNUPG_MAJOR_VERSION != 1 */ } } /* Change the PIN of an OpenPGP card. This is an interactive function. */ void change_pin (int unblock_v2, int allow_admin) { struct agent_card_info_s info; int rc; rc = agent_scd_learn (&info, 0); if (rc) { log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc)); return; } log_info (_("OpenPGP card no. %s detected\n"), info.serialno? info.serialno : "[none]"); if (opt.batch) { agent_release_card_info (&info); log_error (_("can't do this in batch mode\n")); return; } if (unblock_v2) { if (!info.is_v2) log_error (_("This command is only available for version 2 cards\n")); else if (!info.chvretry[1]) log_error (_("Reset Code not or not anymore available\n")); else { rc = agent_scd_change_pin (2, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } } else if (!allow_admin) { rc = agent_scd_change_pin (1, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else for (;;) { char *answer; tty_printf ("\n"); tty_printf ("1 - change PIN\n" "2 - unblock PIN\n" "3 - change Admin PIN\n" "4 - set the Reset Code\n" "Q - quit\n"); tty_printf ("\n"); answer = cpr_get("cardutil.change_pin.menu",_("Your selection? ")); cpr_kill_prompt(); if (strlen (answer) != 1) { xfree (answer); continue; } if (*answer == '1') { /* Change PIN. */ rc = agent_scd_change_pin (1, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else if (*answer == '2') { /* Unblock PIN. */ rc = agent_scd_change_pin (101, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN unblocked and new PIN set.\n"); } else if (*answer == '3') { /* Change Admin PIN. */ rc = agent_scd_change_pin (3, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else if (*answer == '4') { /* Set a new Reset Code. */ rc = agent_scd_change_pin (102, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error setting the Reset Code: %s\n", gpg_strerror (rc)); else tty_printf ("Reset Code set.\n"); } else if (*answer == 'q' || *answer == 'Q') { xfree (answer); break; } xfree (answer); } agent_release_card_info (&info); } static void print_shax_fpr (estream_t fp, const unsigned char *fpr, unsigned int fprlen) { int i; if (fpr) { /* FIXME: Fix formatting for FPRLEN != 20 */ for (i=0; i < fprlen ; i+=2, fpr += 2 ) { if (i == 10 ) tty_fprintf (fp, " "); tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]); } } else tty_fprintf (fp, " [none]"); tty_fprintf (fp, "\n"); } static void print_shax_fpr_colon (estream_t fp, const unsigned char *fpr, unsigned int fprlen) { int i; if (fpr) { for (i=0; i < fprlen ; i++, fpr++) es_fprintf (fp, "%02X", *fpr); } es_putc (':', fp); } static void print_keygrip (estream_t fp, const unsigned char *grp) { int i; if (opt.with_keygrip) { tty_fprintf (fp, " keygrip ....: "); for (i=0; i < 20 ; i++, grp++) tty_fprintf (fp, "%02X", *grp); tty_fprintf (fp, "\n"); } } static void print_name (estream_t fp, const char *text, const char *name) { tty_fprintf (fp, "%s", text); /* FIXME: tty_printf_utf8_string2 eats everything after and including an @ - e.g. when printing an url. */ if (name && *name) { if (fp) print_utf8_buffer2 (fp, name, strlen (name), '\n'); else tty_print_utf8_string2 (NULL, name, strlen (name), 0); } else tty_fprintf (fp, _("[not set]")); tty_fprintf (fp, "\n"); } static void print_isoname (estream_t fp, const char *text, const char *tag, const char *name) { if (opt.with_colons) es_fprintf (fp, "%s:", tag); else tty_fprintf (fp, "%s", text); if (name && *name) { char *p, *given, *buf = xstrdup (name); given = strstr (buf, "<<"); for (p=buf; *p; p++) if (*p == '<') *p = ' '; if (given && given[2]) { *given = 0; given += 2; if (opt.with_colons) es_write_sanitized (fp, given, strlen (given), ":", NULL); else if (fp) print_utf8_buffer2 (fp, given, strlen (given), '\n'); else tty_print_utf8_string2 (NULL, given, strlen (given), 0); if (opt.with_colons) es_putc (':', fp); else if (*buf) tty_fprintf (fp, " "); } if (opt.with_colons) es_write_sanitized (fp, buf, strlen (buf), ":", NULL); else if (fp) print_utf8_buffer2 (fp, buf, strlen (buf), '\n'); else tty_print_utf8_string2 (NULL, buf, strlen (buf), 0); xfree (buf); } else { if (opt.with_colons) es_putc (':', fp); else tty_fprintf (fp, _("[not set]")); } if (opt.with_colons) es_fputs (":\n", fp); else tty_fprintf (fp, "\n"); } /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */ static int fpr_is_zero (const char *fpr, unsigned int fprlen) { int i; for (i=0; i < fprlen && !fpr[i]; i++) ; return (i == fprlen); } /* Return true if the fingerprint FPR consists only of 0xFF. */ static int fpr_is_ff (const char *fpr, unsigned int fprlen) { int i; for (i=0; i < fprlen && fpr[i] == '\xff'; i++) ; return (i == fprlen); } +static void +print_a_version (estream_t fp, const char *prefix, unsigned int value) +{ + unsigned int a, b, c, d; + a = ((value >> 24) & 0xff); + b = ((value >> 16) & 0xff); + c = ((value >> 8) & 0xff); + d = ((value ) & 0xff); + + if (a) + tty_fprintf (fp, "%s %u.%u.%u.%u\n", prefix, a, b, c, d); + else if (b) + tty_fprintf (fp, "%s %u.%u.%u\n", prefix, b, c, d); + else if (c) + tty_fprintf (fp, "%s %u.%u\n", prefix, c, d); + else + tty_fprintf (fp, "%s %u\n", prefix, d); +} + + /* Print all available information about the current card. */ static void current_card_status (ctrl_t ctrl, estream_t fp, char *serialno, size_t serialnobuflen) { struct agent_card_info_s info; PKT_public_key *pk = xcalloc (1, sizeof *pk); kbnode_t keyblock = NULL; int rc; unsigned int uval; const unsigned char *thefpr; unsigned int thefprlen; int i; char *pesc; if (serialno && serialnobuflen) *serialno = 0; rc = agent_scd_learn (&info, 0); if (rc) { if (opt.with_colons) es_fputs ("AID:::\n", fp); log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc)); xfree (pk); return; } if (opt.with_colons) es_fprintf (fp, "Reader:%s:", info.reader? info.reader : ""); else tty_fprintf (fp, "Reader ...........: %s\n", info.reader? info.reader : "[none]"); if (opt.with_colons) es_fprintf (fp, "AID:%s:", info.serialno? info.serialno : ""); else tty_fprintf (fp, "Application ID ...: %s\n", info.serialno? info.serialno : "[none]"); if (!info.serialno || strncmp (info.serialno, "D27600012401", 12) || strlen (info.serialno) != 32 ) { const char *name1, *name2; if (info.apptype && !strcmp (info.apptype, "openpgp")) goto openpgp; else if (info.apptype && !strcmp (info.apptype, "NKS")) { name1 = "netkey"; name2 = "NetKey"; } else if (info.apptype && !strcmp (info.apptype, "DINSIG")) { name1 = "dinsig"; name2 = "DINSIG"; } else if (info.apptype && !strcmp (info.apptype, "P15")) { name1 = "pkcs15"; name2 = "PKCS#15"; } else if (info.apptype && !strcmp (info.apptype, "GELDKARTE")) { name1 = "geldkarte"; name2 = "Geldkarte"; } else if (info.apptype && !strcmp (info.apptype, "PIV")) { name1 = "piv"; name2 = "PIV"; } else { name1 = "unknown"; name2 = "Unknown"; } if (opt.with_colons) es_fprintf (fp, "%s-card:\n", name1); else tty_fprintf (fp, "Application type .: %s\n", name2); agent_release_card_info (&info); xfree (pk); return; } openpgp: if (!serialno) ; else if (strlen (info.serialno)+1 > serialnobuflen) log_error ("serial number longer than expected\n"); else strcpy (serialno, info.serialno); if (opt.with_colons) es_fputs ("openpgp-card:\n", fp); else tty_fprintf (fp, "Application type .: %s\n", "OpenPGP"); if (opt.with_colons) { - es_fprintf (fp, "version:%.4s:\n", info.serialno+12); + if (info.appversion) + es_fprintf (fp, "version:%02u%02u:\n", + (info.appversion >> 8) & 0xff, + info.appversion & 0xff); + else + es_fprintf (fp, "version:%.4s:\n", info.serialno+12); uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18); pesc = (info.manufacturer_name ? percent_escape (info.manufacturer_name, NULL) : NULL); es_fprintf (fp, "vendor:%04x:%s:\n", uval, pesc? pesc:""); xfree (pesc); es_fprintf (fp, "serial:%.8s:\n", info.serialno+20); print_isoname (fp, "Name of cardholder: ", "name", info.disp_name); es_fputs ("lang:", fp); if (info.disp_lang) es_write_sanitized (fp, info.disp_lang, strlen (info.disp_lang), ":", NULL); es_fputs (":\n", fp); es_fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm': info.disp_sex == 2? 'f' : 'u')); es_fputs ("url:", fp); if (info.pubkey_url) es_write_sanitized (fp, info.pubkey_url, strlen (info.pubkey_url), ":", NULL); es_fputs (":\n", fp); es_fputs ("login:", fp); if (info.login_data) es_write_sanitized (fp, info.login_data, strlen (info.login_data), ":", NULL); es_fputs (":\n", fp); es_fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached); for (i=0; i < DIM (info.key_attr); i++) if (info.key_attr[i].algo == PUBKEY_ALGO_RSA) es_fprintf (fp, "keyattr:%d:%d:%u:\n", i+1, info.key_attr[i].algo, info.key_attr[i].nbits); else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA) es_fprintf (fp, "keyattr:%d:%d:%s:\n", i+1, info.key_attr[i].algo, info.key_attr[i].curve); es_fprintf (fp, "maxpinlen:%d:%d:%d:\n", info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]); es_fprintf (fp, "pinretry:%d:%d:%d:\n", info.chvretry[0], info.chvretry[1], info.chvretry[2]); es_fprintf (fp, "sigcount:%lu:::\n", info.sig_counter); if (info.extcap.kdf) { const char *setup; if (info.kdf_do_enabled == 0) setup = "off"; else if (info.kdf_do_enabled == 1) setup = "single"; else setup = "on"; es_fprintf (fp, "kdf:%s:\n", setup); } if (info.extcap.bt) { es_fprintf (fp, "uif:%d:%d:%d:\n", info.uif[0], info.uif[1], info.uif[2]); } for (i=0; i < 4; i++) { if (info.private_do[i]) { es_fprintf (fp, "private_do:%d:", i+1); es_write_sanitized (fp, info.private_do[i], strlen (info.private_do[i]), ":", NULL); es_fputs (":\n", fp); } } es_fputs ("cafpr:", fp); print_shax_fpr_colon (fp, info.cafpr1len? info.cafpr1:NULL, info.cafpr2len); print_shax_fpr_colon (fp, info.cafpr2len? info.cafpr2:NULL, info.cafpr2len); print_shax_fpr_colon (fp, info.cafpr3len? info.cafpr3:NULL, info.cafpr3len); es_putc ('\n', fp); es_fputs ("fpr:", fp); print_shax_fpr_colon (fp, info.fpr1len? info.fpr1:NULL, info.fpr1len); print_shax_fpr_colon (fp, info.fpr2len? info.fpr2:NULL, info.fpr2len); print_shax_fpr_colon (fp, info.fpr3len? info.fpr3:NULL, info.fpr3len); es_putc ('\n', fp); es_fprintf (fp, "fprtime:%lu:%lu:%lu:\n", (unsigned long)info.fpr1time, (unsigned long)info.fpr2time, (unsigned long)info.fpr3time); es_fputs ("grp:", fp); print_shax_fpr_colon (fp, info.grp1, sizeof info.grp1); print_shax_fpr_colon (fp, info.grp2, sizeof info.grp2); print_shax_fpr_colon (fp, info.grp3, sizeof info.grp3); es_putc ('\n', fp); } else { - tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n", + if (info.appversion) + print_a_version (fp, "Version ..........:", info.appversion); + else + tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n", info.serialno[12] == '0'?"":info.serialno+12, info.serialno[13], info.serialno[14] == '0'?"":info.serialno+14, info.serialno[15]); tty_fprintf (fp, "Manufacturer .....: %s\n", info.manufacturer_name? info.manufacturer_name : "?"); tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20); print_isoname (fp, "Name of cardholder: ", "name", info.disp_name); print_name (fp, "Language prefs ...: ", info.disp_lang); tty_fprintf (fp, "Salutation .......: %s\n", info.disp_sex == 1? _("Mr."): info.disp_sex == 2? _("Ms.") : ""); print_name (fp, "URL of public key : ", info.pubkey_url); print_name (fp, "Login data .......: ", info.login_data); if (info.private_do[0]) print_name (fp, "Private DO 1 .....: ", info.private_do[0]); if (info.private_do[1]) print_name (fp, "Private DO 2 .....: ", info.private_do[1]); if (info.private_do[2]) print_name (fp, "Private DO 3 .....: ", info.private_do[2]); if (info.private_do[3]) print_name (fp, "Private DO 4 .....: ", info.private_do[3]); if (info.cafpr1len) { tty_fprintf (fp, "CA fingerprint %d .:", 1); print_shax_fpr (fp, info.cafpr1, info.cafpr1len); } if (info.cafpr2len) { tty_fprintf (fp, "CA fingerprint %d .:", 2); print_shax_fpr (fp, info.cafpr2, info.cafpr2len); } if (info.cafpr3len) { tty_fprintf (fp, "CA fingerprint %d .:", 3); print_shax_fpr (fp, info.cafpr3, info.cafpr3len); } tty_fprintf (fp, "Signature PIN ....: %s\n", info.chv1_cached? _("not forced"): _("forced")); if (info.key_attr[0].algo) { tty_fprintf (fp, "Key attributes ...:"); for (i=0; i < DIM (info.key_attr); i++) if (info.key_attr[i].algo == PUBKEY_ALGO_RSA) tty_fprintf (fp, " rsa%u", info.key_attr[i].nbits); else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA) { const char *curve_for_print = "?"; if (info.key_attr[i].curve) { const char *oid; oid = openpgp_curve_to_oid (info.key_attr[i].curve, NULL, NULL); if (oid) curve_for_print = openpgp_oid_to_curve (oid, 0); } tty_fprintf (fp, " %s", curve_for_print); } tty_fprintf (fp, "\n"); } tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n", info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]); tty_fprintf (fp, "PIN retry counter : %d %d %d\n", info.chvretry[0], info.chvretry[1], info.chvretry[2]); tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter); if (info.extcap.kdf) { const char *setup; if (info.kdf_do_enabled == 0) setup = "off"; else if (info.kdf_do_enabled == 1) setup = "single"; else setup = "on"; tty_fprintf (fp, "KDF setting ......: %s\n", setup); } if (info.extcap.bt) { tty_fprintf (fp, "UIF setting ......: Sign=%s Decrypt=%s Auth=%s\n", info.uif[0] ? "on" : "off", info.uif[1] ? "on" : "off", info.uif[2] ? "on" : "off"); } tty_fprintf (fp, "Signature key ....:"); print_shax_fpr (fp, info.fpr1len? info.fpr1:NULL, info.fpr1len); if (info.fpr1len && info.fpr1time) { tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr1time)); print_keygrip (fp, info.grp1); } tty_fprintf (fp, "Encryption key....:"); print_shax_fpr (fp, info.fpr2len? info.fpr2:NULL, info.fpr2len); if (info.fpr2len && info.fpr2time) { tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr2time)); print_keygrip (fp, info.grp2); } tty_fprintf (fp, "Authentication key:"); print_shax_fpr (fp, info.fpr3len? info.fpr3:NULL, info.fpr3len); if (info.fpr3len && info.fpr3time) { tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr3time)); print_keygrip (fp, info.grp3); } tty_fprintf (fp, "General key info..: "); thefpr = (info.fpr1len? info.fpr1 : info.fpr2len? info.fpr2 : info.fpr3len? info.fpr3 : NULL); thefprlen = (info.fpr1len? info.fpr1len : info.fpr2len? info.fpr2len : info.fpr3len? info.fpr3len : 0); /* If the fingerprint is all 0xff, the key has no associated OpenPGP certificate. */ if ( thefpr && !fpr_is_ff (thefpr, thefprlen) && !get_pubkey_byfprint (ctrl, pk, &keyblock, thefpr, thefprlen)) { print_key_info (ctrl, fp, 0, pk, 0); print_card_key_info (fp, keyblock); } else tty_fprintf (fp, "[none]\n"); } release_kbnode (keyblock); free_public_key (pk); agent_release_card_info (&info); } /* Print all available information for specific card with SERIALNO. Print all available information for current card when SERIALNO is NULL. Or print for all cards when SERIALNO is "all". */ void card_status (ctrl_t ctrl, estream_t fp, const char *serialno) { int err; strlist_t card_list, sl; char *serialno0 = NULL; int all_cards = 0; int any_card = 0; if (serialno == NULL) { current_card_status (ctrl, fp, NULL, 0); return; } if (!strcmp (serialno, "all")) all_cards = 1; err = agent_scd_serialno (&serialno0, NULL); if (err) { if (gpg_err_code (err) != GPG_ERR_ENODEV && opt.verbose) log_info (_("error getting serial number of card: %s\n"), gpg_strerror (err)); /* Nothing available. */ return; } err = agent_scd_cardlist (&card_list); for (sl = card_list; sl; sl = sl->next) { if (!all_cards && strcmp (serialno, sl->d)) continue; if (any_card && !opt.with_colons) tty_fprintf (fp, "\n"); any_card = 1; err = agent_scd_serialno (NULL, sl->d); if (err) { if (opt.verbose) log_info (_("error getting serial number of card: %s\n"), gpg_strerror (err)); continue; } current_card_status (ctrl, fp, NULL, 0); if (!all_cards) goto leave; } /* Select the original card again. */ err = agent_scd_serialno (NULL, serialno0); leave: xfree (serialno0); free_strlist (card_list); } static char * get_one_name (const char *prompt1, const char *prompt2) { char *name; int i; for (;;) { name = cpr_get (prompt1, prompt2); if (!name) return NULL; trim_spaces (name); cpr_kill_prompt (); for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++) ; /* The name must be in Latin-1 and not UTF-8 - lacking the code to ensure this we restrict it to ASCII. */ if (name[i]) tty_printf (_("Error: Only plain ASCII is currently allowed.\n")); else if (strchr (name, '<')) tty_printf (_("Error: The \"<\" character may not be used.\n")); else if (strstr (name, " ")) tty_printf (_("Error: Double spaces are not allowed.\n")); else return name; xfree (name); } } static int change_name (void) { char *surname = NULL, *givenname = NULL; char *isoname = NULL; char *p; int rc; surname = get_one_name ("keygen.smartcard.surname", _("Cardholder's surname: ")); givenname = get_one_name ("keygen.smartcard.givenname", _("Cardholder's given name: ")); if (!surname || !givenname || (!*surname && !*givenname)) { xfree (surname); xfree (givenname); rc = gpg_error (GPG_ERR_CANCELED); goto leave; } isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1); strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname); xfree (surname); xfree (givenname); for (p=isoname; *p; p++) if (*p == ' ') *p = '<'; if (strlen (isoname) > 39 ) { tty_printf (_("Error: Combined name too long " "(limit is %d characters).\n"), 39); xfree (isoname); rc = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname)); if (rc) log_error ("error setting Name: %s\n", gpg_strerror (rc)); leave: xfree (isoname); write_sc_op_status (rc); return rc; } static int change_url (void) { char *url; int rc; url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: ")); if (!url) return -1; trim_spaces (url); cpr_kill_prompt (); rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url)); if (rc) log_error ("error setting URL: %s\n", gpg_strerror (rc)); xfree (url); write_sc_op_status (rc); return rc; } /* Fetch the key from the URL given on the card or try to get it from the default keyserver. */ static int fetch_url (ctrl_t ctrl) { int rc; struct agent_card_info_s info; memset(&info,0,sizeof(info)); rc=agent_scd_getattr("PUBKEY-URL",&info); if(rc) log_error("error retrieving URL from card: %s\n",gpg_strerror(rc)); else { rc=agent_scd_getattr("KEY-FPR",&info); if(rc) log_error("error retrieving key fingerprint from card: %s\n", gpg_strerror(rc)); else if (info.pubkey_url && *info.pubkey_url) { strlist_t sl = NULL; add_to_strlist (&sl, info.pubkey_url); rc = keyserver_fetch (ctrl, sl, KEYORG_URL); free_strlist (sl); } else if (info.fpr1len) { rc = keyserver_import_fprint (ctrl, info.fpr1, info.fpr1len, opt.keyserver, 0); } } agent_release_card_info (&info); return rc; } #define MAX_GET_DATA_FROM_FILE 16384 /* Read data from file FNAME up to MAX_GET_DATA_FROM_FILE characters. On error return -1 and store NULL at R_BUFFER; on success return the number of bytes read and store the address of a newly allocated buffer at R_BUFFER. */ static int get_data_from_file (const char *fname, char **r_buffer) { estream_t fp; char *data; int n; *r_buffer = NULL; fp = es_fopen (fname, "rb"); #if GNUPG_MAJOR_VERSION == 1 if (fp && is_secured_file (fileno (fp))) { fclose (fp); fp = NULL; errno = EPERM; } #endif if (!fp) { tty_printf (_("can't open '%s': %s\n"), fname, strerror (errno)); return -1; } data = xtrymalloc (MAX_GET_DATA_FROM_FILE); if (!data) { tty_printf (_("error allocating enough memory: %s\n"), strerror (errno)); es_fclose (fp); return -1; } n = es_fread (data, 1, MAX_GET_DATA_FROM_FILE, fp); es_fclose (fp); if (n < 0) { tty_printf (_("error reading '%s': %s\n"), fname, strerror (errno)); xfree (data); return -1; } *r_buffer = data; return n; } /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on success. */ static int put_data_to_file (const char *fname, const void *buffer, size_t length) { estream_t fp; fp = es_fopen (fname, "wb"); #if GNUPG_MAJOR_VERSION == 1 if (fp && is_secured_file (fileno (fp))) { fclose (fp); fp = NULL; errno = EPERM; } #endif if (!fp) { tty_printf (_("can't create '%s': %s\n"), fname, strerror (errno)); return -1; } if (length && es_fwrite (buffer, length, 1, fp) != 1) { tty_printf (_("error writing '%s': %s\n"), fname, strerror (errno)); es_fclose (fp); return -1; } es_fclose (fp); return 0; } static int change_login (const char *args) { char *data; int n; int rc; if (args && *args == '<') /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, &data); if (n < 0) return -1; } else { data = cpr_get ("cardedit.change_login", _("Login data (account name): ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); n = strlen (data); } rc = agent_scd_setattr ("LOGIN-DATA", data, n); if (rc) log_error ("error setting login data: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_private_do (const char *args, int nr) { char do_name[] = "PRIVATE-DO-X"; char *data; int n; int rc; log_assert (nr >= 1 && nr <= 4); do_name[11] = '0' + nr; if (args && (args = strchr (args, '<'))) /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, &data); if (n < 0) return -1; } else { data = cpr_get ("cardedit.change_private_do", _("Private DO data: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); n = strlen (data); } rc = agent_scd_setattr (do_name, data, n); if (rc) log_error ("error setting private DO: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_cert (const char *args) { char *data; int n; int rc; if (args && *args == '<') /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, &data); if (n < 0) return -1; } else { tty_printf ("usage error: redirection to file required\n"); return -1; } rc = agent_scd_writecert ("OPENPGP.3", data, n); if (rc) log_error ("error writing certificate to card: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int read_cert (const char *args) { const char *fname; void *buffer; size_t length; int rc; if (args && *args == '>') /* Write it to a file */ { for (args++; spacep (args); args++) ; fname = args; } else { tty_printf ("usage error: redirection to file required\n"); return -1; } rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length); if (rc) log_error ("error reading certificate from card: %s\n", gpg_strerror (rc)); else rc = put_data_to_file (fname, buffer, length); xfree (buffer); write_sc_op_status (rc); return rc; } static int change_lang (void) { char *data, *p; int rc; data = cpr_get ("cardedit.change_lang", _("Language preferences: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); if (strlen (data) > 8 || (strlen (data) & 1)) { tty_printf (_("Error: invalid length of preference string.\n")); xfree (data); return -1; } for (p=data; *p && *p >= 'a' && *p <= 'z'; p++) ; if (*p) { tty_printf (_("Error: invalid characters in preference string.\n")); xfree (data); return -1; } rc = agent_scd_setattr ("DISP-LANG", data, strlen (data)); if (rc) log_error ("error setting lang: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_sex (void) { char *data; const char *str; int rc; data = cpr_get ("cardedit.change_sex", _("Salutation (M = Mr., F = Ms., or space): ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); if (!*data) str = "9"; else if ((*data == 'M' || *data == 'm') && !data[1]) str = "1"; else if ((*data == 'F' || *data == 'f') && !data[1]) str = "2"; else { tty_printf (_("Error: invalid response.\n")); xfree (data); return -1; } rc = agent_scd_setattr ("DISP-SEX", str, 1); if (rc) log_error ("error setting salutation: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_cafpr (int fprno) { char *data; const char *s; int i, c, rc; unsigned char fpr[MAX_FINGERPRINT_LEN]; int fprlen; data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); for (i=0, s=data; i < MAX_FINGERPRINT_LEN && *s; ) { while (spacep(s)) s++; if (*s == ':') s++; while (spacep(s)) s++; c = hextobyte (s); if (c == -1) break; fpr[i++] = c; s += 2; } fprlen = i; xfree (data); if ((fprlen != 20 && fprlen != 32) || *s) { tty_printf (_("Error: invalid formatted fingerprint.\n")); return -1; } rc = agent_scd_setattr (fprno==1?"CA-FPR-1": fprno==2?"CA-FPR-2": fprno==3?"CA-FPR-3":"x", fpr, fprlen); if (rc) log_error ("error setting cafpr: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); return rc; } static void toggle_forcesig (void) { struct agent_card_info_s info; int rc; int newstate; memset (&info, 0, sizeof info); rc = agent_scd_getattr ("CHV-STATUS", &info); if (rc) { log_error ("error getting current status: %s\n", gpg_strerror (rc)); return; } newstate = !info.chv1_cached; agent_release_card_info (&info); rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1); if (rc) log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); } /* Helper for the key generation/edit functions. */ static int get_info_for_key_operation (struct agent_card_info_s *info) { int rc; memset (info, 0, sizeof *info); rc = agent_scd_getattr ("SERIALNO", info); if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12) || strlen (info->serialno) != 32 ) { log_error (_("key operation not possible: %s\n"), rc ? gpg_strerror (rc) : _("not an OpenPGP card")); return rc? rc: -1; } rc = agent_scd_getattr ("KEY-FPR", info); if (!rc) rc = agent_scd_getattr ("CHV-STATUS", info); if (!rc) rc = agent_scd_getattr ("DISP-NAME", info); if (!rc) rc = agent_scd_getattr ("EXTCAP", info); if (!rc) rc = agent_scd_getattr ("KEY-ATTR", info); if (rc) log_error (_("error getting current key info: %s\n"), gpg_strerror (rc)); return rc; } /* Helper for the key generation/edit functions. */ static int check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1) { int rc = 0; *forced_chv1 = !info->chv1_cached; if (*forced_chv1) { /* Switch off the forced mode so that during key generation we don't get bothered with PIN queries for each self-signature. */ rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1); if (rc) { log_error ("error clearing forced signature PIN flag: %s\n", gpg_strerror (rc)); *forced_chv1 = 0; } } if (!rc) { /* Check the PIN now, so that we won't get asked later for each binding signature. */ rc = agent_scd_checkpin (info->serialno); if (rc) { log_error ("error checking the PIN: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); } } return rc; } /* Helper for the key generation/edit functions. */ static void restore_forced_chv1 (int *forced_chv1) { int rc; if (*forced_chv1) { /* Switch back to forced state. */ rc = agent_scd_setattr ("CHV-STATUS-1", "", 1); if (rc) { log_error ("error setting forced signature PIN flag: %s\n", gpg_strerror (rc)); } } } /* Helper for the key generation/edit functions. */ static void show_card_key_info (struct agent_card_info_s *info) { tty_fprintf (NULL, "Signature key ....:"); print_shax_fpr (NULL, info->fpr1len? info->fpr1:NULL, info->fpr1len); tty_fprintf (NULL, "Encryption key....:"); print_shax_fpr (NULL, info->fpr2len? info->fpr2:NULL, info->fpr2len); tty_fprintf (NULL, "Authentication key:"); print_shax_fpr (NULL, info->fpr3len? info->fpr3:NULL, info->fpr3len); tty_printf ("\n"); } /* Helper for the key generation/edit functions. */ static int replace_existing_key_p (struct agent_card_info_s *info, int keyno) { log_assert (keyno >= 0 && keyno <= 3); if ((keyno == 1 && info->fpr1len) || (keyno == 2 && info->fpr2len) || (keyno == 3 && info->fpr3len)) { tty_printf ("\n"); log_info ("WARNING: such a key has already been stored on the card!\n"); tty_printf ("\n"); if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key", _("Replace existing key? (y/N) "))) return -1; return 1; } return 0; } static void show_keysize_warning (void) { static int shown; if (shown) return; shown = 1; tty_printf (_("Note: There is no guarantee that the card supports the requested\n" " key type or size. If the key generation does not succeed,\n" " please check the documentation of your card to see which\n" " key types and sizes are supported.\n") ); } /* Ask for the size of a card key. NBITS is the current size configured for the card. Returns 0 to use the default size (i.e. NBITS) or the selected size. */ static unsigned int ask_card_rsa_keysize (unsigned int nbits) { unsigned int min_nbits = 1024; unsigned int max_nbits = 4096; char *prompt, *answer; unsigned int req_nbits; for (;;) { prompt = xasprintf (_("What keysize do you want? (%u) "), nbits); answer = cpr_get ("cardedit.genkeys.size", prompt); cpr_kill_prompt (); req_nbits = *answer? atoi (answer): nbits; xfree (prompt); xfree (answer); if (req_nbits != nbits && (req_nbits % 32) ) { req_nbits = ((req_nbits + 31) / 32) * 32; tty_printf (_("rounded up to %u bits\n"), req_nbits); } if (req_nbits == nbits) return 0; /* Use default. */ if (req_nbits < min_nbits || req_nbits > max_nbits) { tty_printf (_("%s keysizes must be in the range %u-%u\n"), "RSA", min_nbits, max_nbits); } else return req_nbits; } } /* Ask for the key attribute of a card key. CURRENT is the current attribute configured for the card. KEYNO is the number of the key used to select the prompt. Returns NULL to use the default attribute or the selected attribute structure. */ static struct key_attr * ask_card_keyattr (int keyno, const struct key_attr *current) { struct key_attr *key_attr = NULL; char *answer = NULL; int algo; tty_printf (_("Changing card key attribute for: ")); if (keyno == 0) tty_printf (_("Signature key\n")); else if (keyno == 1) tty_printf (_("Encryption key\n")); else tty_printf (_("Authentication key\n")); tty_printf (_("Please select what kind of key you want:\n")); tty_printf (_(" (%d) RSA\n"), 1 ); tty_printf (_(" (%d) ECC\n"), 2 ); for (;;) { xfree (answer); answer = cpr_get ("cardedit.genkeys.algo", _("Your selection? ")); cpr_kill_prompt (); algo = *answer? atoi (answer) : 0; if (!*answer || algo == 1 || algo == 2) { xfree (answer); break; } else tty_printf (_("Invalid selection.\n")); } if (algo == 0) goto leave; key_attr = xmalloc (sizeof (struct key_attr)); if (algo == 1) { unsigned int nbits, result_nbits; if (current->algo == PUBKEY_ALGO_RSA) nbits = current->nbits; else nbits = 2048; result_nbits = ask_card_rsa_keysize (nbits); if (result_nbits == 0) { if (current->algo == PUBKEY_ALGO_RSA) { xfree (key_attr); key_attr = NULL; } else result_nbits = nbits; } if (key_attr) { key_attr->algo = PUBKEY_ALGO_RSA; key_attr->nbits = result_nbits; } } else { const char *curve; const char *oid_str; if (current->algo == PUBKEY_ALGO_RSA) { if (keyno == 1) /* Encryption key */ algo = PUBKEY_ALGO_ECDH; else /* Signature key or Authentication key */ algo = PUBKEY_ALGO_ECDSA; curve = NULL; } else { algo = current->algo; curve = current->curve; } curve = ask_curve (&algo, NULL, curve); if (curve) { key_attr->algo = algo; oid_str = openpgp_curve_to_oid (curve, NULL, NULL); key_attr->curve = openpgp_oid_to_curve (oid_str, 0); } else { xfree (key_attr); key_attr = NULL; } } leave: if (key_attr) { if (key_attr->algo == PUBKEY_ALGO_RSA) tty_printf (_("The card will now be re-configured" " to generate a key of %u bits\n"), key_attr->nbits); else if (key_attr->algo == PUBKEY_ALGO_ECDH || key_attr->algo == PUBKEY_ALGO_ECDSA || key_attr->algo == PUBKEY_ALGO_EDDSA) tty_printf (_("The card will now be re-configured" " to generate a key of type: %s\n"), key_attr->curve), show_keysize_warning (); } return key_attr; } /* Change the key attribute of key KEYNO (0..2) and show an error * message if that fails. */ static gpg_error_t do_change_keyattr (int keyno, const struct key_attr *key_attr) { gpg_error_t err = 0; char args[100]; if (key_attr->algo == PUBKEY_ALGO_RSA) snprintf (args, sizeof args, "--force %d 1 rsa%u", keyno+1, key_attr->nbits); else if (key_attr->algo == PUBKEY_ALGO_ECDH || key_attr->algo == PUBKEY_ALGO_ECDSA || key_attr->algo == PUBKEY_ALGO_EDDSA) snprintf (args, sizeof args, "--force %d %d %s", keyno+1, key_attr->algo, key_attr->curve); else { log_error (_("public key algorithm %d (%s) is not supported\n"), key_attr->algo, gcry_pk_algo_name (key_attr->algo)); return gpg_error (GPG_ERR_PUBKEY_ALGO); } err = agent_scd_setattr ("KEY-ATTR", args, strlen (args)); if (err) log_error (_("error changing key attribute for key %d: %s\n"), keyno+1, gpg_strerror (err)); return err; } static void key_attr (void) { struct agent_card_info_s info; gpg_error_t err; int keyno; err = get_info_for_key_operation (&info); if (err) { log_error (_("error getting card info: %s\n"), gpg_strerror (err)); return; } if (!(info.is_v2 && info.extcap.aac)) { log_error (_("This command is not supported by this card\n")); goto leave; } for (keyno = 0; keyno < DIM (info.key_attr); keyno++) { struct key_attr *key_attr; if ((key_attr = ask_card_keyattr (keyno, &info.key_attr[keyno]))) { err = do_change_keyattr (keyno, key_attr); xfree (key_attr); if (err) { /* Error: Better read the default key attribute again. */ agent_release_card_info (&info); if (get_info_for_key_operation (&info)) goto leave; /* Ask again for this key. */ keyno--; } } } leave: agent_release_card_info (&info); } static void generate_card_keys (ctrl_t ctrl) { struct agent_card_info_s info; int forced_chv1; int want_backup; if (get_info_for_key_operation (&info)) return; if (info.extcap.ki) { char *answer; /* FIXME: Should be something like cpr_get_bool so that a status GET_BOOL will be emitted. */ answer = cpr_get ("cardedit.genkeys.backup_enc", _("Make off-card backup of encryption key? (Y/n) ")); want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/); cpr_kill_prompt (); xfree (answer); } else want_backup = 0; if ( (info.fpr1len && !fpr_is_zero (info.fpr1, info.fpr1len)) || (info.fpr2len && !fpr_is_zero (info.fpr2, info.fpr2len)) || (info.fpr3len && !fpr_is_zero (info.fpr3, info.fpr3len))) { tty_printf ("\n"); log_info (_("Note: keys are already stored on the card!\n")); tty_printf ("\n"); if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys", _("Replace existing keys? (y/N) "))) { agent_release_card_info (&info); return; } } /* If no displayed name has been set, we assume that this is a fresh card and print a hint about the default PINs. */ if (!info.disp_name || !*info.disp_name) { tty_printf ("\n"); tty_printf (_("Please note that the factory settings of the PINs are\n" " PIN = '%s' Admin PIN = '%s'\n" "You should change them using the command --change-pin\n"), "123456", "12345678"); tty_printf ("\n"); } if (check_pin_for_key_operation (&info, &forced_chv1)) goto leave; generate_keypair (ctrl, 1, NULL, info.serialno, want_backup); leave: agent_release_card_info (&info); restore_forced_chv1 (&forced_chv1); } /* This function is used by the key edit menu to generate an arbitrary subkey. */ gpg_error_t card_generate_subkey (ctrl_t ctrl, kbnode_t pub_keyblock) { gpg_error_t err; struct agent_card_info_s info; int forced_chv1 = 0; int keyno; err = get_info_for_key_operation (&info); if (err) return err; show_card_key_info (&info); tty_printf (_("Please select the type of key to generate:\n")); tty_printf (_(" (1) Signature key\n")); tty_printf (_(" (2) Encryption key\n")); tty_printf (_(" (3) Authentication key\n")); for (;;) { char *answer = cpr_get ("cardedit.genkeys.subkeytype", _("Your selection? ")); cpr_kill_prompt(); if (*answer == CONTROL_D) { xfree (answer); err = gpg_error (GPG_ERR_CANCELED); goto leave; } keyno = *answer? atoi(answer): 0; xfree(answer); if (keyno >= 1 && keyno <= 3) break; /* Okay. */ tty_printf(_("Invalid selection.\n")); } if (replace_existing_key_p (&info, keyno) < 0) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } err = check_pin_for_key_operation (&info, &forced_chv1); if (err) goto leave; err = generate_card_subkeypair (ctrl, pub_keyblock, keyno, info.serialno); leave: agent_release_card_info (&info); restore_forced_chv1 (&forced_chv1); return err; } /* Store the key at NODE into the smartcard and modify NODE to carry the serialno stuff instead of the actual secret key parameters. USE is the usage for that key; 0 means any usage. */ int card_store_subkey (KBNODE node, int use) { struct agent_card_info_s info; int okay = 0; unsigned int nbits; int allow_keyno[3]; int keyno; PKT_public_key *pk; gpg_error_t err; char *hexgrip; int rc; gnupg_isotime_t timebuf; log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY); pk = node->pkt->pkt.public_key; if (get_info_for_key_operation (&info)) return 0; if (!info.extcap.ki) { tty_printf ("The card does not support the import of keys\n"); tty_printf ("\n"); goto leave; } nbits = nbits_from_pk (pk); if (!info.is_v2 && nbits != 1024) { tty_printf ("You may only store a 1024 bit RSA key on the card\n"); tty_printf ("\n"); goto leave; } allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_CERT))); allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC))); allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH))); tty_printf (_("Please select where to store the key:\n")); if (allow_keyno[0]) tty_printf (_(" (1) Signature key\n")); if (allow_keyno[1]) tty_printf (_(" (2) Encryption key\n")); if (allow_keyno[2]) tty_printf (_(" (3) Authentication key\n")); for (;;) { char *answer = cpr_get ("cardedit.genkeys.storekeytype", _("Your selection? ")); cpr_kill_prompt(); if (*answer == CONTROL_D || !*answer) { xfree (answer); goto leave; } keyno = *answer? atoi(answer): 0; xfree(answer); if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1]) { if (info.is_v2 && !info.extcap.aac && info.key_attr[keyno-1].nbits != nbits) { tty_printf ("Key does not match the card's capability.\n"); } else break; /* Okay. */ } else tty_printf(_("Invalid selection.\n")); } if ((rc = replace_existing_key_p (&info, keyno)) < 0) goto leave; err = hexkeygrip_from_pk (pk, &hexgrip); if (err) goto leave; epoch2isotime (timebuf, (time_t)pk->timestamp); rc = agent_keytocard (hexgrip, keyno, rc, info.serialno, timebuf); if (rc) log_error (_("KEYTOCARD failed: %s\n"), gpg_strerror (rc)); else okay = 1; xfree (hexgrip); leave: agent_release_card_info (&info); return okay; } /* Direct sending of an hex encoded APDU with error printing. */ static gpg_error_t send_apdu (const char *hexapdu, const char *desc, unsigned int ignore) { gpg_error_t err; unsigned int sw; err = agent_scd_apdu (hexapdu, &sw); if (err) tty_printf ("sending card command %s failed: %s\n", desc, gpg_strerror (err)); else if (!hexapdu || !strcmp (hexapdu, "undefined") || !strcmp (hexapdu, "reset-keep-lock") || !strcmp (hexapdu, "lock") || !strcmp (hexapdu, "trylock") || !strcmp (hexapdu, "unlock")) ; /* Ignore pseudo APDUs. */ else if (ignore == 0xffff) ; /* Ignore all status words. */ else if (sw != 0x9000) { switch (sw) { case 0x6285: err = gpg_error (GPG_ERR_OBJ_TERM_STATE); break; case 0x6982: err = gpg_error (GPG_ERR_BAD_PIN); break; case 0x6985: err = gpg_error (GPG_ERR_USE_CONDITIONS); break; default: err = gpg_error (GPG_ERR_CARD); } if (!(ignore && ignore == sw)) tty_printf ("card command %s failed: %s (0x%04x)\n", desc, gpg_strerror (err), sw); } return err; } /* Do a factory reset after confirmation. */ static void factory_reset (void) { struct agent_card_info_s info; gpg_error_t err; char *answer = NULL; int termstate = 0; int i; int locked = 0; /* The code below basically does the same what this gpg-connect-agent script does: scd reset scd serialno undefined scd apdu 00 A4 04 00 06 D2 76 00 01 24 01 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 scd apdu 00 e6 00 00 scd apdu 00 44 00 00 scd reset /echo Card has been reset to factory defaults but tries to find out something about the card first. */ err = agent_scd_learn (&info, 0); if (gpg_err_code (err) == GPG_ERR_OBJ_TERM_STATE && gpg_err_source (err) == GPG_ERR_SOURCE_SCD) termstate = 1; else if (err) { log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err)); goto leave; } if (!termstate) { log_info (_("OpenPGP card no. %s detected\n"), info.serialno? info.serialno : "[none]"); if (!(info.status_indicator == 3 || info.status_indicator == 5)) { /* Note: We won't see status-indicator 3 here because it is not possible to select a card application in termination state. */ log_error (_("This command is not supported by this card\n")); goto leave; } tty_printf ("\n"); log_info (_("Note: This command destroys all keys stored on the card!\n")); tty_printf ("\n"); if (!cpr_get_answer_is_yes ("cardedit.factory-reset.proceed", _("Continue? (y/N) "))) goto leave; answer = cpr_get ("cardedit.factory-reset.really", _("Really do a factory reset? (enter \"yes\") ")); cpr_kill_prompt (); trim_spaces (answer); if (strcmp (answer, "yes")) goto leave; /* We need to select a card application before we can send APDUs to the card without scdaemon doing anything on its own. We then lock the connection so that other tools (e.g. Kleopatra) don't try a new select. */ err = send_apdu ("lock", "locking connection ", 0); if (err) goto leave; locked = 1; err = send_apdu ("reset-keep-lock", "reset", 0); if (err) goto leave; err = send_apdu ("undefined", "dummy select ", 0); if (err) goto leave; /* Select the OpenPGP application. */ err = send_apdu ("00A4040006D27600012401", "SELECT AID", 0); if (err) goto leave; /* Do some dummy verifies with wrong PINs to set the retry counter to zero. We can't easily use the card version 2.1 feature of presenting the admin PIN to allow the terminate command because there is no machinery in scdaemon to catch the verify command and ask for the PIN when the "APDU" command is used. */ /* Here, the length of dummy wrong PIN is 32-byte, also supporting authentication with KDF DO. */ for (i=0; i < 4; i++) send_apdu ("0020008120" "40404040404040404040404040404040" "40404040404040404040404040404040", "VERIFY", 0xffff); for (i=0; i < 4; i++) send_apdu ("0020008320" "40404040404040404040404040404040" "40404040404040404040404040404040", "VERIFY", 0xffff); /* Send terminate datafile command. */ err = send_apdu ("00e60000", "TERMINATE DF", 0x6985); if (err) goto leave; } /* Send activate datafile command. This is used without confirmation if the card is already in termination state. */ err = send_apdu ("00440000", "ACTIVATE DF", 0); if (err) goto leave; /* Finally we reset the card reader once more. */ err = send_apdu ("reset-keep-lock", "reset", 0); /* Then, connect the card again. */ if (!err) err = agent_scd_serialno (NULL, NULL); leave: if (locked) send_apdu ("unlock", "unlocking connection ", 0); xfree (answer); agent_release_card_info (&info); } #define USER_PIN_DEFAULT "123456" #define ADMIN_PIN_DEFAULT "12345678" #define KDF_DATA_LENGTH_MIN 90 #define KDF_DATA_LENGTH_MAX 110 /* Generate KDF data. */ static gpg_error_t gen_kdf_data (unsigned char *data, int single_salt) { const unsigned char h0[] = { 0x81, 0x01, 0x03, 0x82, 0x01, 0x08, 0x83, 0x04 }; const unsigned char h1[] = { 0x84, 0x08 }; const unsigned char h2[] = { 0x85, 0x08 }; const unsigned char h3[] = { 0x86, 0x08 }; const unsigned char h4[] = { 0x87, 0x20 }; const unsigned char h5[] = { 0x88, 0x20 }; unsigned char *p, *salt_user, *salt_admin; unsigned char s2k_char; unsigned int iterations; unsigned char count_4byte[4]; gpg_error_t err = 0; p = data; s2k_char = encode_s2k_iterations (agent_get_s2k_count ()); iterations = S2K_DECODE_COUNT (s2k_char); count_4byte[0] = (iterations >> 24) & 0xff; count_4byte[1] = (iterations >> 16) & 0xff; count_4byte[2] = (iterations >> 8) & 0xff; count_4byte[3] = (iterations & 0xff); memcpy (p, h0, sizeof h0); p += sizeof h0; memcpy (p, count_4byte, sizeof count_4byte); p += sizeof count_4byte; memcpy (p, h1, sizeof h1); salt_user = (p += sizeof h1); gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; if (single_salt) salt_admin = salt_user; else { memcpy (p, h2, sizeof h2); p += sizeof h2; gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; memcpy (p, h3, sizeof h3); salt_admin = (p += sizeof h3); gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; } memcpy (p, h4, sizeof h4); p += sizeof h4; err = gcry_kdf_derive (USER_PIN_DEFAULT, strlen (USER_PIN_DEFAULT), GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256, salt_user, 8, iterations, 32, p); p += 32; if (!err) { memcpy (p, h5, sizeof h5); p += sizeof h5; err = gcry_kdf_derive (ADMIN_PIN_DEFAULT, strlen (ADMIN_PIN_DEFAULT), GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256, salt_admin, 8, iterations, 32, p); } return err; } /* Setup KDF data object which is used for PIN authentication. */ static void kdf_setup (const char *args) { struct agent_card_info_s info; gpg_error_t err; unsigned char kdf_data[KDF_DATA_LENGTH_MAX]; size_t len; memset (&info, 0, sizeof info); err = agent_scd_getattr ("EXTCAP", &info); if (err) { log_error (_("error getting card info: %s\n"), gpg_strerror (err)); return; } if (!info.extcap.kdf) { log_error (_("This command is not supported by this card\n")); goto leave; } if (!strcmp (args, "off")) { len = 3; memcpy (kdf_data, "\x81\x01\x00", len); } else { int single = 0; if (*args != 0) single = 1; len = single ? KDF_DATA_LENGTH_MIN: KDF_DATA_LENGTH_MAX; err = gen_kdf_data (kdf_data, single); if (err) goto leave_error; } err = agent_scd_setattr ("KDF", kdf_data, len); if (err) goto leave_error; err = agent_scd_getattr ("KDF", &info); leave_error: if (err) log_error (_("error for setup KDF: %s\n"), gpg_strerror (err)); leave: agent_release_card_info (&info); } static void uif (int arg_number, const char *arg_rest) { struct agent_card_info_s info; int feature_available; gpg_error_t err; char name[100]; unsigned char data[2]; memset (&info, 0, sizeof info); err = agent_scd_getattr ("EXTCAP", &info); if (err) { log_error (_("error getting card info: %s\n"), gpg_strerror (err)); return; } feature_available = info.extcap.bt; agent_release_card_info (&info); if (!feature_available) { log_error (_("This command is not supported by this card\n")); tty_printf ("\n"); return; } snprintf (name, sizeof name, "UIF-%d", arg_number); if ( !strcmp (arg_rest, "off") ) data[0] = 0x00; else if ( !strcmp (arg_rest, "on") ) data[0] = 0x01; else if ( !strcmp (arg_rest, "permanent") ) data[0] = 0x02; data[1] = 0x20; err = agent_scd_setattr (name, data, 2); if (err) log_error (_("error for setup UIF: %s\n"), gpg_strerror (err)); } /* Data used by the command parser. This needs to be outside of the function scope to allow readline based command completion. */ enum cmdids { cmdNOP = 0, cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY, cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR, cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT, cmdREADCERT, cmdUNBLOCK, cmdFACTORYRESET, cmdKDFSETUP, cmdKEYATTR, cmdUIF, cmdINVCMD }; static struct { const char *name; enum cmdids id; int admin_only; const char *desc; } cmds[] = { { "quit" , cmdQUIT , 0, N_("quit this menu")}, { "q" , cmdQUIT , 0, NULL }, { "admin" , cmdADMIN , 0, N_("show admin commands")}, { "help" , cmdHELP , 0, N_("show this help")}, { "?" , cmdHELP , 0, NULL }, { "list" , cmdLIST , 0, N_("list all available data")}, { "l" , cmdLIST , 0, NULL }, { "debug" , cmdDEBUG , 0, NULL }, { "name" , cmdNAME , 1, N_("change card holder's name")}, { "url" , cmdURL , 1, N_("change URL to retrieve key")}, { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")}, { "login" , cmdLOGIN , 1, N_("change the login name")}, { "lang" , cmdLANG , 1, N_("change the language preferences")}, { "salutation",cmdSEX , 1, N_("change card holder's salutation")}, { "sex" ,cmdSEX , 1, NULL }, /* Backward compatibility. */ { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")}, { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")}, { "generate", cmdGENERATE, 1, N_("generate new keys")}, { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")}, { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")}, { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code")}, { "factory-reset", cmdFACTORYRESET, 1, N_("destroy all keys and data")}, { "kdf-setup", cmdKDFSETUP, 1, N_("setup KDF for PIN authentication (on/single/off)")}, { "key-attr", cmdKEYATTR, 1, N_("change the key attribute")}, { "uif", cmdUIF, 1, N_("change the User Interaction Flag")}, /* Note, that we do not announce these command yet. */ { "privatedo", cmdPRIVATEDO, 0, NULL }, { "readcert", cmdREADCERT, 0, NULL }, { "writecert", cmdWRITECERT, 1, NULL }, { NULL, cmdINVCMD, 0, NULL } }; #ifdef HAVE_LIBREADLINE /* These two functions are used by readline for command completion. */ static char * command_generator(const char *text,int state) { static int list_index,len; const char *name; /* If this is a new word to complete, initialize now. This includes saving the length of TEXT for efficiency, and initializing the index variable to 0. */ if(!state) { list_index=0; len=strlen(text); } /* Return the next partial match */ while((name=cmds[list_index].name)) { /* Only complete commands that have help text */ if(cmds[list_index++].desc && strncmp(name,text,len)==0) return strdup(name); } return NULL; } static char ** card_edit_completion(const char *text, int start, int end) { (void)end; /* If we are at the start of a line, we try and command-complete. If not, just do nothing for now. */ if(start==0) return rl_completion_matches(text,command_generator); rl_attempted_completion_over=1; return NULL; } #endif /*HAVE_LIBREADLINE*/ /* Menu to edit all user changeable values on an OpenPGP card. Only Key creation is not handled here. */ void card_edit (ctrl_t ctrl, strlist_t commands) { enum cmdids cmd = cmdNOP; int have_commands = !!commands; int redisplay = 1; char *answer = NULL; int allow_admin=0; char serialnobuf[50]; if (opt.command_fd != -1) ; else if (opt.batch && !have_commands) { log_error(_("can't do this in batch mode\n")); goto leave; } for (;;) { int arg_number; const char *arg_string = ""; const char *arg_rest = ""; char *p; int i; int cmd_admin_only; tty_printf("\n"); if (redisplay) { if (opt.with_colons) { current_card_status (ctrl, es_stdout, serialnobuf, DIM (serialnobuf)); fflush (stdout); } else { current_card_status (ctrl, NULL, serialnobuf, DIM (serialnobuf)); tty_printf("\n"); } redisplay = 0; } do { xfree (answer); if (have_commands) { if (commands) { answer = xstrdup (commands->d); commands = commands->next; } else if (opt.batch) { answer = xstrdup ("quit"); } else have_commands = 0; } if (!have_commands) { tty_enable_completion (card_edit_completion); answer = cpr_get_no_help("cardedit.prompt", _("gpg/card> ")); cpr_kill_prompt(); tty_disable_completion (); } trim_spaces(answer); } while ( *answer == '#' ); arg_number = 0; /* Yes, here is the init which egcc complains about */ cmd_admin_only = 0; if (!*answer) cmd = cmdLIST; /* Default to the list command */ else if (*answer == CONTROL_D) cmd = cmdQUIT; else { if ((p=strchr (answer,' '))) { *p++ = 0; trim_spaces (answer); trim_spaces (p); arg_number = atoi(p); arg_string = p; arg_rest = p; while (digitp (arg_rest)) arg_rest++; while (spacep (arg_rest)) arg_rest++; } for (i=0; cmds[i].name; i++ ) if (!ascii_strcasecmp (answer, cmds[i].name )) break; cmd = cmds[i].id; cmd_admin_only = cmds[i].admin_only; } if (!allow_admin && cmd_admin_only) { tty_printf ("\n"); tty_printf (_("Admin-only command\n")); continue; } switch (cmd) { case cmdHELP: for (i=0; cmds[i].name; i++ ) if(cmds[i].desc && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin))) tty_printf("%-14s %s\n", cmds[i].name, _(cmds[i].desc) ); break; case cmdADMIN: if ( !strcmp (arg_string, "on") ) allow_admin = 1; else if ( !strcmp (arg_string, "off") ) allow_admin = 0; else if ( !strcmp (arg_string, "verify") ) { /* Force verification of the Admin Command. However, this is only done if the retry counter is at initial state. */ char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1); strcpy (stpcpy (tmp, serialnobuf), "[CHV3]"); allow_admin = !agent_scd_checkpin (tmp); xfree (tmp); } else /* Toggle. */ allow_admin=!allow_admin; if(allow_admin) tty_printf(_("Admin commands are allowed\n")); else tty_printf(_("Admin commands are not allowed\n")); break; case cmdVERIFY: agent_scd_checkpin (serialnobuf); redisplay = 1; break; case cmdLIST: redisplay = 1; break; case cmdNAME: change_name (); break; case cmdURL: change_url (); break; case cmdFETCH: fetch_url (ctrl); break; case cmdLOGIN: change_login (arg_string); break; case cmdLANG: change_lang (); break; case cmdSEX: change_sex (); break; case cmdCAFPR: if ( arg_number < 1 || arg_number > 3 ) tty_printf ("usage: cafpr N\n" " 1 <= N <= 3\n"); else change_cafpr (arg_number); break; case cmdPRIVATEDO: if ( arg_number < 1 || arg_number > 4 ) tty_printf ("usage: privatedo N\n" " 1 <= N <= 4\n"); else change_private_do (arg_string, arg_number); break; case cmdWRITECERT: if ( arg_number != 3 ) tty_printf ("usage: writecert 3 < FILE\n"); else change_cert (arg_rest); break; case cmdREADCERT: if ( arg_number != 3 ) tty_printf ("usage: readcert 3 > FILE\n"); else read_cert (arg_rest); break; case cmdFORCESIG: toggle_forcesig (); break; case cmdGENERATE: generate_card_keys (ctrl); break; case cmdPASSWD: change_pin (0, allow_admin); break; case cmdUNBLOCK: change_pin (1, allow_admin); break; case cmdFACTORYRESET: factory_reset (); break; case cmdKDFSETUP: kdf_setup (arg_string); break; case cmdKEYATTR: key_attr (); break; case cmdUIF: if ( arg_number < 1 || arg_number > 3 ) tty_printf ("usage: uif N [on|off|permanent]\n" " 1 <= N <= 3\n"); else uif (arg_number, arg_rest); break; case cmdQUIT: goto leave; case cmdNOP: break; case cmdINVCMD: default: tty_printf ("\n"); tty_printf (_("Invalid command (try \"help\")\n")); break; } /* End command switch. */ } /* End of main menu loop. */ leave: xfree (answer); }