diff --git a/sm/encrypt.c b/sm/encrypt.c index f90a4449b..331bfa8ba 100644 --- a/sm/encrypt.c +++ b/sm/encrypt.c @@ -1,578 +1,579 @@ /* encrypt.c - Encrypt a message * Copyright (C) 2001, 2003, 2004, 2007, 2008, * 2010 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 . */ #include #include #include #include #include #include #include #include #include "gpgsm.h" #include #include #include "keydb.h" #include "../common/i18n.h" #include "../common/compliance.h" struct dek_s { const char *algoid; int algo; gcry_cipher_hd_t chd; char key[32]; int keylen; char iv[32]; int ivlen; }; typedef struct dek_s *DEK; /* Callback parameters for the encryption. */ struct encrypt_cb_parm_s { estream_t fp; DEK dek; int eof_seen; int ready; int readerror; int bufsize; unsigned char *buffer; int buflen; }; /* Initialize the data encryption key (session key). */ static int init_dek (DEK dek) { int rc=0, mode, i; dek->algo = gcry_cipher_map_name (dek->algoid); mode = gcry_cipher_mode_from_oid (dek->algoid); if (!dek->algo || !mode) { log_error ("unsupported algorithm '%s'\n", dek->algoid); return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); } /* Extra check for algorithms we consider to be too weak for encryption, although we support them for decryption. Note that there is another check below discriminating on the key length. */ switch (dek->algo) { case GCRY_CIPHER_DES: case GCRY_CIPHER_RFC2268_40: log_error ("cipher algorithm '%s' not allowed: too weak\n", gnupg_cipher_algo_name (dek->algo)); return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); default: break; } dek->keylen = gcry_cipher_get_algo_keylen (dek->algo); if (!dek->keylen || dek->keylen > sizeof (dek->key)) return gpg_error (GPG_ERR_BUG); dek->ivlen = gcry_cipher_get_algo_blklen (dek->algo); if (!dek->ivlen || dek->ivlen > sizeof (dek->iv)) return gpg_error (GPG_ERR_BUG); /* Make sure we don't use weak keys. */ if (dek->keylen < 100/8) { log_error ("key length of '%s' too small\n", dek->algoid); return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); } rc = gcry_cipher_open (&dek->chd, dek->algo, mode, GCRY_CIPHER_SECURE); if (rc) { log_error ("failed to create cipher context: %s\n", gpg_strerror (rc)); return rc; } for (i=0; i < 8; i++) { gcry_randomize (dek->key, dek->keylen, GCRY_STRONG_RANDOM ); rc = gcry_cipher_setkey (dek->chd, dek->key, dek->keylen); if (gpg_err_code (rc) != GPG_ERR_WEAK_KEY) break; log_info(_("weak key created - retrying\n") ); } if (rc) { log_error ("failed to set the key: %s\n", gpg_strerror (rc)); gcry_cipher_close (dek->chd); dek->chd = NULL; return rc; } gcry_create_nonce (dek->iv, dek->ivlen); rc = gcry_cipher_setiv (dek->chd, dek->iv, dek->ivlen); if (rc) { log_error ("failed to set the IV: %s\n", gpg_strerror (rc)); gcry_cipher_close (dek->chd); dek->chd = NULL; return rc; } return 0; } static int encode_session_key (DEK dek, gcry_sexp_t * r_data) { gcry_sexp_t data; char *p; int rc; p = xtrymalloc (64 + 2 * dek->keylen); if (!p) return gpg_error_from_syserror (); strcpy (p, "(data\n (flags pkcs1)\n (value #"); bin2hex (dek->key, dek->keylen, p + strlen (p)); strcat (p, "#))\n"); rc = gcry_sexp_sscan (&data, NULL, p, strlen (p)); xfree (p); *r_data = data; return rc; } /* Encrypt the DEK under the key contained in CERT and return it as a canonical S-Exp in encval. */ static int encrypt_dek (const DEK dek, ksba_cert_t cert, unsigned char **encval) { gcry_sexp_t s_ciph, s_data, s_pkey; int rc; ksba_sexp_t buf; size_t len; *encval = NULL; /* get the key from the cert */ buf = ksba_cert_get_public_key (cert); if (!buf) { log_error ("no public key for recipient\n"); return gpg_error (GPG_ERR_NO_PUBKEY); } len = gcry_sexp_canon_len (buf, 0, NULL, NULL); if (!len) { log_error ("libksba did not return a proper S-Exp\n"); return gpg_error (GPG_ERR_BUG); } rc = gcry_sexp_sscan (&s_pkey, NULL, (char*)buf, len); xfree (buf); buf = NULL; if (rc) { log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (rc)); return rc; } /* Put the encoded cleartext into a simple list. */ s_data = NULL; /* (avoid compiler warning) */ rc = encode_session_key (dek, &s_data); if (rc) { log_error ("encode_session_key failed: %s\n", gpg_strerror (rc)); return rc; } /* pass it to libgcrypt */ rc = gcry_pk_encrypt (&s_ciph, s_data, s_pkey); gcry_sexp_release (s_data); gcry_sexp_release (s_pkey); /* Reformat it. */ if (!rc) { rc = make_canon_sexp (s_ciph, encval, NULL); gcry_sexp_release (s_ciph); } return rc; } /* do the actual encryption */ static int encrypt_cb (void *cb_value, char *buffer, size_t count, size_t *nread) { struct encrypt_cb_parm_s *parm = cb_value; int blklen = parm->dek->ivlen; unsigned char *p; size_t n; *nread = 0; if (!buffer) return -1; /* not supported */ if (parm->ready) return -1; if (count < blklen) BUG (); if (!parm->eof_seen) { /* fillup the buffer */ p = parm->buffer; for (n=parm->buflen; n < parm->bufsize; n++) { int c = es_getc (parm->fp); if (c == EOF) { if (es_ferror (parm->fp)) { parm->readerror = errno; return -1; } parm->eof_seen = 1; break; } p[n] = c; } parm->buflen = n; } n = parm->buflen < count? parm->buflen : count; n = n/blklen * blklen; if (n) { /* encrypt the stuff */ gcry_cipher_encrypt (parm->dek->chd, buffer, n, parm->buffer, n); *nread = n; /* Who cares about cycles, take the easy way and shift the buffer */ parm->buflen -= n; memmove (parm->buffer, parm->buffer+n, parm->buflen); } else if (parm->eof_seen) { /* no complete block but eof: add padding */ /* fixme: we should try to do this also in the above code path */ int i, npad = blklen - (parm->buflen % blklen); p = parm->buffer; for (n=parm->buflen, i=0; n < parm->bufsize && i < npad; n++, i++) p[n] = npad; gcry_cipher_encrypt (parm->dek->chd, buffer, n, parm->buffer, n); *nread = n; parm->ready = 1; } return 0; } /* Perform an encrypt operation. Encrypt the data received on DATA-FD and write it to OUT_FP. The recipients are take from the certificate given in recplist; if this is NULL it will be encrypted for a default recipient */ int gpgsm_encrypt (ctrl_t ctrl, certlist_t recplist, int data_fd, estream_t out_fp) { int rc = 0; gnupg_ksba_io_t b64writer = NULL; gpg_error_t err; ksba_writer_t writer; ksba_reader_t reader = NULL; ksba_cms_t cms = NULL; ksba_stop_reason_t stopreason; KEYDB_HANDLE kh = NULL; struct encrypt_cb_parm_s encparm; DEK dek = NULL; int recpno; estream_t data_fp = NULL; certlist_t cl; int count; int compliant; memset (&encparm, 0, sizeof encparm); audit_set_type (ctrl->audit, AUDIT_TYPE_ENCRYPT); /* Check that the certificate list is not empty and that at least one certificate is not flagged as encrypt_to; i.e. is a real recipient. */ for (cl = recplist; cl; cl = cl->next) if (!cl->is_encrypt_to) break; if (!cl) { log_error(_("no valid recipients given\n")); gpgsm_status (ctrl, STATUS_NO_RECP, "0"); audit_log_i (ctrl->audit, AUDIT_GOT_RECIPIENTS, 0); rc = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } for (count = 0, cl = recplist; cl; cl = cl->next) count++; audit_log_i (ctrl->audit, AUDIT_GOT_RECIPIENTS, count); kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } /* Fixme: We should use the unlocked version of the es functions. */ data_fp = es_fdopen_nc (data_fd, "rb"); if (!data_fp) { rc = gpg_error_from_syserror (); log_error ("fdopen() failed: %s\n", strerror (errno)); goto leave; } err = ksba_reader_new (&reader); if (err) rc = err; if (!rc) rc = ksba_reader_set_cb (reader, encrypt_cb, &encparm); if (rc) goto leave; encparm.fp = data_fp; ctrl->pem_name = "ENCRYPTED MESSAGE"; rc = gnupg_ksba_create_writer (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0) | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)), ctrl->pem_name, out_fp, &writer); if (rc) { log_error ("can't create writer: %s\n", gpg_strerror (rc)); goto leave; } err = ksba_cms_new (&cms); if (err) { rc = err; goto leave; } err = ksba_cms_set_reader_writer (cms, reader, writer); if (err) { log_debug ("ksba_cms_set_reader_writer failed: %s\n", gpg_strerror (err)); rc = err; goto leave; } audit_log (ctrl->audit, AUDIT_GOT_DATA); /* We are going to create enveloped data with uninterpreted data as inner content */ err = ksba_cms_set_content_type (cms, 0, KSBA_CT_ENVELOPED_DATA); if (!err) err = ksba_cms_set_content_type (cms, 1, KSBA_CT_DATA); if (err) { log_debug ("ksba_cms_set_content_type failed: %s\n", gpg_strerror (err)); rc = err; goto leave; } /* Check compliance. */ if (!gnupg_cipher_is_allowed (opt.compliance, 1, gcry_cipher_map_name (opt.def_cipher_algoid), gcry_cipher_mode_from_oid (opt.def_cipher_algoid))) { log_error (_("cipher algorithm '%s' may not be used in %s mode\n"), opt.def_cipher_algoid, gnupg_compliance_option_string (opt.compliance)); rc = gpg_error (GPG_ERR_CIPHER_ALGO); goto leave; } if (!gnupg_rng_is_compliant (opt.compliance)) { rc = gpg_error (GPG_ERR_FORBIDDEN); log_error (_("%s is not compliant with %s mode\n"), "RNG", gnupg_compliance_option_string (opt.compliance)); gpgsm_status_with_error (ctrl, STATUS_ERROR, "random-compliance", rc); goto leave; } /* Create a session key */ dek = xtrycalloc_secure (1, sizeof *dek); if (!dek) rc = out_of_core (); else { dek->algoid = opt.def_cipher_algoid; rc = init_dek (dek); } if (rc) { log_error ("failed to create the session key: %s\n", gpg_strerror (rc)); goto leave; } err = ksba_cms_set_content_enc_algo (cms, dek->algoid, dek->iv, dek->ivlen); if (err) { log_error ("ksba_cms_set_content_enc_algo failed: %s\n", gpg_strerror (err)); rc = err; goto leave; } encparm.dek = dek; /* Use a ~8k (AES) or ~4k (3DES) buffer */ encparm.bufsize = 500 * dek->ivlen; encparm.buffer = xtrymalloc (encparm.bufsize); if (!encparm.buffer) { rc = out_of_core (); goto leave; } audit_log_s (ctrl->audit, AUDIT_SESSION_KEY, dek->algoid); compliant = gnupg_cipher_is_compliant (CO_DE_VS, dek->algo, GCRY_CIPHER_MODE_CBC); /* Gather certificates of recipients, encrypt the session key for each and store them in the CMS object */ for (recpno = 0, cl = recplist; cl; recpno++, cl = cl->next) { unsigned char *encval; unsigned int nbits; int pk_algo; /* Check compliance. */ pk_algo = gpgsm_get_key_algo_info (cl->cert, &nbits); if (!gnupg_pk_is_compliant (opt.compliance, pk_algo, 0, NULL, nbits, NULL)) { char kidstr[10+1]; snprintf (kidstr, sizeof kidstr, "0x%08lX", gpgsm_get_short_fingerprint (cl->cert, NULL)); log_info (_("WARNING: key %s is not suitable for encryption" " in %s mode\n"), kidstr, gnupg_compliance_option_string (opt.compliance)); } /* Fixme: When adding ECC we need to provide the curvename and * the key to gnupg_pk_is_compliant. */ if (compliant && !gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0, NULL, nbits, NULL)) compliant = 0; rc = encrypt_dek (dek, cl->cert, &encval); if (rc) { audit_log_cert (ctrl->audit, AUDIT_ENCRYPTED_TO, cl->cert, rc); log_error ("encryption failed for recipient no. %d: %s\n", recpno, gpg_strerror (rc)); goto leave; } err = ksba_cms_add_recipient (cms, cl->cert); if (err) { audit_log_cert (ctrl->audit, AUDIT_ENCRYPTED_TO, cl->cert, err); log_error ("ksba_cms_add_recipient failed: %s\n", gpg_strerror (err)); rc = err; xfree (encval); goto leave; } err = ksba_cms_set_enc_val (cms, recpno, encval); xfree (encval); audit_log_cert (ctrl->audit, AUDIT_ENCRYPTED_TO, cl->cert, err); if (err) { log_error ("ksba_cms_set_enc_val failed: %s\n", gpg_strerror (err)); rc = err; goto leave; } } if (compliant && gnupg_gcrypt_is_compliant (CO_DE_VS)) gpgsm_status (ctrl, STATUS_ENCRYPTION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS)); /* Main control loop for encryption. */ recpno = 0; do { err = ksba_cms_build (cms, &stopreason); if (err) { log_debug ("ksba_cms_build failed: %s\n", gpg_strerror (err)); rc = err; goto leave; } } while (stopreason != KSBA_SR_READY); if (encparm.readerror) { log_error ("error reading input: %s\n", strerror (encparm.readerror)); rc = gpg_error (gpg_err_code_from_errno (encparm.readerror)); goto leave; } rc = gnupg_ksba_finish_writer (b64writer); if (rc) { log_error ("write failed: %s\n", gpg_strerror (rc)); goto leave; } audit_log (ctrl->audit, AUDIT_ENCRYPTION_DONE); - log_info ("encrypted data created\n"); + if (!opt.quiet) + log_info ("encrypted data created\n"); leave: ksba_cms_release (cms); gnupg_ksba_destroy_writer (b64writer); ksba_reader_release (reader); keydb_release (kh); xfree (dek); es_fclose (data_fp); xfree (encparm.buffer); return rc; } diff --git a/sm/gpgsm.c b/sm/gpgsm.c index 55a92c629..0baf8de38 100644 --- a/sm/gpgsm.c +++ b/sm/gpgsm.c @@ -1,2321 +1,2326 @@ /* gpgsm.c - GnuPG for S/MIME * Copyright (C) 2001-2020 Free Software Foundation, Inc. * Copyright (C) 2001-2019 Werner Koch * Copyright (C) 2015-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 . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #define INCLUDED_BY_MAIN_MODULE 1 #include "gpgsm.h" #include #include /* malloc hooks */ #include "passphrase.h" #include "../common/shareddefs.h" #include "../kbx/keybox.h" /* malloc hooks */ #include "../common/i18n.h" #include "keydb.h" #include "../common/sysutils.h" #include "../common/gc-opt-flags.h" #include "../common/asshelp.h" #include "../common/init.h" #include "../common/compliance.h" +#include "minip12.h" #ifndef O_BINARY #define O_BINARY 0 #endif enum cmd_and_opt_values { aNull = 0, oArmor = 'a', aDetachedSign = 'b', aSym = 'c', aDecrypt = 'd', aEncr = 'e', aListKeys = 'k', aListSecretKeys = 'K', oDryRun = 'n', oOutput = 'o', oQuiet = 'q', oRecipient = 'r', aSign = 's', oUser = 'u', oVerbose = 'v', oBatch = 500, aClearsign, aKeygen, aSignEncr, aDeleteKey, aImport, aVerify, aListExternalKeys, aListChain, aSendKeys, aRecvKeys, aExport, aExportSecretKeyP12, aExportSecretKeyP8, aExportSecretKeyRaw, aServer, aLearnCard, aCallDirmngr, aCallProtectTool, aPasswd, aGPGConfList, aGPGConfTest, aDumpKeys, aDumpChain, aDumpSecretKeys, aDumpExternalKeys, aKeydbClearSomeCertFlags, aFingerprint, oOptions, oDebug, oDebugLevel, oDebugAll, oDebugNone, oDebugWait, oDebugAllowCoreDump, oDebugNoChainValidation, oDebugIgnoreExpiration, oLogFile, oNoLogFile, oAuditLog, oHtmlAuditLog, oEnableSpecialFilenames, oAgentProgram, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oPreferSystemDirmngr, oDirmngrProgram, oDisableDirmngr, oProtectToolProgram, oFakedSystemTime, oPassphraseFD, oPinentryMode, oRequestOrigin, oAssumeArmor, oAssumeBase64, oAssumeBinary, oBase64, oNoArmor, oP12Charset, oCompliance, oDisableCRLChecks, oEnableCRLChecks, oDisableTrustedCertCRLCheck, oEnableTrustedCertCRLCheck, oForceCRLRefresh, oEnableIssuerBasedCRLCheck, oDisableOCSP, oEnableOCSP, oIncludeCerts, oPolicyFile, oDisablePolicyChecks, oEnablePolicyChecks, oAutoIssuerKeyRetrieve, oWithFingerprint, oWithMD5Fingerprint, oWithKeygrip, oWithSecret, oAnswerYes, oAnswerNo, oKeyring, oDefaultKey, oDefRecipient, oDefRecipientSelf, oNoDefRecipient, oStatusFD, oCipherAlgo, oDigestAlgo, oExtraDigestAlgo, oNoVerbose, oNoSecmemWarn, oNoDefKeyring, oNoGreeting, oNoTTY, oNoOptions, oNoBatch, oHomedir, oWithColons, oWithKeyData, oWithValidation, oWithEphemeralKeys, oSkipVerify, oValidationModel, oKeyServer, oEncryptTo, oNoEncryptTo, oLoggerFD, oDisableCipherAlgo, oDisablePubkeyAlgo, oIgnoreTimeConflict, oNoRandomSeedFile, oNoCommonCertsImport, oIgnoreCertExtension, oNoAutostart }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aSign, "sign", N_("make a signature")), /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/ ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")), ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")), /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/ ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")), ARGPARSE_c (aVerify, "verify", N_("verify a signature")), ARGPARSE_c (aListKeys, "list-keys", N_("list keys")), ARGPARSE_c (aListExternalKeys, "list-external-keys", N_("list external keys")), ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")), ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")), ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")), ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")), ARGPARSE_c (aKeygen, "gen-key", "@"), ARGPARSE_c (aDeleteKey, "delete-keys", N_("remove keys from the public keyring")), /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/ /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/ ARGPARSE_c (aImport, "import", N_("import certificates")), ARGPARSE_c (aExport, "export", N_("export certificates")), /* We use -raw and not -p1 for pkcs#1 secret key export so that it won't accidentally be used in case -p12 was intended. */ ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"), ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"), ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"), ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")), ARGPARSE_c (aServer, "server", N_("run in server mode")), ARGPARSE_c (aCallDirmngr, "call-dirmngr", N_("pass a command to the dirmngr")), ARGPARSE_c (aCallProtectTool, "call-protect-tool", N_("invoke gpg-protect-tool")), ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")), ARGPARSE_c (aPasswd, "passwd", "@"), ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_c (aDumpKeys, "dump-cert", "@"), ARGPARSE_c (aDumpKeys, "dump-keys", "@"), ARGPARSE_c (aDumpChain, "dump-chain", "@"), ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"), ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"), ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")), ARGPARSE_s_n (oArmor, "armour", "@"), ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")), ARGPARSE_s_s (oP12Charset, "p12-charset", "@"), ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"), ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"), ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"), ARGPARSE_s_n (oAssumeArmor, "assume-armor", N_("assume input is in PEM format")), ARGPARSE_s_n (oAssumeBase64, "assume-base64", N_("assume input is in base-64 format")), ARGPARSE_s_n (oAssumeBinary, "assume-binary", N_("assume input is in binary format")), ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")), ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"), ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks", N_("never consult a CRL")), ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"), ARGPARSE_s_n (oDisableTrustedCertCRLCheck, "disable-trusted-cert-crl-check", "@"), ARGPARSE_s_n (oEnableTrustedCertCRLCheck, "enable-trusted-cert-crl-check", "@"), ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"), ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"), ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")), ARGPARSE_s_s (oValidationModel, "validation-model", "@"), ARGPARSE_s_i (oIncludeCerts, "include-certs", N_("|N|number of certificates to include") ), ARGPARSE_s_s (oPolicyFile, "policy-file", N_("|FILE|take policy information from FILE")), ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks", N_("do not check certificate policies")), ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"), ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve", N_("fetch missing issuer certificates")), ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"), ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"), ARGPARSE_s_s (oUser, "local-user", N_("|USER-ID|use USER-ID to sign or decrypt")), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a server mode log to FILE")), ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"), ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"), ARGPARSE_s_s (oAuditLog, "audit-log", N_("|FILE|write an audit log to FILE")), ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"), ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")), ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")), ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")), ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")), ARGPARSE_s_s (oKeyring, "keyring", N_("|FILE|add keyring to the list of keyrings")), ARGPARSE_s_s (oDefaultKey, "default-key", N_("|USER-ID|use USER-ID as default secret key")), /* Not yet used: */ /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */ /* N_("|NAME|use NAME as default recipient")), */ /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */ /* N_("use the default key as default recipient")), */ /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */ ARGPARSE_s_s (oKeyServer, "keyserver", N_("|SPEC|use this keyserver to lookup keys")), ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_n (oDebugNone, "debug-none", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"), ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"), ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), ARGPARSE_s_s (oCipherAlgo, "cipher-algo", N_("|NAME|use cipher algorithm NAME")), ARGPARSE_s_s (oDigestAlgo, "digest-algo", N_("|NAME|use message digest algorithm NAME")), ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"), ARGPARSE_group (302, N_( "@\n(See the man page for a complete listing of all commands and options)\n" )), /* Hidden options. */ ARGPARSE_s_s (oCompliance, "compliance", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"), ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"), ARGPARSE_s_n (oNoArmor, "no-armor", "@"), ARGPARSE_s_n (oNoArmor, "no-armour", "@"), ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_noconffile (oNoOptions, "no-options", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDisplay, "display", "@"), ARGPARSE_s_s (oTTYname, "ttyname", "@"), ARGPARSE_s_s (oTTYtype, "ttytype", "@"), ARGPARSE_s_s (oLCctype, "lc-ctype", "@"), ARGPARSE_s_s (oLCmessages, "lc-messages", "@"), ARGPARSE_s_s (oXauthority, "xauthority", "@"), ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"), ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"), ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"), ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"), ARGPARSE_s_n (oNoBatch, "no-batch", "@"), ARGPARSE_s_n (oWithColons, "with-colons", "@"), ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"), ARGPARSE_s_n (oWithValidation, "with-validation", "@"), ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"), ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"), ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"), ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"), ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"), ARGPARSE_s_n (oWithSecret, "with-secret", "@"), ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"), ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"), ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"), ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"), ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"), ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), ARGPARSE_s_n (oEnableIssuerBasedCRLCheck, "enable-issuer-based-crl-check", "@"), /* Command aliases. */ ARGPARSE_c (aListKeys, "list-key", "@"), ARGPARSE_c (aListChain, "list-signatures", "@"), ARGPARSE_c (aListChain, "list-sigs", "@"), ARGPARSE_c (aListChain, "check-signatures", "@"), ARGPARSE_c (aListChain, "check-sigs", "@"), ARGPARSE_c (aDeleteKey, "delete-key", "@"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_X509_VALUE , "x509" }, { DBG_MPI_VALUE , "mpi" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { 0, NULL } }; /* Global variable to keep an error count. */ int gpgsm_errors_seen = 0; /* It is possible that we are currentlu running under setuid permissions */ static int maybe_setuid = 1; /* Helper to implement --debug-level and --debug*/ static const char *debug_level; static unsigned int debug_value; /* Default value for include-certs. We need an extra macro for gpgconf-list because the variable will be changed by the command line option. It is often cumbersome to locate intermediate certificates, thus by default we include all certificates in the chain. However we leave out the root certificate because that would make it too easy for the recipient to import that root certificate. A root certificate should be installed only after due checks and thus it won't help to send it along with each message. */ #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */ static int default_include_certs = DEFAULT_INCLUDE_CERTS; /* Whether the chain mode shall be used for validation. */ static int default_validation_model; /* The default cipher algo. */ #define DEFAULT_CIPHER_ALGO "AES" static char *build_list (const char *text, const char *(*mapf)(int), int (*chkf)(int)); static void set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd ); static void emergency_cleanup (void); static int open_read (const char *filename); static estream_t open_es_fread (const char *filename, const char *mode); static estream_t open_es_fwrite (const char *filename); static void run_protect_tool (int argc, char **argv); static int our_pk_test_algo (int algo) { switch (algo) { case GCRY_PK_RSA: case GCRY_PK_ECDSA: return gcry_pk_test_algo (algo); default: return 1; } } static int our_cipher_test_algo (int algo) { switch (algo) { case GCRY_CIPHER_3DES: case GCRY_CIPHER_AES128: case GCRY_CIPHER_AES192: case GCRY_CIPHER_AES256: case GCRY_CIPHER_SERPENT128: case GCRY_CIPHER_SERPENT192: case GCRY_CIPHER_SERPENT256: case GCRY_CIPHER_SEED: case GCRY_CIPHER_CAMELLIA128: case GCRY_CIPHER_CAMELLIA192: case GCRY_CIPHER_CAMELLIA256: return gcry_cipher_test_algo (algo); default: return 1; } } static int our_md_test_algo (int algo) { switch (algo) { case GCRY_MD_MD5: case GCRY_MD_SHA1: case GCRY_MD_RMD160: case GCRY_MD_SHA224: case GCRY_MD_SHA256: case GCRY_MD_SHA384: case GCRY_MD_SHA512: case GCRY_MD_WHIRLPOOL: return gcry_md_test_algo (algo); default: return 1; } } static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; if (maybe_setuid) { gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ maybe_setuid = 0; } s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } static const char * my_strusage( int level ) { static char *digests, *pubkeys, *ciphers; static char *ver_gcry, *ver_ksba; const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPGSM@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)"); break; case 41: p = _("Syntax: @GPGSM@ [options] [files]\n" "Sign, check, encrypt or decrypt using the S/MIME protocol\n" "Default operation depends on the input data\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; case 21: if (!ver_ksba) ver_ksba = make_libversion ("libksba", ksba_check_version); p = ver_ksba; break; case 31: p = "\nHome: "; break; case 32: p = gnupg_homedir (); break; case 33: p = _("\nSupported algorithms:\n"); break; case 34: if (!ciphers) ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name, our_cipher_test_algo ); p = ciphers; break; case 35: if (!pubkeys) pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name, our_pk_test_algo ); p = pubkeys; break; case 36: if (!digests) digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo ); p = digests; break; default: p = NULL; break; } return p; } static char * build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int)) { int i; size_t n=strlen(text)+2; char *list, *p; if (maybe_setuid) { gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */ } for (i=1; i < 400; i++ ) if (!chkf(i)) n += strlen(mapf(i)) + 2; list = xmalloc (21 + n); *list = 0; for (p=NULL, i=1; i < 400; i++) { if (!chkf(i)) { if( !p ) p = stpcpy (list, text ); else p = stpcpy (p, ", "); p = stpcpy (p, mapf(i) ); } } if (p) strcpy (p, "\n" ); return list; } /* Set the file pointer into binary mode if required. */ static void set_binary (FILE *fp) { #ifdef HAVE_DOSISH_SYSTEM setmode (fileno (fp), O_BINARY); #else (void)fp; #endif } static void wrong_args (const char *text) { fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text); gpgsm_exit (2); } static void set_opt_session_env (const char *name, const char *value) { gpg_error_t err; err = session_env_setenv (opt.session_env, name, value); if (err) log_fatal ("error setting session environment: %s\n", gpg_strerror (err)); } /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active debug flags are propagated to the subsystems. With DEBUG_LEVEL set, a specific set of debug flags is set; and individual debugging flags will be added on top. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE; else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); gpgsm_exit (2); } opt.debug |= debug_value; if (opt.debug && !opt.verbose) opt.verbose = 1; if (opt.debug) opt.quiet = 0; if (opt.debug & DBG_MPI_VALUE) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2); if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); + + /* minip12.c may be used outside of GnuPG, thus we don't have the + * opt structure over there. */ + p12_set_verbosity (opt.verbose); } static void set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd) { enum cmd_and_opt_values cmd = *ret_cmd; if (!cmd || cmd == new_cmd) cmd = new_cmd; else if ( cmd == aSign && new_cmd == aEncr ) cmd = aSignEncr; else if ( cmd == aEncr && new_cmd == aSign ) cmd = aSignEncr; else if ( (cmd == aSign && new_cmd == aClearsign) || (cmd == aClearsign && new_cmd == aSign) ) cmd = aClearsign; else { log_error(_("conflicting commands\n")); gpgsm_exit(2); } *ret_cmd = cmd; } /* Helper to add recipients to a list. */ static void do_add_recipient (ctrl_t ctrl, const char *name, certlist_t *recplist, int is_encrypt_to, int recp_required) { int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to); if (rc) { if (recp_required) { log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc)); gpgsm_status2 (ctrl, STATUS_INV_RECP, get_inv_recpsgnr_code (rc), name, NULL); } else log_info (_("Note: won't be able to encrypt to '%s': %s\n"), name, gpg_strerror (rc)); } } static void parse_validation_model (const char *model) { int i = gpgsm_parse_validation_model (model); if (i == -1) log_error (_("unknown validation model '%s'\n"), model); else default_validation_model = i; } /* Release the list of SERVERS. As usual it is okay to call this function with SERVERS passed as NULL. */ void keyserver_list_free (struct keyserver_spec *servers) { while (servers) { struct keyserver_spec *tmp = servers->next; xfree (servers->host); xfree (servers->user); if (servers->pass) memset (servers->pass, 0, strlen (servers->pass)); xfree (servers->pass); xfree (servers->base); xfree (servers); servers = tmp; } } /* See also dirmngr ldapserver_parse_one(). */ struct keyserver_spec * parse_keyserver_line (char *line, const char *filename, unsigned int lineno) { char *p; char *endp; struct keyserver_spec *server; int fieldno; int fail = 0; /* Parse the colon separated fields. */ server = xcalloc (1, sizeof *server); for (fieldno = 1, p = line; p; p = endp, fieldno++ ) { endp = strchr (p, ':'); if (endp) *endp++ = '\0'; trim_spaces (p); switch (fieldno) { case 1: if (*p) server->host = xstrdup (p); else { log_error (_("%s:%u: no hostname given\n"), filename, lineno); fail = 1; } break; case 2: if (*p) server->port = atoi (p); break; case 3: if (*p) server->user = xstrdup (p); break; case 4: if (*p && !server->user) { log_error (_("%s:%u: password given without user\n"), filename, lineno); fail = 1; } else if (*p) server->pass = xstrdup (p); break; case 5: if (*p) server->base = xstrdup (p); break; default: /* (We silently ignore extra fields.) */ break; } } if (fail) { log_info (_("%s:%u: skipping this line\n"), filename, lineno); keyserver_list_free (server); server = NULL; } return server; } int main ( int argc, char **argv) { ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; /* char *username;*/ int may_coredump; strlist_t sl, remusr= NULL, locusr=NULL; strlist_t nrings=NULL; int detached_sig = 0; char *last_configname = NULL; const char *configname = NULL; /* NULL or points to last_configname. * NULL also indicates that we are * processing options from the cmdline. */ int debug_argparser = 0; int no_more_options = 0; int default_keyring = 1; char *logfile = NULL; char *auditlog = NULL; char *htmlauditlog = NULL; int greeting = 0; int nogreeting = 0; int debug_wait = 0; int use_random_seed = 1; int no_common_certs_import = 0; int with_fpr = 0; const char *forced_digest_algo = NULL; const char *extra_digest_algo = NULL; enum cmd_and_opt_values cmd = 0; struct server_control_s ctrl; certlist_t recplist = NULL; certlist_t signerlist = NULL; int do_not_setup_keys = 0; int recp_required = 0; estream_t auditfp = NULL; estream_t htmlauditfp = NULL; struct assuan_malloc_hooks malloc_hooks; int pwfd = -1; static const char *homedirvalue; early_system_init (); gnupg_reopen_std (GPGSM_NAME); /* trap_unaligned ();*/ gnupg_rl_initialize (); set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); /* Please note that we may running SUID(ROOT), so be very CAREFUL when adding any stuff between here and the call to secmem_init() somewhere after the option parsing */ log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); /* Check that the libraries are suitable. Do it here because the option parse may need services of the library */ if (!ksba_check_version (NEED_KSBA_VERSION) ) log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba", NEED_KSBA_VERSION, ksba_check_version (NULL) ); gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); may_coredump = disable_core_dumps (); gnupg_init_signals (0, emergency_cleanup); dotlock_create (NULL, 0); /* Register lockfile cleanup. */ /* Tell the compliance module who we are. */ gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPGSM); opt.autostart = 1; opt.session_env = session_env_new (); if (!opt.session_env) log_fatal ("error allocating session environment block: %s\n", strerror (errno)); /* Note: If you change this default cipher algorithm , please remember to update the Gpgconflist entry as well. */ opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO; /* First check whether we have a config file on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); while (gnupg_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oDebug: case oDebugAll: debug_argparser++; break; case oNoOptions: /* Set here here because the homedir would otherwise be * created before main option parsing starts. */ opt.no_homedir_creation = 1; break; case oHomedir: homedirvalue = pargs.r.ret_str; break; case aCallProtectTool: /* Make sure that --version and --help are passed to the * protect-tool. */ goto leave_cmdline_parser; } } leave_cmdline_parser: /* Reset the flags. */ pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); /* Initialize the secure memory. */ gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); maybe_setuid = 0; /* * Now we are now working under our real uid */ ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); setup_libassuan_logging (&opt.debug, NULL); /* Set homedir. */ gnupg_set_homedir (homedirvalue); /* Setup a default control structure for command line mode */ memset (&ctrl, 0, sizeof ctrl); gpgsm_init_default_ctrl (&ctrl); ctrl.no_server = 1; ctrl.status_fd = -1; /* No status output. */ ctrl.autodetect_encoding = 1; /* Set the default policy file */ opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL); /* The configuraton directories for use by gpgrt_argparser. */ gnupg_set_confdir (GNUPG_CONFDIR_SYS, gnupg_sysconfdir ()); gnupg_set_confdir (GNUPG_CONFDIR_USER, gnupg_homedir ()); /* We are re-using the struct, thus the reset flag. We OR the * flags so that the internal intialized flag won't be cleared. */ argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags |= (ARGPARSE_FLAG_RESET | ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_SYS | ARGPARSE_FLAG_USER); while (!no_more_options && gnupg_argparser (&pargs, opts, GPGSM_NAME EXTSEP_S "conf")) { switch (pargs.r_opt) { case ARGPARSE_CONFFILE: if (debug_argparser) log_info (_("reading options from '%s'\n"), pargs.r_type? pargs.r.ret_str: "[cmdline]"); if (pargs.r_type) { xfree (last_configname); last_configname = xstrdup (pargs.r.ret_str); configname = last_configname; } else configname = NULL; break; case aGPGConfList: case aGPGConfTest: set_cmd (&cmd, pargs.r_opt); do_not_setup_keys = 1; default_keyring = 0; nogreeting = 1; break; case aServer: opt.batch = 1; set_cmd (&cmd, aServer); break; case aCallDirmngr: opt.batch = 1; set_cmd (&cmd, aCallDirmngr); do_not_setup_keys = 1; break; case aCallProtectTool: opt.batch = 1; set_cmd (&cmd, aCallProtectTool); no_more_options = 1; /* Stop parsing. */ do_not_setup_keys = 1; break; case aDeleteKey: set_cmd (&cmd, aDeleteKey); /*greeting=1;*/ do_not_setup_keys = 1; break; case aDetachedSign: detached_sig = 1; set_cmd (&cmd, aSign ); break; case aKeygen: set_cmd (&cmd, aKeygen); greeting=1; do_not_setup_keys = 1; break; case aImport: case aSendKeys: case aRecvKeys: case aExport: case aExportSecretKeyP12: case aExportSecretKeyP8: case aExportSecretKeyRaw: case aDumpKeys: case aDumpChain: case aDumpExternalKeys: case aDumpSecretKeys: case aListKeys: case aListExternalKeys: case aListSecretKeys: case aListChain: case aLearnCard: case aPasswd: case aKeydbClearSomeCertFlags: do_not_setup_keys = 1; set_cmd (&cmd, pargs.r_opt); break; case aEncr: recp_required = 1; set_cmd (&cmd, pargs.r_opt); break; case aSym: case aDecrypt: case aSign: case aClearsign: case aVerify: set_cmd (&cmd, pargs.r_opt); break; /* Output encoding selection. */ case oArmor: ctrl.create_pem = 1; break; case oBase64: ctrl.create_pem = 0; ctrl.create_base64 = 1; break; case oNoArmor: ctrl.create_pem = 0; ctrl.create_base64 = 0; break; case oP12Charset: opt.p12_charset = pargs.r.ret_str; break; case oPassphraseFD: pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0); break; case oPinentryMode: opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str); if (opt.pinentry_mode == -1) log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str); break; case oRequestOrigin: opt.request_origin = parse_request_origin (pargs.r.ret_str); if (opt.request_origin == -1) log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str); break; /* Input encoding selection. */ case oAssumeArmor: ctrl.autodetect_encoding = 0; ctrl.is_pem = 1; ctrl.is_base64 = 0; break; case oAssumeBase64: ctrl.autodetect_encoding = 0; ctrl.is_pem = 0; ctrl.is_base64 = 1; break; case oAssumeBinary: ctrl.autodetect_encoding = 0; ctrl.is_pem = 0; ctrl.is_base64 = 0; break; case oDisableCRLChecks: opt.no_crl_check = 1; break; case oEnableCRLChecks: opt.no_crl_check = 0; break; case oDisableTrustedCertCRLCheck: opt.no_trusted_cert_crl_check = 1; break; case oEnableTrustedCertCRLCheck: opt.no_trusted_cert_crl_check = 0; break; case oForceCRLRefresh: opt.force_crl_refresh = 1; break; case oEnableIssuerBasedCRLCheck: opt.enable_issuer_based_crl_check = 1; break; case oDisableOCSP: ctrl.use_ocsp = opt.enable_ocsp = 0; break; case oEnableOCSP: ctrl.use_ocsp = opt.enable_ocsp = 1; break; case oIncludeCerts: ctrl.include_certs = default_include_certs = pargs.r.ret_int; break; case oPolicyFile: xfree (opt.policy_file); if (*pargs.r.ret_str) opt.policy_file = xstrdup (pargs.r.ret_str); else opt.policy_file = NULL; break; case oDisablePolicyChecks: opt.no_policy_check = 1; break; case oEnablePolicyChecks: opt.no_policy_check = 0; break; case oAutoIssuerKeyRetrieve: opt.auto_issuer_key_retrieve = 1; break; case oOutput: opt.outfile = pargs.r.ret_str; break; case oQuiet: opt.quiet = 1; break; case oNoTTY: /* fixme:tty_no_terminal(1);*/ break; case oDryRun: opt.dry_run = 1; break; case oVerbose: opt.verbose++; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); break; case oNoVerbose: opt.verbose = 0; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); break; case oLogFile: logfile = pargs.r.ret_str; break; case oNoLogFile: logfile = NULL; break; case oAuditLog: auditlog = pargs.r.ret_str; break; case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break; case oBatch: opt.batch = 1; greeting = 0; break; case oNoBatch: opt.batch = 0; break; case oAnswerYes: opt.answer_yes = 1; break; case oAnswerNo: opt.answer_no = 1; break; case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break; case oDebug: if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags)) { pargs.r_opt = ARGPARSE_INVALID_ARG; pargs.err = ARGPARSE_PRINT_ERROR; } break; case oDebugAll: debug_value = ~0; break; case oDebugNone: debug_value = 0; break; case oDebugLevel: debug_level = pargs.r.ret_str; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oDebugAllowCoreDump: may_coredump = enable_core_dumps (); break; case oDebugNoChainValidation: opt.no_chain_validation = 1; break; case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break; case oStatusFD: ctrl.status_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 1); break; case oLoggerFD: log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oWithMD5Fingerprint: opt.with_md5_fingerprint=1; /*fall through*/ case oWithFingerprint: with_fpr=1; /*fall through*/ case aFingerprint: opt.fingerprint++; break; case oWithKeygrip: opt.with_keygrip = 1; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDisplay: set_opt_session_env ("DISPLAY", pargs.r.ret_str); break; case oTTYname: set_opt_session_env ("GPG_TTY", pargs.r.ret_str); break; case oTTYtype: set_opt_session_env ("TERM", pargs.r.ret_str); break; case oXauthority: set_opt_session_env ("XAUTHORITY", pargs.r.ret_str); break; case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break; case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break; case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break; case oDisableDirmngr: opt.disable_dirmngr = 1; break; case oPreferSystemDirmngr: /* Obsolete */; break; case oProtectToolProgram: opt.protect_tool_program = pargs.r.ret_str; break; case oFakedSystemTime: { time_t faked_time = isotime2epoch (pargs.r.ret_str); if (faked_time == (time_t)(-1)) faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10); gnupg_set_time (faked_time, 0); } break; case oNoDefKeyring: default_keyring = 0; break; case oNoGreeting: nogreeting = 1; break; case oDefaultKey: if (*pargs.r.ret_str) { xfree (opt.local_user); opt.local_user = xstrdup (pargs.r.ret_str); } break; case oDefRecipient: if (*pargs.r.ret_str) opt.def_recipient = xstrdup (pargs.r.ret_str); break; case oDefRecipientSelf: xfree (opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 1; break; case oNoDefRecipient: xfree (opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 0; break; case oWithKeyData: opt.with_key_data=1; /* fall through */ case oWithColons: ctrl.with_colons = 1; break; case oWithSecret: ctrl.with_secret = 1; break; case oWithValidation: ctrl.with_validation=1; break; case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break; case oSkipVerify: opt.skip_verify=1; break; case oNoEncryptTo: opt.no_encrypt_to = 1; break; case oEncryptTo: /* Store the recipient in the second list */ sl = add_to_strlist (&remusr, pargs.r.ret_str); sl->flags = 1; break; case oRecipient: /* store the recipient */ add_to_strlist ( &remusr, pargs.r.ret_str); break; case oUser: /* Store the local users, the first one is the default */ if (!opt.local_user) opt.local_user = xstrdup (pargs.r.ret_str); add_to_strlist (&locusr, pargs.r.ret_str); break; case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break; case oCipherAlgo: opt.def_cipher_algoid = pargs.r.ret_str; break; case oDisableCipherAlgo: { int algo = gcry_cipher_map_name (pargs.r.ret_str); gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo); } break; case oDisablePubkeyAlgo: { int algo = gcry_pk_map_name (pargs.r.ret_str); gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo ); } break; case oDigestAlgo: forced_digest_algo = pargs.r.ret_str; break; case oExtraDigestAlgo: extra_digest_algo = pargs.r.ret_str; break; case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break; case oNoRandomSeedFile: use_random_seed = 0; break; case oNoCommonCertsImport: no_common_certs_import = 1; break; case oEnableSpecialFilenames: enable_special_filenames (); break; case oValidationModel: parse_validation_model (pargs.r.ret_str); break; case oKeyServer: { struct keyserver_spec *keyserver; keyserver = parse_keyserver_line (pargs.r.ret_str, configname, pargs.lineno); if (! keyserver) log_error (_("could not parse keyserver\n")); else { /* FIXME: Keep last next pointer. */ struct keyserver_spec **next_p = &opt.keyserver; while (*next_p) next_p = &(*next_p)->next; *next_p = keyserver; } } break; case oIgnoreCertExtension: add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str); break; case oNoAutostart: opt.autostart = 0; break; case oCompliance: { struct gnupg_compliance_option compliance_options[] = { { "gnupg", CO_GNUPG }, { "de-vs", CO_DE_VS } }; int compliance = gnupg_parse_compliance_option (pargs.r.ret_str, compliance_options, DIM (compliance_options), opt.quiet); if (compliance < 0) log_inc_errorcount (); /* Force later termination. */ opt.compliance = compliance; } break; default: if (configname) pargs.err = ARGPARSE_PRINT_WARNING; else { pargs.err = ARGPARSE_PRINT_ERROR; /* The argparse function calls a plain exit and thus we * need to print a status here. */ gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-parser", gpg_error (GPG_ERR_GENERAL)); } break; } } gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (!last_configname) opt.config_filename = make_filename (gnupg_homedir (), GPGSM_NAME EXTSEP_S "conf", NULL); else opt.config_filename = last_configname; if (log_get_errorcount(0)) { gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-parser", gpg_error (GPG_ERR_GENERAL)); gpgsm_exit(2); } if (pwfd != -1) /* Read the passphrase now. */ read_passphrase_from_fd (pwfd); /* Now that we have the options parsed we need to update the default control structure. */ gpgsm_init_default_ctrl (&ctrl); if (nogreeting) greeting = 0; if (greeting) { es_fprintf (es_stderr, "%s %s; %s\n", strusage(11), strusage(13), strusage(14) ); es_fprintf (es_stderr, "%s\n", strusage(15) ); } # ifdef IS_DEVELOPMENT_VERSION if (!opt.batch) { log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n"); log_info ("It is only intended for test purposes and should NOT be\n"); log_info ("used in a production environment or with production keys!\n"); } # endif if (may_coredump && !opt.quiet) log_info (_("WARNING: program may create a core file!\n")); /* if (opt.qualsig_approval && !opt.quiet) */ /* log_info (_("This software has officially been approved to " */ /* "create and verify\n" */ /* "qualified signatures according to German law.\n")); */ if (logfile && cmd == aServer) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } /*FIXME if (opt.batch) */ /* tty_batchmode (1); */ gcry_control (GCRYCTL_RESUME_SECMEM_WARN); set_debug (); /* Although we always use gpgsm_exit, we better install a regualr exit handler so that at least the secure memory gets wiped out. */ if (atexit (emergency_cleanup)) { log_error ("atexit failed\n"); gpgsm_exit (2); } /* Must do this after dropping setuid, because the mapping functions may try to load an module and we may have disabled an algorithm. We remap the commonly used algorithms to the OIDs for convenience. We need to work with the OIDs because they are used to check whether the encryption mode is actually available. */ if (!strcmp (opt.def_cipher_algoid, "3DES") ) opt.def_cipher_algoid = "1.2.840.113549.3.7"; else if (!strcmp (opt.def_cipher_algoid, "AES") || !strcmp (opt.def_cipher_algoid, "AES128")) opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2"; else if (!strcmp (opt.def_cipher_algoid, "AES192") ) opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22"; else if (!strcmp (opt.def_cipher_algoid, "AES256") ) opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42"; else if (!strcmp (opt.def_cipher_algoid, "SERPENT") || !strcmp (opt.def_cipher_algoid, "SERPENT128") ) opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2"; else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") ) opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22"; else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") ) opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42"; else if (!strcmp (opt.def_cipher_algoid, "SEED") ) opt.def_cipher_algoid = "1.2.410.200004.1.4"; else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA") || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") ) opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2"; else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") ) opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3"; else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") ) opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4"; if (cmd != aGPGConfList) { if ( !gcry_cipher_map_name (opt.def_cipher_algoid) || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid)) log_error (_("selected cipher algorithm is invalid\n")); if (forced_digest_algo) { opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo); if (our_md_test_algo(opt.forced_digest_algo) ) log_error (_("selected digest algorithm is invalid\n")); } if (extra_digest_algo) { opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo); if (our_md_test_algo (opt.extra_digest_algo) ) log_error (_("selected digest algorithm is invalid\n")); } } /* Check our chosen algorithms against the list of allowed * algorithms in the current compliance mode, and fail hard if it is * not. This is us being nice to the user informing her early that * the chosen algorithms are not available. We also check and * enforce this right before the actual operation. */ if (! gnupg_cipher_is_allowed (opt.compliance, cmd == aEncr || cmd == aSignEncr, gcry_cipher_map_name (opt.def_cipher_algoid), GCRY_CIPHER_MODE_NONE) && ! gnupg_cipher_is_allowed (opt.compliance, cmd == aEncr || cmd == aSignEncr, gcry_cipher_mode_from_oid (opt.def_cipher_algoid), GCRY_CIPHER_MODE_NONE)) log_error (_("cipher algorithm '%s' may not be used in %s mode\n"), opt.def_cipher_algoid, gnupg_compliance_option_string (opt.compliance)); if (forced_digest_algo && ! gnupg_digest_is_allowed (opt.compliance, cmd == aSign || cmd == aSignEncr || cmd == aClearsign, opt.forced_digest_algo)) log_error (_("digest algorithm '%s' may not be used in %s mode\n"), forced_digest_algo, gnupg_compliance_option_string (opt.compliance)); if (extra_digest_algo && ! gnupg_digest_is_allowed (opt.compliance, cmd == aSign || cmd == aSignEncr || cmd == aClearsign, opt.extra_digest_algo)) log_error (_("digest algorithm '%s' may not be used in %s mode\n"), extra_digest_algo, gnupg_compliance_option_string (opt.compliance)); if (log_get_errorcount(0)) { gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-postprocessing", gpg_error (GPG_ERR_GENERAL)); gpgsm_exit (2); } /* Set the random seed file. */ if (use_random_seed) { char *p = make_filename (gnupg_homedir (), "random_seed", NULL); gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p); xfree(p); } if (!cmd && opt.fingerprint && !with_fpr) set_cmd (&cmd, aListKeys); /* Add default keybox. */ if (!nrings && default_keyring) { int created; keydb_add_resource (&ctrl, "pubring.kbx", 0, &created); if (created && !no_common_certs_import) { /* Import the standard certificates for a new default keybox. */ char *filelist[2]; filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL); filelist[1] = NULL; if (!gnupg_access (filelist[0], F_OK)) { log_info (_("importing common certificates '%s'\n"), filelist[0]); gpgsm_import_files (&ctrl, 1, filelist, open_read); } xfree (filelist[0]); } } for (sl = nrings; sl; sl = sl->next) keydb_add_resource (&ctrl, sl->d, 0, NULL); FREE_STRLIST(nrings); /* Prepare the audit log feature for certain commands. */ if (auditlog || htmlauditlog) { switch (cmd) { case aEncr: case aSign: case aDecrypt: case aVerify: audit_release (ctrl.audit); ctrl.audit = audit_new (); if (auditlog) auditfp = open_es_fwrite (auditlog); if (htmlauditlog) htmlauditfp = open_es_fwrite (htmlauditlog); break; default: break; } } if (!do_not_setup_keys) { int errcount = log_get_errorcount (0); for (sl = locusr; sl ; sl = sl->next) { int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0); if (rc) { log_error (_("can't sign using '%s': %s\n"), sl->d, gpg_strerror (rc)); gpgsm_status2 (&ctrl, STATUS_INV_SGNR, get_inv_recpsgnr_code (rc), sl->d, NULL); gpgsm_status2 (&ctrl, STATUS_INV_RECP, get_inv_recpsgnr_code (rc), sl->d, NULL); } } /* Build the recipient list. We first add the regular ones and then the encrypt-to ones because the underlying function will silently ignore duplicates and we can't allow keeping a duplicate which is flagged as encrypt-to as the actually encrypt function would then complain about no (regular) recipients. */ for (sl = remusr; sl; sl = sl->next) if (!(sl->flags & 1)) do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required); if (!opt.no_encrypt_to) { for (sl = remusr; sl; sl = sl->next) if ((sl->flags & 1)) do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required); } /* We do not require a recipient for decryption but because * recipients and signers are always checked and log_error is * sometimes used (for failed signing keys or due to a failed * CRL checking) that would have bumbed up the error counter. * We clear the counter in the decryption case because there is * no reason to force decryption to fail. */ if (cmd == aDecrypt && !errcount) log_get_errorcount (1); /* clear counter */ } if (log_get_errorcount(0)) gpgsm_exit(1); /* Must stop for invalid recipients. */ /* Dispatch command. */ switch (cmd) { case aGPGConfList: { /* List options and default values in the GPG Conf format. */ char *config_filename_esc = percent_escape (opt.config_filename, NULL); es_printf ("%s-%s.conf:%lu:\"%s\n", GPGCONF_NAME, GPGSM_NAME, GC_OPT_FLAG_DEFAULT, config_filename_esc); xfree (config_filename_esc); es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT); es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("enable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, DEFAULT_INCLUDE_CERTS); es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, DEFAULT_CIPHER_ALGO); es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT); es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT); es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT); es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE); /* The next one is an info only item and should match what proc_parameters actually implements. */ es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "RSA-3072"); es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg"); } break; case aGPGConfTest: /* This is merely a dummy command to test whether the configuration file is valid. */ break; case aServer: if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } gpgsm_server (recplist); break; case aCallDirmngr: if (!argc) wrong_args ("--call-dirmngr {args}"); else if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1)) gpgsm_exit (1); break; case aCallProtectTool: run_protect_tool (argc, argv); break; case aEncr: /* Encrypt the given file. */ { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); set_binary (stdin); if (!argc) /* Source is stdin. */ gpgsm_encrypt (&ctrl, recplist, 0, fp); else if (argc == 1) /* Source is the given file. */ gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp); else wrong_args ("--encrypt [datafile]"); es_fclose (fp); } break; case aSign: /* Sign the given file. */ { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); /* Fixme: We should also allow concatenation of multiple files for signing because that is what gpg does.*/ set_binary (stdin); if (!argc) /* Create from stdin. */ gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp); else if (argc == 1) /* From file. */ gpgsm_sign (&ctrl, signerlist, open_read (*argv), detached_sig, fp); else wrong_args ("--sign [datafile]"); es_fclose (fp); } break; case aSignEncr: /* sign and encrypt the given file */ log_error ("this command has not yet been implemented\n"); break; case aClearsign: /* make a clearsig */ log_error ("this command has not yet been implemented\n"); break; case aVerify: { estream_t fp = NULL; set_binary (stdin); if (argc == 2 && opt.outfile) log_info ("option --output ignored for a detached signature\n"); else if (opt.outfile) fp = open_es_fwrite (opt.outfile); if (!argc) gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */ else if (argc == 1) gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */ else if (argc == 2) /* detached signature (sig, detached) */ gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL); else wrong_args ("--verify [signature [detached_data]]"); es_fclose (fp); } break; case aDecrypt: { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); set_binary (stdin); if (!argc) gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */ else if (argc == 1) gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */ else wrong_args ("--decrypt [filename]"); es_fclose (fp); } break; case aDeleteKey: for (sl=NULL; argc; argc--, argv++) add_to_strlist (&sl, *argv); gpgsm_delete (&ctrl, sl); free_strlist(sl); break; case aListChain: case aDumpChain: ctrl.with_chain = 1; /* fall through */ case aListKeys: case aDumpKeys: case aListExternalKeys: case aDumpExternalKeys: case aListSecretKeys: case aDumpSecretKeys: { unsigned int mode; estream_t fp; switch (cmd) { case aListChain: case aListKeys: mode = (0 | 0 | (1<<6)); break; case aDumpChain: case aDumpKeys: mode = (256 | 0 | (1<<6)); break; case aListExternalKeys: mode = (0 | 0 | (1<<7)); break; case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break; case aListSecretKeys: mode = (0 | 2 | (1<<6)); break; case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break; default: BUG(); } fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); for (sl=NULL; argc; argc--, argv++) add_to_strlist (&sl, *argv); gpgsm_list_keys (&ctrl, sl, fp, mode); free_strlist(sl); es_fclose (fp); } break; case aKeygen: /* Generate a key; well kind of. */ { estream_t fpin = NULL; estream_t fpout; if (opt.batch) { if (!argc) /* Create from stdin. */ fpin = open_es_fread ("-", "r"); else if (argc == 1) /* From file. */ fpin = open_es_fread (*argv, "r"); else wrong_args ("--generate-key --batch [parmfile]"); } fpout = open_es_fwrite (opt.outfile?opt.outfile:"-"); if (fpin) gpgsm_genkey (&ctrl, fpin, fpout); else gpgsm_gencertreq_tty (&ctrl, fpout); es_fclose (fpout); } break; case aImport: gpgsm_import_files (&ctrl, argc, argv, open_read); break; case aExport: { estream_t fp; fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); for (sl=NULL; argc; argc--, argv++) add_to_strlist (&sl, *argv); gpgsm_export (&ctrl, sl, fp); free_strlist(sl); es_fclose (fp); } break; case aExportSecretKeyP12: { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); if (argc == 1) gpgsm_p12_export (&ctrl, *argv, fp, 0); else wrong_args ("--export-secret-key-p12 KEY-ID"); if (fp != es_stdout) es_fclose (fp); } break; case aExportSecretKeyP8: { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); if (argc == 1) gpgsm_p12_export (&ctrl, *argv, fp, 1); else wrong_args ("--export-secret-key-p8 KEY-ID"); if (fp != es_stdout) es_fclose (fp); } break; case aExportSecretKeyRaw: { estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-"); if (argc == 1) gpgsm_p12_export (&ctrl, *argv, fp, 2); else wrong_args ("--export-secret-key-raw KEY-ID"); if (fp != es_stdout) es_fclose (fp); } break; case aSendKeys: case aRecvKeys: log_error ("this command has not yet been implemented\n"); break; case aLearnCard: if (argc) wrong_args ("--learn-card"); else { int rc = gpgsm_agent_learn (&ctrl); if (rc) log_error ("error learning card: %s\n", gpg_strerror (rc)); } break; case aPasswd: if (argc != 1) wrong_args ("--change-passphrase "); else { int rc; ksba_cert_t cert = NULL; char *grip = NULL; rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert, 0); if (rc) ; else if (!(grip = gpgsm_get_keygrip_hexstring (cert))) rc = gpg_error (GPG_ERR_BUG); else { char *desc = gpgsm_format_keydesc (cert); rc = gpgsm_agent_passwd (&ctrl, grip, desc); xfree (desc); } if (rc) log_error ("error changing passphrase: %s\n", gpg_strerror (rc)); xfree (grip); ksba_cert_release (cert); } break; case aKeydbClearSomeCertFlags: for (sl=NULL; argc; argc--, argv++) add_to_strlist (&sl, *argv); keydb_clear_some_cert_flags (&ctrl, sl); free_strlist(sl); break; default: log_error (_("invalid command (there is no implicit command)\n")); break; } /* Print the audit result if needed. */ if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp)) { if (auditlog && auditfp) audit_print_result (ctrl.audit, auditfp, 0); if (htmlauditlog && htmlauditfp) audit_print_result (ctrl.audit, htmlauditfp, 1); audit_release (ctrl.audit); ctrl.audit = NULL; es_fclose (auditfp); es_fclose (htmlauditfp); } /* cleanup */ keyserver_list_free (opt.keyserver); opt.keyserver = NULL; gpgsm_release_certlist (recplist); gpgsm_release_certlist (signerlist); FREE_STRLIST (remusr); FREE_STRLIST (locusr); gpgsm_exit(0); return 8; /*NOTREACHED*/ } /* Note: This function is used by signal handlers!. */ static void emergency_cleanup (void) { gcry_control (GCRYCTL_TERM_SECMEM ); } void gpgsm_exit (int rc) { gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE); if (opt.debug & DBG_MEMSTAT_VALUE) { gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); } if (opt.debug) gcry_control (GCRYCTL_DUMP_SECMEM_STATS ); emergency_cleanup (); rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0; exit (rc); } void gpgsm_init_default_ctrl (struct server_control_s *ctrl) { ctrl->include_certs = default_include_certs; ctrl->use_ocsp = opt.enable_ocsp; ctrl->validation_model = default_validation_model; ctrl->offline = opt.disable_dirmngr; } int gpgsm_parse_validation_model (const char *model) { if (!ascii_strcasecmp (model, "shell") ) return 0; else if ( !ascii_strcasecmp (model, "chain") ) return 1; else if ( !ascii_strcasecmp (model, "steed") ) return 2; else return -1; } /* Open the FILENAME for read and return the file descriptor. Stop with an error message in case of problems. "-" denotes stdin and if special filenames are allowed the given fd is opened instead. */ static int open_read (const char *filename) { int fd; if (filename[0] == '-' && !filename[1]) { set_binary (stdin); return 0; /* stdin */ } fd = check_special_filename (filename, 0, 0); if (fd != -1) return fd; fd = gnupg_open (filename, O_RDONLY | O_BINARY, 0); if (fd == -1) { log_error (_("can't open '%s': %s\n"), filename, strerror (errno)); gpgsm_exit (2); } return fd; } /* Same as open_read but return an estream_t. */ static estream_t open_es_fread (const char *filename, const char *mode) { int fd; estream_t fp; if (filename[0] == '-' && !filename[1]) fd = fileno (stdin); else fd = check_special_filename (filename, 0, 0); if (fd != -1) { fp = es_fdopen_nc (fd, mode); if (!fp) { log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno)); gpgsm_exit (2); } return fp; } fp = es_fopen (filename, mode); if (!fp) { log_error (_("can't open '%s': %s\n"), filename, strerror (errno)); gpgsm_exit (2); } return fp; } /* Open FILENAME for fwrite and return an extended stream. Stop with an error message in case of problems. "-" denotes stdout and if special filenames are allowed the given fd is opened instead. Caller must close the returned stream. */ static estream_t open_es_fwrite (const char *filename) { int fd; estream_t fp; if (filename[0] == '-' && !filename[1]) { fflush (stdout); fp = es_fdopen_nc (fileno(stdout), "wb"); return fp; } fd = check_special_filename (filename, 1, 0); if (fd != -1) { fp = es_fdopen_nc (fd, "wb"); if (!fp) { log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno)); gpgsm_exit (2); } return fp; } fp = es_fopen (filename, "wb"); if (!fp) { log_error (_("can't open '%s': %s\n"), filename, strerror (errno)); gpgsm_exit (2); } return fp; } static void run_protect_tool (int argc, char **argv) { #ifdef HAVE_W32_SYSTEM (void)argc; (void)argv; #else const char *pgm; char **av; int i; if (!opt.protect_tool_program || !*opt.protect_tool_program) pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL); else pgm = opt.protect_tool_program; av = xcalloc (argc+2, sizeof *av); av[0] = strrchr (pgm, '/'); if (!av[0]) av[0] = xstrdup (pgm); for (i=1; argc; i++, argc--, argv++) av[i] = *argv; av[i] = NULL; execv (pgm, av); log_error ("error executing '%s': %s\n", pgm, strerror (errno)); #endif /*!HAVE_W32_SYSTEM*/ gpgsm_exit (2); } diff --git a/sm/import.c b/sm/import.c index ca693824a..7ee1d7164 100644 --- a/sm/import.c +++ b/sm/import.c @@ -1,939 +1,940 @@ /* import.c - Import certificates * Copyright (C) 2001, 2003, 2004, 2009, 2010 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 . */ #include #include #include #include #include #include #include #include #include "gpgsm.h" #include #include #include "keydb.h" #include "../common/exechelp.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */ #include "../common/membuf.h" #include "minip12.h" /* The arbitrary limit of one PKCS#12 object. */ #define MAX_P12OBJ_SIZE 128 /*kb*/ struct stats_s { unsigned long count; unsigned long imported; unsigned long unchanged; unsigned long not_imported; unsigned long secret_read; unsigned long secret_imported; unsigned long secret_dups; }; struct rsa_secret_key_s { gcry_mpi_t n; /* public modulus */ gcry_mpi_t e; /* public exponent */ gcry_mpi_t d; /* exponent */ gcry_mpi_t p; /* prime p. */ gcry_mpi_t q; /* prime q. */ gcry_mpi_t u; /* inverse of p mod q. */ }; static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader, struct stats_s *stats); static void print_imported_status (ctrl_t ctrl, ksba_cert_t cert, int new_cert) { char *fpr; fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); if (new_cert) gpgsm_status2 (ctrl, STATUS_IMPORTED, fpr, "[X.509]", NULL); gpgsm_status2 (ctrl, STATUS_IMPORT_OK, new_cert? "1":"0", fpr, NULL); xfree (fpr); } /* Print an IMPORT_PROBLEM status. REASON is one of: 0 := "No specific reason given". 1 := "Invalid Certificate". 2 := "Issuer Certificate missing". 3 := "Certificate Chain too long". 4 := "Error storing certificate". */ static void print_import_problem (ctrl_t ctrl, ksba_cert_t cert, int reason) { char *fpr = NULL; char buf[25]; int i; sprintf (buf, "%d", reason); if (cert) { fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); /* detetect an error (all high) value */ for (i=0; fpr[i] == 'F'; i++) ; if (!fpr[i]) { xfree (fpr); fpr = NULL; } } gpgsm_status2 (ctrl, STATUS_IMPORT_PROBLEM, buf, fpr, NULL); xfree (fpr); } void print_imported_summary (ctrl_t ctrl, struct stats_s *stats) { char buf[14*25]; if (!opt.quiet) { log_info (_("total number processed: %lu\n"), stats->count); if (stats->imported) { log_info (_(" imported: %lu"), stats->imported ); log_printf ("\n"); } if (stats->unchanged) log_info (_(" unchanged: %lu\n"), stats->unchanged); if (stats->secret_read) log_info (_(" secret keys read: %lu\n"), stats->secret_read ); if (stats->secret_imported) log_info (_(" secret keys imported: %lu\n"), stats->secret_imported ); if (stats->secret_dups) log_info (_(" secret keys unchanged: %lu\n"), stats->secret_dups ); if (stats->not_imported) log_info (_(" not imported: %lu\n"), stats->not_imported); } sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", stats->count, 0l /*stats->no_user_id*/, stats->imported, 0l /*stats->imported_rsa*/, stats->unchanged, 0l /*stats->n_uids*/, 0l /*stats->n_subk*/, 0l /*stats->n_sigs*/, 0l /*stats->n_revoc*/, stats->secret_read, stats->secret_imported, stats->secret_dups, 0l /*stats->skipped_new_keys*/, stats->not_imported ); gpgsm_status (ctrl, STATUS_IMPORT_RES, buf); } static void check_and_store (ctrl_t ctrl, struct stats_s *stats, ksba_cert_t cert, int depth) { int rc; if (stats) stats->count++; if ( depth >= 50 ) { log_error (_("certificate chain too long\n")); if (stats) stats->not_imported++; print_import_problem (ctrl, cert, 3); return; } /* Some basic checks, but don't care about missing certificates; this is so that we are able to import entire certificate chains w/o requiring a special order (i.e. root-CA first). This used to be different but because gpgsm_verify even imports certificates without any checks, it doesn't matter much and the code gets much cleaner. A housekeeping function to remove certificates w/o an anchor would be nice, though. Optionally we do a full validation in addition to the basic test. */ rc = gpgsm_basic_cert_check (ctrl, cert); if (!rc && ctrl->with_validation) rc = gpgsm_validate_chain (ctrl, cert, "", NULL, 0, NULL, 0, NULL); if (!rc || (!ctrl->with_validation && (gpg_err_code (rc) == GPG_ERR_MISSING_CERT || gpg_err_code (rc) == GPG_ERR_MISSING_ISSUER_CERT))) { int existed; if (!keydb_store_cert (ctrl, cert, 0, &existed)) { ksba_cert_t next = NULL; if (!existed) { print_imported_status (ctrl, cert, 1); if (stats) stats->imported++; } else { print_imported_status (ctrl, cert, 0); if (stats) stats->unchanged++; } if (opt.verbose > 1 && existed) { if (depth) log_info ("issuer certificate already in DB\n"); else log_info ("certificate already in DB\n"); } else if (opt.verbose && !existed) { if (depth) log_info ("issuer certificate imported\n"); else log_info ("certificate imported\n"); } /* Now lets walk up the chain and import all certificates up the chain. This is required in case we already stored parent certificates in the ephemeral keybox. Do not update the statistics, though. */ if (!gpgsm_walk_cert_chain (ctrl, cert, &next)) { check_and_store (ctrl, NULL, next, depth+1); ksba_cert_release (next); } } else { log_error (_("error storing certificate\n")); if (stats) stats->not_imported++; print_import_problem (ctrl, cert, 4); } } else { log_error (_("basic certificate checks failed - not imported\n")); if (stats) stats->not_imported++; /* We keep the test for GPG_ERR_MISSING_CERT only in case GPG_ERR_MISSING_CERT has been used instead of the newer GPG_ERR_MISSING_ISSUER_CERT. */ print_import_problem (ctrl, cert, gpg_err_code (rc) == GPG_ERR_MISSING_ISSUER_CERT? 2 : gpg_err_code (rc) == GPG_ERR_MISSING_CERT? 2 : gpg_err_code (rc) == GPG_ERR_BAD_CERT? 1 : 0); } } static int import_one (ctrl_t ctrl, struct stats_s *stats, int in_fd) { int rc; gnupg_ksba_io_t b64reader = NULL; ksba_reader_t reader; ksba_cert_t cert = NULL; ksba_cms_t cms = NULL; estream_t fp = NULL; ksba_content_type_t ct; int any = 0; fp = es_fdopen_nc (in_fd, "rb"); if (!fp) { rc = gpg_error_from_syserror (); log_error ("fdopen() failed: %s\n", strerror (errno)); goto leave; } rc = gnupg_ksba_create_reader (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0) | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0) | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0) | GNUPG_KSBA_IO_MULTIPEM), fp, &reader); if (rc) { log_error ("can't create reader: %s\n", gpg_strerror (rc)); goto leave; } /* We need to loop here to handle multiple PEM objects in one file. */ do { ksba_cms_release (cms); cms = NULL; ksba_cert_release (cert); cert = NULL; ct = ksba_cms_identify (reader); if (ct == KSBA_CT_SIGNED_DATA) { /* This is probably a signed-only message - import the certs */ ksba_stop_reason_t stopreason; int i; rc = ksba_cms_new (&cms); if (rc) goto leave; rc = ksba_cms_set_reader_writer (cms, reader, NULL); if (rc) { log_error ("ksba_cms_set_reader_writer failed: %s\n", gpg_strerror (rc)); goto leave; } do { rc = ksba_cms_parse (cms, &stopreason); if (rc) { log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc)); goto leave; } if (stopreason == KSBA_SR_BEGIN_DATA) log_info ("not a certs-only message\n"); } while (stopreason != KSBA_SR_READY); for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++) { check_and_store (ctrl, stats, cert, 0); ksba_cert_release (cert); cert = NULL; } if (!i) log_error ("no certificate found\n"); else any = 1; } else if (ct == KSBA_CT_PKCS12) { /* This seems to be a pkcs12 message. */ rc = parse_p12 (ctrl, reader, stats); if (!rc) any = 1; } else if (ct == KSBA_CT_NONE) { /* Failed to identify this message - assume a certificate */ rc = ksba_cert_new (&cert); if (rc) goto leave; rc = ksba_cert_read_der (cert, reader); if (rc) goto leave; check_and_store (ctrl, stats, cert, 0); any = 1; } else { log_error ("can't extract certificates from input\n"); rc = gpg_error (GPG_ERR_NO_DATA); } ksba_reader_clear (reader, NULL, NULL); } while (!gnupg_ksba_reader_eof_seen (b64reader)); leave: if (any && gpg_err_code (rc) == GPG_ERR_EOF) rc = 0; ksba_cms_release (cms); ksba_cert_release (cert); gnupg_ksba_destroy_reader (b64reader); es_fclose (fp); return rc; } /* Re-import certifciates. IN_FD is a list of linefeed delimited fingerprints t re-import. The actual re-import is done by clearing the ephemeral flag. */ static int reimport_one (ctrl_t ctrl, struct stats_s *stats, int in_fd) { gpg_error_t err = 0; estream_t fp = NULL; char line[100]; /* Sufficient for a fingerprint. */ KEYDB_HANDLE kh; KEYDB_SEARCH_DESC desc; ksba_cert_t cert = NULL; unsigned int flags; kh = keydb_new (); if (!kh) { err = gpg_error (GPG_ERR_ENOMEM);; log_error (_("failed to allocate keyDB handle\n")); goto leave; } keydb_set_ephemeral (kh, 1); fp = es_fdopen_nc (in_fd, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error ("es_fdopen(%d) failed: %s\n", in_fd, gpg_strerror (err)); goto leave; } while (es_fgets (line, DIM(line)-1, fp) ) { if (*line && line[strlen(line)-1] != '\n') { err = gpg_error (GPG_ERR_LINE_TOO_LONG); goto leave; } trim_spaces (line); if (!*line) continue; stats->count++; err = classify_user_id (line, &desc, 0); if (err) { print_import_problem (ctrl, NULL, 0); stats->not_imported++; continue; } keydb_search_reset (kh); err = keydb_search (ctrl, kh, &desc, 1); if (err) { print_import_problem (ctrl, NULL, 0); stats->not_imported++; continue; } ksba_cert_release (cert); cert = NULL; err = keydb_get_cert (kh, &cert); if (err) { log_error ("keydb_get_cert() failed: %s\n", gpg_strerror (err)); print_import_problem (ctrl, NULL, 1); stats->not_imported++; continue; } err = keydb_get_flags (kh, KEYBOX_FLAG_BLOB, 0, &flags); if (err) { log_error (_("error getting stored flags: %s\n"), gpg_strerror (err)); print_imported_status (ctrl, cert, 0); stats->not_imported++; continue; } if ( !(flags & KEYBOX_FLAG_BLOB_EPHEMERAL) ) { print_imported_status (ctrl, cert, 0); stats->unchanged++; continue; } err = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0, KEYBOX_FLAG_BLOB_EPHEMERAL, 0); if (err) { log_error ("clearing ephemeral flag failed: %s\n", gpg_strerror (err)); print_import_problem (ctrl, cert, 0); stats->not_imported++; continue; } print_imported_status (ctrl, cert, 1); stats->imported++; } err = 0; if (es_ferror (fp)) { err = gpg_error_from_syserror (); log_error ("error reading fd %d: %s\n", in_fd, gpg_strerror (err)); goto leave; } leave: ksba_cert_release (cert); keydb_release (kh); es_fclose (fp); return err; } int gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode) { int rc; struct stats_s stats; memset (&stats, 0, sizeof stats); if (reimport_mode) rc = reimport_one (ctrl, &stats, in_fd); else rc = import_one (ctrl, &stats, in_fd); print_imported_summary (ctrl, &stats); /* If we never printed an error message do it now so that a command line invocation will return with an error (log_error keeps a global errorcount) */ if (rc && !log_get_errorcount (0)) log_error (_("error importing certificate: %s\n"), gpg_strerror (rc)); return rc; } int gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files, int (*of)(const char *fname)) { int rc = 0; struct stats_s stats; memset (&stats, 0, sizeof stats); if (!nfiles) rc = import_one (ctrl, &stats, 0); else { for (; nfiles && !rc ; nfiles--, files++) { int fd = of (*files); rc = import_one (ctrl, &stats, fd); close (fd); if (rc == -1) rc = 0; } } print_imported_summary (ctrl, &stats); /* If we never printed an error message do it now so that a command line invocation will return with an error (log_error keeps a global errorcount) */ if (rc && !log_get_errorcount (0)) log_error (_("error importing certificate: %s\n"), gpg_strerror (rc)); return rc; } /* Check that the RSA secret key SKEY is valid. Swap parameters to the libgcrypt standard. */ static gpg_error_t rsa_key_check (struct rsa_secret_key_s *skey) { int err = 0; gcry_mpi_t t = gcry_mpi_snew (0); gcry_mpi_t t1 = gcry_mpi_snew (0); gcry_mpi_t t2 = gcry_mpi_snew (0); gcry_mpi_t phi = gcry_mpi_snew (0); /* Check that n == p * q. */ gcry_mpi_mul (t, skey->p, skey->q); if (gcry_mpi_cmp( t, skey->n) ) { log_error ("RSA oops: n != p * q\n"); err++; } /* Check that p is less than q. */ if (gcry_mpi_cmp (skey->p, skey->q) > 0) { gcry_mpi_t tmp; log_info ("swapping secret primes\n"); tmp = gcry_mpi_copy (skey->p); gcry_mpi_set (skey->p, skey->q); gcry_mpi_set (skey->q, tmp); gcry_mpi_release (tmp); /* Recompute u. */ gcry_mpi_invm (skey->u, skey->p, skey->q); } /* Check that e divides neither p-1 nor q-1. */ gcry_mpi_sub_ui (t, skey->p, 1 ); gcry_mpi_div (NULL, t, t, skey->e, 0); if (!gcry_mpi_cmp_ui( t, 0) ) { log_error ("RSA oops: e divides p-1\n"); err++; } gcry_mpi_sub_ui (t, skey->q, 1); gcry_mpi_div (NULL, t, t, skey->e, 0); if (!gcry_mpi_cmp_ui( t, 0)) { log_info ("RSA oops: e divides q-1\n" ); err++; } /* Check that d is correct. */ gcry_mpi_sub_ui (t1, skey->p, 1); gcry_mpi_sub_ui (t2, skey->q, 1); gcry_mpi_mul (phi, t1, t2); gcry_mpi_invm (t, skey->e, phi); if (gcry_mpi_cmp (t, skey->d)) { /* No: try universal exponent. */ gcry_mpi_gcd (t, t1, t2); gcry_mpi_div (t, NULL, phi, t, 0); gcry_mpi_invm (t, skey->e, t); if (gcry_mpi_cmp (t, skey->d)) { log_error ("RSA oops: bad secret exponent\n"); err++; } } /* Check for correctness of u. */ gcry_mpi_invm (t, skey->p, skey->q); if (gcry_mpi_cmp (t, skey->u)) { log_info ("RSA oops: bad u parameter\n"); err++; } if (err) log_info ("RSA secret key check failed\n"); gcry_mpi_release (t); gcry_mpi_release (t1); gcry_mpi_release (t2); gcry_mpi_release (phi); return err? gpg_error (GPG_ERR_BAD_SECKEY):0; } /* Object passed to store_cert_cb. */ struct store_cert_parm_s { gpg_error_t err; /* First error seen. */ struct stats_s *stats; /* The stats object. */ ctrl_t ctrl; /* The control object. */ }; /* Helper to store the DER encoded certificate CERTDATA of length CERTDATALEN. */ static void store_cert_cb (void *opaque, const unsigned char *certdata, size_t certdatalen) { struct store_cert_parm_s *parm = opaque; gpg_error_t err; ksba_cert_t cert; err = ksba_cert_new (&cert); if (err) { if (!parm->err) parm->err = err; return; } err = ksba_cert_init_from_mem (cert, certdata, certdatalen); if (err) { log_error ("failed to parse a certificate: %s\n", gpg_strerror (err)); if (!parm->err) parm->err = err; } else check_and_store (parm->ctrl, parm->stats, cert, 0); ksba_cert_release (cert); } /* Assume that the reader is at a pkcs#12 message and try to import certificates from that stupid format. We will transfer secret keys to the agent. */ static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader, struct stats_s *stats) { gpg_error_t err = 0; char buffer[1024]; size_t ntotal, nread; membuf_t p12mbuf; char *p12buffer = NULL; size_t p12buflen; size_t p12bufoff; gcry_mpi_t *kparms = NULL; struct rsa_secret_key_s sk; char *passphrase = NULL; unsigned char *key = NULL; size_t keylen; void *kek = NULL; size_t keklen; unsigned char *wrappedkey = NULL; size_t wrappedkeylen; gcry_cipher_hd_t cipherhd = NULL; gcry_sexp_t s_key = NULL; unsigned char grip[20]; int bad_pass = 0; int i; struct store_cert_parm_s store_cert_parm; memset (&store_cert_parm, 0, sizeof store_cert_parm); store_cert_parm.ctrl = ctrl; store_cert_parm.stats = stats; init_membuf (&p12mbuf, 4096); ntotal = 0; while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread))) { if (ntotal >= MAX_P12OBJ_SIZE*1024) { /* Arbitrary limit to avoid DoS attacks. */ err = gpg_error (GPG_ERR_TOO_LARGE); log_error ("pkcs#12 object is larger than %dk\n", MAX_P12OBJ_SIZE); break; } put_membuf (&p12mbuf, buffer, nread); ntotal += nread; } if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; if (!err) { p12buffer = get_membuf (&p12mbuf, &p12buflen); if (!p12buffer) err = gpg_error_from_syserror (); } if (err) { log_error (_("error reading input: %s\n"), gpg_strerror (err)); goto leave; } /* GnuPG 2.0.4 accidentally created binary P12 files with the string "The passphrase is %s encoded.\n\n" prepended to the ASN.1 data. We fix that here. */ if (p12buflen > 29 && !memcmp (p12buffer, "The passphrase is ", 18)) { for (p12bufoff=18; p12bufoff < p12buflen && p12buffer[p12bufoff] != '\n'; p12bufoff++) ; p12bufoff++; if (p12bufoff < p12buflen && p12buffer[p12bufoff] == '\n') p12bufoff++; } else p12bufoff = 0; err = gpgsm_agent_ask_passphrase (ctrl, i18n_utf8 ("Please enter the passphrase to unprotect the PKCS#12 object."), 0, &passphrase); if (err) goto leave; kparms = p12_parse (p12buffer + p12bufoff, p12buflen - p12bufoff, passphrase, store_cert_cb, &store_cert_parm, &bad_pass); xfree (passphrase); passphrase = NULL; if (!kparms) { log_error ("error parsing or decrypting the PKCS#12 file\n"); err = gpg_error (GPG_ERR_INV_OBJ); goto leave; } /* print_mpi (" n", kparms[0]); */ /* print_mpi (" e", kparms[1]); */ /* print_mpi (" d", kparms[2]); */ /* print_mpi (" p", kparms[3]); */ /* print_mpi (" q", kparms[4]); */ /* print_mpi ("dmp1", kparms[5]); */ /* print_mpi ("dmq1", kparms[6]); */ /* print_mpi (" u", kparms[7]); */ sk.n = kparms[0]; sk.e = kparms[1]; sk.d = kparms[2]; sk.q = kparms[3]; sk.p = kparms[4]; sk.u = kparms[7]; err = rsa_key_check (&sk); if (err) goto leave; /* print_mpi (" n", sk.n); */ /* print_mpi (" e", sk.e); */ /* print_mpi (" d", sk.d); */ /* print_mpi (" p", sk.p); */ /* print_mpi (" q", sk.q); */ /* print_mpi (" u", sk.u); */ /* Create an S-expression from the parameters. */ err = gcry_sexp_build (&s_key, NULL, "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))", sk.n, sk.e, sk.d, sk.p, sk.q, sk.u, NULL); for (i=0; i < 8; i++) gcry_mpi_release (kparms[i]); gcry_free (kparms); kparms = NULL; if (err) { log_error ("failed to create S-expression from key: %s\n", gpg_strerror (err)); goto leave; } /* Compute the keygrip. */ if (!gcry_pk_get_keygrip (s_key, grip)) { err = gpg_error (GPG_ERR_GENERAL); log_error ("can't calculate keygrip\n"); goto leave; } - log_printhex (grip, 20, "keygrip="); + if (DBG_X509) + log_printhex (grip, 20, "keygrip="); /* Convert to canonical encoding using a function which pads it to a multiple of 64 bits. We need this padding for AESWRAP. */ err = make_canon_sexp_pad (s_key, 1, &key, &keylen); if (err) { log_error ("error creating canonical S-expression\n"); goto leave; } gcry_sexp_release (s_key); s_key = NULL; /* Get the current KEK. */ err = gpgsm_agent_keywrap_key (ctrl, 0, &kek, &keklen); if (err) { log_error ("error getting the KEK: %s\n", gpg_strerror (err)); goto leave; } /* Wrap the key. */ err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_AESWRAP, 0); if (err) goto leave; err = gcry_cipher_setkey (cipherhd, kek, keklen); if (err) goto leave; xfree (kek); kek = NULL; wrappedkeylen = keylen + 8; wrappedkey = xtrymalloc (wrappedkeylen); if (!wrappedkey) { err = gpg_error_from_syserror (); goto leave; } err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen); if (err) goto leave; xfree (key); key = NULL; gcry_cipher_close (cipherhd); cipherhd = NULL; /* Send the wrapped key to the agent. */ err = gpgsm_agent_import_key (ctrl, wrappedkey, wrappedkeylen); if (!err) { stats->count++; stats->secret_read++; stats->secret_imported++; } else if ( gpg_err_code (err) == GPG_ERR_EEXIST ) { err = 0; stats->count++; stats->secret_read++; stats->secret_dups++; } /* If we did not get an error from storing the secret key we return a possible error from parsing the certificates. We do this after storing the secret keys so that a bad certificate does not inhibit our chance to store the secret key. */ if (!err && store_cert_parm.err) err = store_cert_parm.err; leave: if (kparms) { for (i=0; i < 8; i++) gcry_mpi_release (kparms[i]); gcry_free (kparms); kparms = NULL; } xfree (key); gcry_sexp_release (s_key); xfree (passphrase); gcry_cipher_close (cipherhd); xfree (wrappedkey); xfree (kek); xfree (get_membuf (&p12mbuf, NULL)); xfree (p12buffer); if (bad_pass) { /* We only write a plain error code and not direct BAD_PASSPHRASE because the pkcs12 parser might issue this message multiple times, BAD_PASSPHRASE in general requires a keyID and parts of the import might actually succeed so that IMPORT_PROBLEM is also not appropriate. */ gpgsm_status_with_err_code (ctrl, STATUS_ERROR, "import.parsep12", GPG_ERR_BAD_PASSPHRASE); } return err; } diff --git a/sm/minip12.c b/sm/minip12.c index 7087e444c..e1e1bce08 100644 --- a/sm/minip12.c +++ b/sm/minip12.c @@ -1,2620 +1,2633 @@ /* minip12.c - A minimal pkcs-12 implementation. * Copyright (C) 2002, 2003, 2004, 2006, 2011 Free Software Foundation, Inc. * Copyright (C) 2014 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 . */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef TEST #include #include #endif #include "../common/logging.h" #include "../common/utf8conv.h" #include "minip12.h" #ifndef DIM #define DIM(v) (sizeof(v)/sizeof((v)[0])) #endif enum { UNIVERSAL = 0, APPLICATION = 1, ASNCONTEXT = 2, PRIVATE = 3 }; enum { TAG_NONE = 0, TAG_BOOLEAN = 1, TAG_INTEGER = 2, TAG_BIT_STRING = 3, TAG_OCTET_STRING = 4, TAG_NULL = 5, TAG_OBJECT_ID = 6, TAG_OBJECT_DESCRIPTOR = 7, TAG_EXTERNAL = 8, TAG_REAL = 9, TAG_ENUMERATED = 10, TAG_EMBEDDED_PDV = 11, TAG_UTF8_STRING = 12, TAG_REALTIVE_OID = 13, TAG_SEQUENCE = 16, TAG_SET = 17, TAG_NUMERIC_STRING = 18, TAG_PRINTABLE_STRING = 19, TAG_TELETEX_STRING = 20, TAG_VIDEOTEX_STRING = 21, TAG_IA5_STRING = 22, TAG_UTC_TIME = 23, TAG_GENERALIZED_TIME = 24, TAG_GRAPHIC_STRING = 25, TAG_VISIBLE_STRING = 26, TAG_GENERAL_STRING = 27, TAG_UNIVERSAL_STRING = 28, TAG_CHARACTER_STRING = 29, TAG_BMP_STRING = 30 }; static unsigned char const oid_data[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01 }; static unsigned char const oid_encryptedData[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x06 }; static unsigned char const oid_pkcs_12_keyBag[11] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x01 }; static unsigned char const oid_pkcs_12_pkcs_8ShroudedKeyBag[11] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x02 }; static unsigned char const oid_pkcs_12_CertBag[11] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x03 }; static unsigned char const oid_pkcs_12_CrlBag[11] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x04 }; static unsigned char const oid_pbeWithSHAAnd3_KeyTripleDES_CBC[10] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03 }; static unsigned char const oid_pbeWithSHAAnd40BitRC2_CBC[10] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06 }; static unsigned char const oid_x509Certificate_for_pkcs_12[10] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x16, 0x01 }; static unsigned char const oid_pkcs5PBKDF2[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C }; static unsigned char const oid_pkcs5PBES2[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D }; static unsigned char const oid_aes128_CBC[9] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02 }; static unsigned char const oid_rsaEncryption[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 }; static unsigned char const data_3desiter2048[30] = { 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30, 0x0E, 0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 }; #define DATA_3DESITER2048_SALT_OFF 18 static unsigned char const data_rc2iter2048[30] = { 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06, 0x30, 0x0E, 0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 }; #define DATA_RC2ITER2048_SALT_OFF 18 static unsigned char const data_mactemplate[51] = { 0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x04, 0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x02, 0x08, 0x00 }; #define DATA_MACTEMPLATE_MAC_OFF 17 #define DATA_MACTEMPLATE_SALT_OFF 39 static unsigned char const data_attrtemplate[106] = { 0x31, 0x7c, 0x30, 0x55, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x14, 0x31, 0x48, 0x1e, 0x46, 0x00, 0x47, 0x00, 0x6e, 0x00, 0x75, 0x00, 0x50, 0x00, 0x47, 0x00, 0x20, 0x00, 0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x74, 0x00, 0x65, 0x00, 0x64, 0x00, 0x20, 0x00, 0x63, 0x00, 0x65, 0x00, 0x72, 0x00, 0x74, 0x00, 0x69, 0x00, 0x66, 0x00, 0x69, 0x00, 0x63, 0x00, 0x61, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, 0x31, 0x16, 0x04, 0x14 }; /* Need to append SHA-1 digest. */ #define DATA_ATTRTEMPLATE_KEYID_OFF 73 struct buffer_s { unsigned char *buffer; size_t length; }; struct tag_info { int class; int is_constructed; unsigned long tag; unsigned long length; /* length part of the TLV */ int nhdr; int ndef; /* It is an indefinite length */ }; +static int opt_verbose; + + +void +p12_set_verbosity (int verbose) +{ + opt_verbose = verbose; +} + + /* Parse the buffer at the address BUFFER which is of SIZE and return the tag and the length part from the TLV triplet. Update BUFFER and SIZE on success. Checks that the encoded length does not exhaust the length of the provided buffer. */ static int parse_tag (unsigned char const **buffer, size_t *size, struct tag_info *ti) { int c; unsigned long tag; const unsigned char *buf = *buffer; size_t length = *size; ti->length = 0; ti->ndef = 0; ti->nhdr = 0; /* Get the tag */ if (!length) return -1; /* premature eof */ c = *buf++; length--; ti->nhdr++; ti->class = (c & 0xc0) >> 6; ti->is_constructed = !!(c & 0x20); tag = c & 0x1f; if (tag == 0x1f) { tag = 0; do { tag <<= 7; if (!length) return -1; /* premature eof */ c = *buf++; length--; ti->nhdr++; tag |= c & 0x7f; } while (c & 0x80); } ti->tag = tag; /* Get the length */ if (!length) return -1; /* prematureeof */ c = *buf++; length--; ti->nhdr++; if ( !(c & 0x80) ) ti->length = c; else if (c == 0x80) ti->ndef = 1; else if (c == 0xff) return -1; /* forbidden length value */ else { unsigned long len = 0; int count = c & 0x7f; for (; count; count--) { len <<= 8; if (!length) return -1; /* premature_eof */ c = *buf++; length--; ti->nhdr++; len |= c & 0xff; } ti->length = len; } if (ti->class == UNIVERSAL && !ti->tag) ti->length = 0; if (ti->length > length) return -1; /* data larger than buffer. */ *buffer = buf; *size = length; return 0; } /* Given an ASN.1 chunk of a structure like: 24 NDEF: OCTET STRING -- This is not passed to us 04 1: OCTET STRING -- INPUT point s to here : 30 04 1: OCTET STRING : 80 [...] 04 2: OCTET STRING : 00 00 : } -- This denotes a Null tag and are the last -- two bytes in INPUT. Create a new buffer with the content of that octet string. INPUT is the original buffer with a length as stored at LENGTH. Returns NULL on error or a new malloced buffer with the length of this new buffer stored at LENGTH and the number of bytes parsed from input are added to the value stored at INPUT_CONSUMED. INPUT_CONSUMED is allowed to be passed as NULL if the caller is not interested in this value. */ static unsigned char * cram_octet_string (const unsigned char *input, size_t *length, size_t *input_consumed) { const unsigned char *s = input; size_t n = *length; unsigned char *output, *d; struct tag_info ti; /* Allocate output buf. We know that it won't be longer than the input buffer. */ d = output = gcry_malloc (n); if (!output) goto bailout; for (;;) { if (parse_tag (&s, &n, &ti)) goto bailout; if (ti.class == UNIVERSAL && ti.tag == TAG_OCTET_STRING && !ti.ndef && !ti.is_constructed) { memcpy (d, s, ti.length); s += ti.length; d += ti.length; n -= ti.length; } else if (ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed) break; /* Ready */ else goto bailout; } *length = d - output; if (input_consumed) *input_consumed += s - input; return output; bailout: if (input_consumed) *input_consumed += s - input; gcry_free (output); return NULL; } static int string_to_key (int id, char *salt, size_t saltlen, int iter, const char *pw, int req_keylen, unsigned char *keybuf) { int rc, i, j; gcry_md_hd_t md; gcry_mpi_t num_b1 = NULL; int pwlen; unsigned char hash[20], buf_b[64], buf_i[128], *p; size_t cur_keylen; size_t n; cur_keylen = 0; pwlen = strlen (pw); if (pwlen > 63/2) { log_error ("password too long\n"); return -1; } if (saltlen < 8) { log_error ("salt too short\n"); return -1; } /* Store salt and password in BUF_I */ p = buf_i; for(i=0; i < 64; i++) *p++ = salt [i%saltlen]; for(i=j=0; i < 64; i += 2) { *p++ = 0; *p++ = pw[j]; if (++j > pwlen) /* Note, that we include the trailing zero */ j = 0; } for (;;) { rc = gcry_md_open (&md, GCRY_MD_SHA1, 0); if (rc) { log_error ( "gcry_md_open failed: %s\n", gpg_strerror (rc)); return rc; } for(i=0; i < 64; i++) gcry_md_putc (md, id); gcry_md_write (md, buf_i, 128); memcpy (hash, gcry_md_read (md, 0), 20); gcry_md_close (md); for (i=1; i < iter; i++) gcry_md_hash_buffer (GCRY_MD_SHA1, hash, hash, 20); for (i=0; i < 20 && cur_keylen < req_keylen; i++) keybuf[cur_keylen++] = hash[i]; if (cur_keylen == req_keylen) { gcry_mpi_release (num_b1); return 0; /* ready */ } /* need more bytes. */ for(i=0; i < 64; i++) buf_b[i] = hash[i % 20]; rc = gcry_mpi_scan (&num_b1, GCRYMPI_FMT_USG, buf_b, 64, &n); if (rc) { log_error ( "gcry_mpi_scan failed: %s\n", gpg_strerror (rc)); return -1; } gcry_mpi_add_ui (num_b1, num_b1, 1); for (i=0; i < 128; i += 64) { gcry_mpi_t num_ij; rc = gcry_mpi_scan (&num_ij, GCRYMPI_FMT_USG, buf_i + i, 64, &n); if (rc) { log_error ( "gcry_mpi_scan failed: %s\n", gpg_strerror (rc)); return -1; } gcry_mpi_add (num_ij, num_ij, num_b1); gcry_mpi_clear_highbit (num_ij, 64*8); rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf_i + i, 64, &n, num_ij); if (rc) { log_error ( "gcry_mpi_print failed: %s\n", gpg_strerror (rc)); return -1; } gcry_mpi_release (num_ij); } } } static int set_key_iv (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter, const char *pw, int keybytes) { unsigned char keybuf[24]; int rc; assert (keybytes == 5 || keybytes == 24); if (string_to_key (1, salt, saltlen, iter, pw, keybytes, keybuf)) return -1; rc = gcry_cipher_setkey (chd, keybuf, keybytes); if (rc) { log_error ( "gcry_cipher_setkey failed: %s\n", gpg_strerror (rc)); return -1; } if (string_to_key (2, salt, saltlen, iter, pw, 8, keybuf)) return -1; rc = gcry_cipher_setiv (chd, keybuf, 8); if (rc) { log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc)); return -1; } return 0; } static int set_key_iv_pbes2 (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter, const void *iv, size_t ivlen, const char *pw, int algo) { unsigned char *keybuf; size_t keylen; int rc; keylen = gcry_cipher_get_algo_keylen (algo); if (!keylen) return -1; keybuf = gcry_malloc_secure (keylen); if (!keybuf) return -1; rc = gcry_kdf_derive (pw, strlen (pw), GCRY_KDF_PBKDF2, GCRY_MD_SHA1, salt, saltlen, iter, keylen, keybuf); if (rc) { log_error ("gcry_kdf_derive failed: %s\n", gpg_strerror (rc)); gcry_free (keybuf); return -1; } rc = gcry_cipher_setkey (chd, keybuf, keylen); gcry_free (keybuf); if (rc) { log_error ("gcry_cipher_setkey failed: %s\n", gpg_strerror (rc)); return -1; } rc = gcry_cipher_setiv (chd, iv, ivlen); if (rc) { log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc)); return -1; } return 0; } static void crypt_block (unsigned char *buffer, size_t length, char *salt, size_t saltlen, int iter, const void *iv, size_t ivlen, const char *pw, int cipher_algo, int encrypt) { gcry_cipher_hd_t chd; int rc; rc = gcry_cipher_open (&chd, cipher_algo, GCRY_CIPHER_MODE_CBC, 0); if (rc) { log_error ( "gcry_cipher_open failed: %s\n", gpg_strerror(rc)); wipememory (buffer, length); return; } if (cipher_algo == GCRY_CIPHER_AES128 ? set_key_iv_pbes2 (chd, salt, saltlen, iter, iv, ivlen, pw, cipher_algo) : set_key_iv (chd, salt, saltlen, iter, pw, cipher_algo == GCRY_CIPHER_RFC2268_40? 5:24)) { wipememory (buffer, length); goto leave; } rc = encrypt? gcry_cipher_encrypt (chd, buffer, length, NULL, 0) : gcry_cipher_decrypt (chd, buffer, length, NULL, 0); if (rc) { wipememory (buffer, length); log_error ( "en/de-crytion failed: %s\n", gpg_strerror (rc)); goto leave; } leave: gcry_cipher_close (chd); } /* Decrypt a block of data and try several encodings of the key. CIPHERTEXT is the encrypted data of size LENGTH bytes; PLAINTEXT is a buffer of the same size to receive the decryption result. SALT, SALTLEN, ITER and PW are the information required for decryption and CIPHER_ALGO is the algorithm id to use. CHECK_FNC is a function called with the plaintext and used to check whether the decryption succeeded; i.e. that a correct passphrase has been given. That function shall return true if the decryption has likely succeeded. */ static void decrypt_block (const void *ciphertext, unsigned char *plaintext, size_t length, char *salt, size_t saltlen, int iter, const void *iv, size_t ivlen, const char *pw, int cipher_algo, int (*check_fnc) (const void *, size_t)) { static const char * const charsets[] = { "", /* No conversion - use the UTF-8 passphrase direct. */ "ISO-8859-1", "ISO-8859-15", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "KOI8-R", "IBM437", "IBM850", "EUC-JP", "BIG5", NULL }; int charsetidx = 0; char *convertedpw = NULL; /* Malloced and converted password or NULL. */ size_t convertedpwsize = 0; /* Allocated length. */ for (charsetidx=0; charsets[charsetidx]; charsetidx++) { if (*charsets[charsetidx]) { jnlib_iconv_t cd; const char *inptr; char *outptr; size_t inbytes, outbytes; if (!convertedpw) { /* We assume one byte encodings. Thus we can allocate the buffer of the same size as the original passphrase; the result will actually be shorter then. */ convertedpwsize = strlen (pw) + 1; convertedpw = gcry_malloc_secure (convertedpwsize); if (!convertedpw) { log_info ("out of secure memory while" " converting passphrase\n"); break; /* Give up. */ } } cd = jnlib_iconv_open (charsets[charsetidx], "utf-8"); if (cd == (jnlib_iconv_t)(-1)) continue; inptr = pw; inbytes = strlen (pw); outptr = convertedpw; outbytes = convertedpwsize - 1; if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes, &outptr, &outbytes) == (size_t)-1) { jnlib_iconv_close (cd); continue; } *outptr = 0; jnlib_iconv_close (cd); log_info ("decryption failed; trying charset '%s'\n", charsets[charsetidx]); } memcpy (plaintext, ciphertext, length); crypt_block (plaintext, length, salt, saltlen, iter, iv, ivlen, convertedpw? convertedpw:pw, cipher_algo, 0); if (check_fnc (plaintext, length)) break; /* Decryption succeeded. */ } gcry_free (convertedpw); } /* Return true if the decryption of an bag_encrypted_data object has likely succeeded. */ static int bag_decrypted_data_p (const void *plaintext, size_t length) { struct tag_info ti; const unsigned char *p = plaintext; size_t n = length; /* { */ /* # warning debug code is enabled */ /* FILE *fp = fopen ("tmp-rc2-plain.der", "wb"); */ /* if (!fp || fwrite (p, n, 1, fp) != 1) */ /* exit (2); */ /* fclose (fp); */ /* } */ if (parse_tag (&p, &n, &ti)) return 0; if (ti.class || ti.tag != TAG_SEQUENCE) return 0; if (parse_tag (&p, &n, &ti)) return 0; return 1; } /* Note: If R_RESULT is passed as NULL, a key object as already be processed and thus we need to skip it here. */ static int parse_bag_encrypted_data (const unsigned char *buffer, size_t length, int startoffset, size_t *r_consumed, const char *pw, void (*certcb)(void*, const unsigned char*, size_t), void *certcbarg, gcry_mpi_t **r_result, int *r_badpass) { struct tag_info ti; const unsigned char *p = buffer; const unsigned char *p_start = buffer; size_t n = length; const char *where; char salt[20]; size_t saltlen; char iv[16]; unsigned int iter; unsigned char *plain = NULL; int bad_pass = 0; unsigned char *cram_buffer = NULL; size_t consumed = 0; /* Number of bytes consumed from the original buffer. */ int is_3des = 0; int is_pbes2 = 0; gcry_mpi_t *result = NULL; int result_count; if (r_result) *r_result = NULL; where = "start"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_SEQUENCE) goto bailout; where = "bag.encryptedData.version"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 0) goto bailout; p++; n--; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_SEQUENCE) goto bailout; where = "bag.encryptedData.data"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data) || memcmp (p, oid_data, DIM(oid_data))) goto bailout; p += DIM(oid_data); n -= DIM(oid_data); where = "bag.encryptedData.keyinfo"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pbeWithSHAAnd40BitRC2_CBC) && !memcmp (p, oid_pbeWithSHAAnd40BitRC2_CBC, DIM(oid_pbeWithSHAAnd40BitRC2_CBC))) { p += DIM(oid_pbeWithSHAAnd40BitRC2_CBC); n -= DIM(oid_pbeWithSHAAnd40BitRC2_CBC); } else if (!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC) && !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC, DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC))) { p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC); n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC); is_3des = 1; } else if (!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pkcs5PBES2) && !memcmp (p, oid_pkcs5PBES2, ti.length)) { p += ti.length; n -= ti.length; is_pbes2 = 1; } else goto bailout; if (is_pbes2) { where = "pkcs5PBES2-params"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pkcs5PBKDF2) && !memcmp (p, oid_pkcs5PBKDF2, ti.length))) goto bailout; /* Not PBKDF2. */ p += ti.length; n -= ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length >= 8 && ti.length < sizeof salt)) goto bailout; /* No salt or unsupported length. */ saltlen = ti.length; memcpy (salt, p, saltlen); p += saltlen; n -= saltlen; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length)) goto bailout; /* No valid iteration count. */ for (iter=0; ti.length; ti.length--) { iter <<= 8; iter |= (*p++) & 0xff; n--; } /* Note: We don't support the optional parameters but assume that the algorithmIdentifier follows. */ if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_aes128_CBC) && !memcmp (p, oid_aes128_CBC, ti.length))) goto bailout; /* Not AES-128. */ p += ti.length; n -= ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv)) goto bailout; /* Bad IV. */ memcpy (iv, p, sizeof iv); p += sizeof iv; n -= sizeof iv; } else { where = "rc2or3des-params"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OCTET_STRING || ti.length < 8 || ti.length > 20 ) goto bailout; saltlen = ti.length; memcpy (salt, p, saltlen); p += saltlen; n -= saltlen; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_INTEGER || !ti.length ) goto bailout; for (iter=0; ti.length; ti.length--) { iter <<= 8; iter |= (*p++) & 0xff; n--; } } where = "rc2or3desoraes-ciphertext"; if (parse_tag (&p, &n, &ti)) goto bailout; consumed = p - p_start; if (ti.class == ASNCONTEXT && ti.tag == 0 && ti.is_constructed && ti.ndef) { /* Mozilla exported certs now come with single byte chunks of octect strings. (Mozilla Firefox 1.0.4). Arghh. */ where = "cram-rc2or3des-ciphertext"; cram_buffer = cram_octet_string ( p, &n, &consumed); if (!cram_buffer) goto bailout; p = p_start = cram_buffer; if (r_consumed) *r_consumed = consumed; r_consumed = NULL; /* Ugly hack to not update that value any further. */ ti.length = n; } else if (ti.class == ASNCONTEXT && ti.tag == 0 && ti.length ) ; else goto bailout; - log_info ("%lu bytes of %s encrypted text\n",ti.length, - is_pbes2?"AES128":is_3des?"3DES":"RC2"); + if (opt_verbose) + log_info ("%lu bytes of %s encrypted text\n",ti.length, + is_pbes2?"AES128":is_3des?"3DES":"RC2"); plain = gcry_malloc_secure (ti.length); if (!plain) { log_error ("error allocating decryption buffer\n"); goto bailout; } decrypt_block (p, plain, ti.length, salt, saltlen, iter, iv, is_pbes2?16:0, pw, is_pbes2 ? GCRY_CIPHER_AES128 : is_3des ? GCRY_CIPHER_3DES : GCRY_CIPHER_RFC2268_40, bag_decrypted_data_p); n = ti.length; startoffset = 0; p_start = p = plain; where = "outer.outer.seq"; if (parse_tag (&p, &n, &ti)) { bad_pass = 1; goto bailout; } if (ti.class || ti.tag != TAG_SEQUENCE) { bad_pass = 1; goto bailout; } if (parse_tag (&p, &n, &ti)) { bad_pass = 1; goto bailout; } /* Loop over all certificates inside the bag. */ while (n) { int iscrlbag = 0; int iskeybag = 0; where = "certbag.nextcert"; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; where = "certbag.objectidentifier"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OBJECT_ID) goto bailout; if ( ti.length == DIM(oid_pkcs_12_CertBag) && !memcmp (p, oid_pkcs_12_CertBag, DIM(oid_pkcs_12_CertBag))) { p += DIM(oid_pkcs_12_CertBag); n -= DIM(oid_pkcs_12_CertBag); } else if ( ti.length == DIM(oid_pkcs_12_CrlBag) && !memcmp (p, oid_pkcs_12_CrlBag, DIM(oid_pkcs_12_CrlBag))) { p += DIM(oid_pkcs_12_CrlBag); n -= DIM(oid_pkcs_12_CrlBag); iscrlbag = 1; } else if ( ti.length == DIM(oid_pkcs_12_keyBag) && !memcmp (p, oid_pkcs_12_keyBag, DIM(oid_pkcs_12_keyBag))) { /* The TrustedMIME plugin for MS Outlook started to create files with just one outer 3DES encrypted container and inside the certificates as well as the key. */ p += DIM(oid_pkcs_12_keyBag); n -= DIM(oid_pkcs_12_keyBag); iskeybag = 1; } else goto bailout; where = "certbag.before.certheader"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (iscrlbag) { log_info ("skipping unsupported crlBag\n"); p += ti.length; n -= ti.length; } else if (iskeybag && (result || !r_result)) { log_info ("one keyBag already processed; skipping this one\n"); p += ti.length; n -= ti.length; } else if (iskeybag) { int len; - log_info ("processing simple keyBag\n"); + if (opt_verbose) + log_info ("processing simple keyBag\n"); /* Fixme: This code is duplicated from parse_bag_data. */ if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER || ti.length != 1 || *p) goto bailout; p++; n--; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; len = ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (len < ti.nhdr) goto bailout; len -= ti.nhdr; if (ti.class || ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_rsaEncryption) || memcmp (p, oid_rsaEncryption, DIM(oid_rsaEncryption))) goto bailout; p += DIM (oid_rsaEncryption); n -= DIM (oid_rsaEncryption); if (len < ti.length) goto bailout; len -= ti.length; if (n < len) goto bailout; p += len; n -= len; if ( parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_OCTET_STRING) goto bailout; if ( parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; len = ti.length; result = gcry_calloc (10, sizeof *result); if (!result) { log_error ( "error allocating result array\n"); goto bailout; } result_count = 0; where = "reading.keybag.key-parameters"; for (result_count = 0; len && result_count < 9;) { if ( parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER) goto bailout; if (len < ti.nhdr) goto bailout; len -= ti.nhdr; if (len < ti.length) goto bailout; len -= ti.length; if (!result_count && ti.length == 1 && !*p) ; /* ignore the very first one if it is a 0 */ else { int rc; rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p, ti.length, NULL); if (rc) { log_error ("error parsing key parameter: %s\n", gpg_strerror (rc)); goto bailout; } result_count++; } p += ti.length; n -= ti.length; } if (len) goto bailout; } else { - log_info ("processing certBag\n"); + if (opt_verbose) + log_info ("processing certBag\n"); if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_x509Certificate_for_pkcs_12) || memcmp (p, oid_x509Certificate_for_pkcs_12, DIM(oid_x509Certificate_for_pkcs_12))) goto bailout; p += DIM(oid_x509Certificate_for_pkcs_12); n -= DIM(oid_x509Certificate_for_pkcs_12); where = "certbag.before.octetstring"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OCTET_STRING || ti.ndef) goto bailout; /* Return the certificate. */ if (certcb) certcb (certcbarg, p, ti.length); p += ti.length; n -= ti.length; } /* Ugly hack to cope with the padding: Forget about the rest if that is less or equal to the cipher's block length. We can reasonable assume that all valid data will be longer than just one block. */ if (n <= (is_pbes2? 16:8)) n = 0; /* Skip the optional SET with the pkcs12 cert attributes. */ if (n) { where = "bag.attributes"; if (parse_tag (&p, &n, &ti)) goto bailout; if (!ti.class && ti.tag == TAG_SEQUENCE) ; /* No attributes. */ else if (!ti.class && ti.tag == TAG_SET && !ti.ndef) { /* The optional SET. */ p += ti.length; n -= ti.length; if (n <= (is_pbes2?16:8)) n = 0; if (n && parse_tag (&p, &n, &ti)) goto bailout; } else goto bailout; } } if (r_consumed) *r_consumed = consumed; gcry_free (plain); gcry_free (cram_buffer); if (r_result) *r_result = result; return 0; bailout: if (result) { int i; for (i=0; result[i]; i++) gcry_mpi_release (result[i]); gcry_free (result); } if (r_consumed) *r_consumed = consumed; gcry_free (plain); gcry_free (cram_buffer); log_error ("encryptedData error at \"%s\", offset %u\n", where, (unsigned int)((p - p_start)+startoffset)); if (bad_pass) { /* Note, that the following string might be used by other programs to check for a bad passphrase; it should therefore not be translated or changed. */ log_error ("possibly bad passphrase given\n"); *r_badpass = 1; } return -1; } /* Return true if the decryption of a bag_data object has likely succeeded. */ static int bag_data_p (const void *plaintext, size_t length) { struct tag_info ti; const unsigned char *p = plaintext; size_t n = length; /* { */ /* # warning debug code is enabled */ /* FILE *fp = fopen ("tmp-3des-plain-key.der", "wb"); */ /* if (!fp || fwrite (p, n, 1, fp) != 1) */ /* exit (2); */ /* fclose (fp); */ /* } */ if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) return 0; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER || ti.length != 1 || *p) return 0; return 1; } static gcry_mpi_t * parse_bag_data (const unsigned char *buffer, size_t length, int startoffset, size_t *r_consumed, const char *pw) { int rc; struct tag_info ti; const unsigned char *p = buffer; const unsigned char *p_start = buffer; size_t n = length; const char *where; char salt[20]; size_t saltlen; char iv[16]; unsigned int iter; int len; unsigned char *plain = NULL; gcry_mpi_t *result = NULL; int result_count, i; unsigned char *cram_buffer = NULL; size_t consumed = 0; /* Number of bytes consumed from the original buffer. */ int is_pbes2 = 0; where = "start"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OCTET_STRING) goto bailout; consumed = p - p_start; if (ti.is_constructed && ti.ndef) { /* Mozilla exported certs now come with single byte chunks of octect strings. (Mozilla Firefox 1.0.4). Arghh. */ where = "cram-data.outersegs"; cram_buffer = cram_octet_string ( p, &n, &consumed); if (!cram_buffer) goto bailout; p = p_start = cram_buffer; if (r_consumed) *r_consumed = consumed; r_consumed = NULL; /* Ugly hack to not update that value any further. */ } where = "data.outerseqs"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; where = "data.objectidentifier"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag) || memcmp (p, oid_pkcs_12_pkcs_8ShroudedKeyBag, DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag))) goto bailout; p += DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag); n -= DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag); where = "shrouded,outerseqs"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class == 0 && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC) && !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC, DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC))) { p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC); n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC); } else if (ti.class == 0 && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pkcs5PBES2) && !memcmp (p, oid_pkcs5PBES2, DIM(oid_pkcs5PBES2))) { p += DIM(oid_pkcs5PBES2); n -= DIM(oid_pkcs5PBES2); is_pbes2 = 1; } else goto bailout; if (is_pbes2) { where = "pkcs5PBES2-params"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_pkcs5PBKDF2) && !memcmp (p, oid_pkcs5PBKDF2, ti.length))) goto bailout; /* Not PBKDF2. */ p += ti.length; n -= ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length >= 8 && ti.length < sizeof salt)) goto bailout; /* No salt or unsupported length. */ saltlen = ti.length; memcpy (salt, p, saltlen); p += saltlen; n -= saltlen; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length)) goto bailout; /* No valid iteration count. */ for (iter=0; ti.length; ti.length--) { iter <<= 8; iter |= (*p++) & 0xff; n--; } /* Note: We don't support the optional parameters but assume that the algorithmIdentifier follows. */ if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_aes128_CBC) && !memcmp (p, oid_aes128_CBC, ti.length))) goto bailout; /* Not AES-128. */ p += ti.length; n -= ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv)) goto bailout; /* Bad IV. */ memcpy (iv, p, sizeof iv); p += sizeof iv; n -= sizeof iv; } else { where = "3des-params"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OCTET_STRING || ti.length < 8 || ti.length > 20) goto bailout; saltlen = ti.length; memcpy (salt, p, saltlen); p += saltlen; n -= saltlen; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_INTEGER || !ti.length ) goto bailout; for (iter=0; ti.length; ti.length--) { iter <<= 8; iter |= (*p++) & 0xff; n--; } } where = "3desoraes-ciphertext"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class || ti.tag != TAG_OCTET_STRING || !ti.length ) goto bailout; log_info ("%lu bytes of %s encrypted text\n", ti.length, is_pbes2? "AES128":"3DES"); plain = gcry_malloc_secure (ti.length); if (!plain) { log_error ("error allocating decryption buffer\n"); goto bailout; } consumed += p - p_start + ti.length; decrypt_block (p, plain, ti.length, salt, saltlen, iter, iv, is_pbes2? 16:0, pw, is_pbes2? GCRY_CIPHER_AES128 : GCRY_CIPHER_3DES, bag_data_p); n = ti.length; startoffset = 0; p_start = p = plain; where = "decrypted-text"; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER || ti.length != 1 || *p) goto bailout; p++; n--; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; len = ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (len < ti.nhdr) goto bailout; len -= ti.nhdr; if (ti.class || ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_rsaEncryption) || memcmp (p, oid_rsaEncryption, DIM(oid_rsaEncryption))) goto bailout; p += DIM (oid_rsaEncryption); n -= DIM (oid_rsaEncryption); if (len < ti.length) goto bailout; len -= ti.length; if (n < len) goto bailout; p += len; n -= len; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_OCTET_STRING) goto bailout; if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE) goto bailout; len = ti.length; result = gcry_calloc (10, sizeof *result); if (!result) { log_error ( "error allocating result array\n"); goto bailout; } result_count = 0; where = "reading.key-parameters"; for (result_count=0; len && result_count < 9;) { if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER) goto bailout; if (len < ti.nhdr) goto bailout; len -= ti.nhdr; if (len < ti.length) goto bailout; len -= ti.length; if (!result_count && ti.length == 1 && !*p) ; /* ignore the very first one if it is a 0 */ else { rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p, ti.length, NULL); if (rc) { log_error ("error parsing key parameter: %s\n", gpg_strerror (rc)); goto bailout; } result_count++; } p += ti.length; n -= ti.length; } if (len) goto bailout; gcry_free (cram_buffer); if (r_consumed) *r_consumed = consumed; return result; bailout: gcry_free (plain); if (result) { for (i=0; result[i]; i++) gcry_mpi_release (result[i]); gcry_free (result); } gcry_free (cram_buffer); log_error ( "data error at \"%s\", offset %u\n", where, (unsigned int)((p - buffer) + startoffset)); if (r_consumed) *r_consumed = consumed; return NULL; } /* Parse a PKCS12 object and return an array of MPI representing the secret key parameters. This is a very limited implementation in that it is only able to look for 3DES encoded encryptedData and tries to extract the first private key object it finds. In case of an error NULL is returned. CERTCB and CERRTCBARG are used to pass X.509 certificates back to the caller. */ gcry_mpi_t * p12_parse (const unsigned char *buffer, size_t length, const char *pw, void (*certcb)(void*, const unsigned char*, size_t), void *certcbarg, int *r_badpass) { struct tag_info ti; const unsigned char *p = buffer; const unsigned char *p_start = buffer; size_t n = length; const char *where; int bagseqlength, len; int bagseqndef, lenndef; gcry_mpi_t *result = NULL; unsigned char *cram_buffer = NULL; *r_badpass = 0; where = "pfx"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_SEQUENCE) goto bailout; where = "pfxVersion"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 3) goto bailout; p++; n--; where = "authSave"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_SEQUENCE) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data) || memcmp (p, oid_data, DIM(oid_data))) goto bailout; p += DIM(oid_data); n -= DIM(oid_data); if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != ASNCONTEXT || ti.tag) goto bailout; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != UNIVERSAL || ti.tag != TAG_OCTET_STRING) goto bailout; if (ti.is_constructed && ti.ndef) { /* Mozilla exported certs now come with single byte chunks of octect strings. (Mozilla Firefox 1.0.4). Arghh. */ where = "cram-bags"; cram_buffer = cram_octet_string ( p, &n, NULL); if (!cram_buffer) goto bailout; p = p_start = cram_buffer; } where = "bags"; if (parse_tag (&p, &n, &ti)) goto bailout; if (ti.class != UNIVERSAL || ti.tag != TAG_SEQUENCE) goto bailout; bagseqndef = ti.ndef; bagseqlength = ti.length; while (bagseqlength || bagseqndef) { /* log_debug ( "at offset %u\n", (p - p_start)); */ where = "bag-sequence"; if (parse_tag (&p, &n, &ti)) goto bailout; if (bagseqndef && ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed) break; /* Ready */ if (ti.class != UNIVERSAL || ti.tag != TAG_SEQUENCE) goto bailout; if (!bagseqndef) { if (bagseqlength < ti.nhdr) goto bailout; bagseqlength -= ti.nhdr; if (bagseqlength < ti.length) goto bailout; bagseqlength -= ti.length; } lenndef = ti.ndef; len = ti.length; if (parse_tag (&p, &n, &ti)) goto bailout; if (lenndef) len = ti.nhdr; else len -= ti.nhdr; if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_encryptedData) && !memcmp (p, oid_encryptedData, DIM(oid_encryptedData))) { size_t consumed = 0; p += DIM(oid_encryptedData); n -= DIM(oid_encryptedData); if (!lenndef) len -= DIM(oid_encryptedData); where = "bag.encryptedData"; if (parse_bag_encrypted_data (p, n, (p - p_start), &consumed, pw, certcb, certcbarg, result? NULL : &result, r_badpass)) goto bailout; if (lenndef) len += consumed; } else if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_data) && !memcmp (p, oid_data, DIM(oid_data))) { if (result) { log_info ("already got an key object, skipping this one\n"); p += ti.length; n -= ti.length; } else { size_t consumed = 0; p += DIM(oid_data); n -= DIM(oid_data); if (!lenndef) len -= DIM(oid_data); result = parse_bag_data (p, n, (p - p_start), &consumed, pw); if (!result) goto bailout; if (lenndef) len += consumed; } } else { log_info ("unknown bag type - skipped\n"); p += ti.length; n -= ti.length; } if (len < 0 || len > n) goto bailout; p += len; n -= len; if (lenndef) { /* Need to skip the Null Tag. */ if (parse_tag (&p, &n, &ti)) goto bailout; if (!(ti.class == UNIVERSAL && !ti.tag && !ti.is_constructed)) goto bailout; } } gcry_free (cram_buffer); return result; bailout: log_error ("error at \"%s\", offset %u\n", where, (unsigned int)(p - p_start)); if (result) { int i; for (i=0; result[i]; i++) gcry_mpi_release (result[i]); gcry_free (result); } gcry_free (cram_buffer); return NULL; } static size_t compute_tag_length (size_t n) { int needed = 0; if (n < 128) needed += 2; /* tag and one length byte */ else if (n < 256) needed += 3; /* tag, number of length bytes, 1 length byte */ else if (n < 65536) needed += 4; /* tag, number of length bytes, 2 length bytes */ else { log_error ("object too larger to encode\n"); return 0; } return needed; } static unsigned char * store_tag_length (unsigned char *p, int tag, size_t n) { if (tag == TAG_SEQUENCE) tag |= 0x20; /* constructed */ *p++ = tag; if (n < 128) *p++ = n; else if (n < 256) { *p++ = 0x81; *p++ = n; } else if (n < 65536) { *p++ = 0x82; *p++ = n >> 8; *p++ = n; } return p; } /* Create the final PKCS-12 object from the sequences contained in SEQLIST. PW is the password. That array is terminated with an NULL object. */ static unsigned char * create_final (struct buffer_s *sequences, const char *pw, size_t *r_length) { int i; size_t needed = 0; size_t len[8], n; unsigned char *macstart; size_t maclen; unsigned char *result, *p; size_t resultlen; char salt[8]; unsigned char keybuf[20]; gcry_md_hd_t md; int rc; int with_mac = 1; /* 9 steps to create the pkcs#12 Krampf. */ /* 8. The MAC. */ /* We add this at step 0. */ /* 7. All the buffers. */ for (i=0; sequences[i].buffer; i++) needed += sequences[i].length; /* 6. This goes into a sequences. */ len[6] = needed; n = compute_tag_length (needed); needed += n; /* 5. Encapsulate all in an octet string. */ len[5] = needed; n = compute_tag_length (needed); needed += n; /* 4. And tag it with [0]. */ len[4] = needed; n = compute_tag_length (needed); needed += n; /* 3. Prepend an data OID. */ needed += 2 + DIM (oid_data); /* 2. Put all into a sequences. */ len[2] = needed; n = compute_tag_length (needed); needed += n; /* 1. Prepend the version integer 3. */ needed += 3; /* 0. And the final outer sequence. */ if (with_mac) needed += DIM (data_mactemplate); len[0] = needed; n = compute_tag_length (needed); needed += n; /* Allocate a buffer. */ result = gcry_malloc (needed); if (!result) { log_error ("error allocating buffer\n"); return NULL; } p = result; /* 0. Store the very outer sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[0]); /* 1. Store the version integer 3. */ *p++ = TAG_INTEGER; *p++ = 1; *p++ = 3; /* 2. Store another sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[2]); /* 3. Store the data OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data)); memcpy (p, oid_data, DIM (oid_data)); p += DIM (oid_data); /* 4. Next comes a context tag. */ p = store_tag_length (p, 0xa0, len[4]); /* 5. And an octet string. */ p = store_tag_length (p, TAG_OCTET_STRING, len[5]); /* 6. And the inner sequence. */ macstart = p; p = store_tag_length (p, TAG_SEQUENCE, len[6]); /* 7. Append all the buffers. */ for (i=0; sequences[i].buffer; i++) { memcpy (p, sequences[i].buffer, sequences[i].length); p += sequences[i].length; } if (with_mac) { /* Intermezzo to compute the MAC. */ maclen = p - macstart; gcry_randomize (salt, 8, GCRY_STRONG_RANDOM); if (string_to_key (3, salt, 8, 2048, pw, 20, keybuf)) { gcry_free (result); return NULL; } rc = gcry_md_open (&md, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC); if (rc) { log_error ("gcry_md_open failed: %s\n", gpg_strerror (rc)); gcry_free (result); return NULL; } rc = gcry_md_setkey (md, keybuf, 20); if (rc) { log_error ("gcry_md_setkey failed: %s\n", gpg_strerror (rc)); gcry_md_close (md); gcry_free (result); return NULL; } gcry_md_write (md, macstart, maclen); /* 8. Append the MAC template and fix it up. */ memcpy (p, data_mactemplate, DIM (data_mactemplate)); memcpy (p + DATA_MACTEMPLATE_SALT_OFF, salt, 8); memcpy (p + DATA_MACTEMPLATE_MAC_OFF, gcry_md_read (md, 0), 20); p += DIM (data_mactemplate); gcry_md_close (md); } /* Ready. */ resultlen = p - result; if (needed != resultlen) log_debug ("length mismatch: %lu, %lu\n", (unsigned long)needed, (unsigned long)resultlen); *r_length = resultlen; return result; } /* Build a DER encoded SEQUENCE with the key: SEQUENCE { INTEGER 0 SEQUENCE { OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) NULL } OCTET STRING, encapsulates { SEQUENCE { INTEGER 0 INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER } } } MODE controls what is being generated: 0 - As described above 1 - Ditto but without the padding 2 - Only the inner part (pkcs#1) */ static unsigned char * build_key_sequence (gcry_mpi_t *kparms, int mode, size_t *r_length) { int rc, i; size_t needed, n; unsigned char *plain, *p; size_t plainlen; size_t outseqlen, oidseqlen, octstrlen, inseqlen; needed = 3; /* The version integer with value 0. */ for (i=0; kparms[i]; i++) { n = 0; rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]); if (rc) { log_error ("error formatting parameter: %s\n", gpg_strerror (rc)); return NULL; } needed += n; n = compute_tag_length (n); if (!n) return NULL; needed += n; } if (i != 8) { log_error ("invalid parameters for p12_build\n"); return NULL; } /* Now this all goes into a sequence. */ inseqlen = needed; n = compute_tag_length (needed); if (!n) return NULL; needed += n; if (mode != 2) { /* Encapsulate all into an octet string. */ octstrlen = needed; n = compute_tag_length (needed); if (!n) return NULL; needed += n; /* Prepend the object identifier sequence. */ oidseqlen = 2 + DIM (oid_rsaEncryption) + 2; needed += 2 + oidseqlen; /* The version number. */ needed += 3; /* And finally put the whole thing into a sequence. */ outseqlen = needed; n = compute_tag_length (needed); if (!n) return NULL; needed += n; } /* allocate 8 extra bytes for padding */ plain = gcry_malloc_secure (needed+8); if (!plain) { log_error ("error allocating encryption buffer\n"); return NULL; } /* And now fill the plaintext buffer. */ p = plain; if (mode != 2) { p = store_tag_length (p, TAG_SEQUENCE, outseqlen); /* Store version. */ *p++ = TAG_INTEGER; *p++ = 1; *p++ = 0; /* Store object identifier sequence. */ p = store_tag_length (p, TAG_SEQUENCE, oidseqlen); p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_rsaEncryption)); memcpy (p, oid_rsaEncryption, DIM (oid_rsaEncryption)); p += DIM (oid_rsaEncryption); *p++ = TAG_NULL; *p++ = 0; /* Start with the octet string. */ p = store_tag_length (p, TAG_OCTET_STRING, octstrlen); } p = store_tag_length (p, TAG_SEQUENCE, inseqlen); /* Store the key parameters. */ *p++ = TAG_INTEGER; *p++ = 1; *p++ = 0; for (i=0; kparms[i]; i++) { n = 0; rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]); if (rc) { log_error ("oops: error formatting parameter: %s\n", gpg_strerror (rc)); gcry_free (plain); return NULL; } p = store_tag_length (p, TAG_INTEGER, n); n = plain + needed - p; rc = gcry_mpi_print (GCRYMPI_FMT_STD, p, n, &n, kparms[i]); if (rc) { log_error ("oops: error storing parameter: %s\n", gpg_strerror (rc)); gcry_free (plain); return NULL; } p += n; } plainlen = p - plain; assert (needed == plainlen); if (!mode) { /* Append some pad characters; we already allocated extra space. */ n = 8 - plainlen % 8; for (i=0; i < n; i++, plainlen++) *p++ = n; } *r_length = plainlen; return plain; } static unsigned char * build_key_bag (unsigned char *buffer, size_t buflen, char *salt, const unsigned char *sha1hash, const char *keyidstr, size_t *r_length) { size_t len[11], needed; unsigned char *p, *keybag; size_t keybaglen; /* Walk 11 steps down to collect the info: */ /* 10. The data goes into an octet string. */ needed = compute_tag_length (buflen); needed += buflen; /* 9. Prepend the algorithm identifier. */ needed += DIM (data_3desiter2048); /* 8. Put a sequence around. */ len[8] = needed; needed += compute_tag_length (needed); /* 7. Prepend a [0] tag. */ len[7] = needed; needed += compute_tag_length (needed); /* 6b. The attributes which are appended at the end. */ if (sha1hash) needed += DIM (data_attrtemplate) + 20; /* 6. Prepend the shroudedKeyBag OID. */ needed += 2 + DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag); /* 5+4. Put all into two sequences. */ len[5] = needed; needed += compute_tag_length ( needed); len[4] = needed; needed += compute_tag_length (needed); /* 3. This all goes into an octet string. */ len[3] = needed; needed += compute_tag_length (needed); /* 2. Prepend another [0] tag. */ len[2] = needed; needed += compute_tag_length (needed); /* 1. Prepend the data OID. */ needed += 2 + DIM (oid_data); /* 0. Prepend another sequence. */ len[0] = needed; needed += compute_tag_length (needed); /* Now that we have all length information, allocate a buffer. */ p = keybag = gcry_malloc (needed); if (!keybag) { log_error ("error allocating buffer\n"); return NULL; } /* Walk 11 steps up to store the data. */ /* 0. Store the first sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[0]); /* 1. Store the data OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data)); memcpy (p, oid_data, DIM (oid_data)); p += DIM (oid_data); /* 2. Store a [0] tag. */ p = store_tag_length (p, 0xa0, len[2]); /* 3. And an octet string. */ p = store_tag_length (p, TAG_OCTET_STRING, len[3]); /* 4+5. Two sequences. */ p = store_tag_length (p, TAG_SEQUENCE, len[4]); p = store_tag_length (p, TAG_SEQUENCE, len[5]); /* 6. Store the shroudedKeyBag OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag)); memcpy (p, oid_pkcs_12_pkcs_8ShroudedKeyBag, DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag)); p += DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag); /* 7. Store a [0] tag. */ p = store_tag_length (p, 0xa0, len[7]); /* 8. Store a sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[8]); /* 9. Now for the pre-encoded algorithm identifier and the salt. */ memcpy (p, data_3desiter2048, DIM (data_3desiter2048)); memcpy (p + DATA_3DESITER2048_SALT_OFF, salt, 8); p += DIM (data_3desiter2048); /* 10. And the octet string with the encrypted data. */ p = store_tag_length (p, TAG_OCTET_STRING, buflen); memcpy (p, buffer, buflen); p += buflen; /* Append the attributes whose length we calculated at step 2b. */ if (sha1hash) { int i; memcpy (p, data_attrtemplate, DIM (data_attrtemplate)); for (i=0; i < 8; i++) p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i]; p += DIM (data_attrtemplate); memcpy (p, sha1hash, 20); p += 20; } keybaglen = p - keybag; if (needed != keybaglen) log_debug ("length mismatch: %lu, %lu\n", (unsigned long)needed, (unsigned long)keybaglen); *r_length = keybaglen; return keybag; } static unsigned char * build_cert_bag (unsigned char *buffer, size_t buflen, char *salt, size_t *r_length) { size_t len[9], needed; unsigned char *p, *certbag; size_t certbaglen; /* Walk 9 steps down to collect the info: */ /* 8. The data goes into an octet string. */ needed = compute_tag_length (buflen); needed += buflen; /* 7. The algorithm identifier. */ needed += DIM (data_rc2iter2048); /* 6. The data OID. */ needed += 2 + DIM (oid_data); /* 5. A sequence. */ len[5] = needed; needed += compute_tag_length ( needed); /* 4. An integer. */ needed += 3; /* 3. A sequence. */ len[3] = needed; needed += compute_tag_length (needed); /* 2. A [0] tag. */ len[2] = needed; needed += compute_tag_length (needed); /* 1. The encryptedData OID. */ needed += 2 + DIM (oid_encryptedData); /* 0. The first sequence. */ len[0] = needed; needed += compute_tag_length (needed); /* Now that we have all length information, allocate a buffer. */ p = certbag = gcry_malloc (needed); if (!certbag) { log_error ("error allocating buffer\n"); return NULL; } /* Walk 9 steps up to store the data. */ /* 0. Store the first sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[0]); /* 1. Store the encryptedData OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_encryptedData)); memcpy (p, oid_encryptedData, DIM (oid_encryptedData)); p += DIM (oid_encryptedData); /* 2. Store a [0] tag. */ p = store_tag_length (p, 0xa0, len[2]); /* 3. Store a sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[3]); /* 4. Store the integer 0. */ *p++ = TAG_INTEGER; *p++ = 1; *p++ = 0; /* 5. Store a sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[5]); /* 6. Store the data OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data)); memcpy (p, oid_data, DIM (oid_data)); p += DIM (oid_data); /* 7. Now for the pre-encoded algorithm identifier and the salt. */ memcpy (p, data_rc2iter2048, DIM (data_rc2iter2048)); memcpy (p + DATA_RC2ITER2048_SALT_OFF, salt, 8); p += DIM (data_rc2iter2048); /* 8. And finally the [0] tag with the encrypted data. */ p = store_tag_length (p, 0x80, buflen); memcpy (p, buffer, buflen); p += buflen; certbaglen = p - certbag; if (needed != certbaglen) log_debug ("length mismatch: %lu, %lu\n", (unsigned long)needed, (unsigned long)certbaglen); *r_length = certbaglen; return certbag; } static unsigned char * build_cert_sequence (const unsigned char *buffer, size_t buflen, const unsigned char *sha1hash, const char *keyidstr, size_t *r_length) { size_t len[8], needed, n; unsigned char *p, *certseq; size_t certseqlen; int i; assert (strlen (keyidstr) == 8); /* Walk 8 steps down to collect the info: */ /* 7. The data goes into an octet string. */ needed = compute_tag_length (buflen); needed += buflen; /* 6. A [0] tag. */ len[6] = needed; needed += compute_tag_length (needed); /* 5. An OID. */ needed += 2 + DIM (oid_x509Certificate_for_pkcs_12); /* 4. A sequence. */ len[4] = needed; needed += compute_tag_length (needed); /* 3. A [0] tag. */ len[3] = needed; needed += compute_tag_length (needed); /* 2b. The attributes which are appended at the end. */ if (sha1hash) needed += DIM (data_attrtemplate) + 20; /* 2. An OID. */ needed += 2 + DIM (oid_pkcs_12_CertBag); /* 1. A sequence. */ len[1] = needed; needed += compute_tag_length (needed); /* 0. The first sequence. */ len[0] = needed; needed += compute_tag_length (needed); /* Now that we have all length information, allocate a buffer. */ p = certseq = gcry_malloc (needed + 8 /*(for padding)*/); if (!certseq) { log_error ("error allocating buffer\n"); return NULL; } /* Walk 8 steps up to store the data. */ /* 0. Store the first sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[0]); /* 1. Store the second sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[1]); /* 2. Store the pkcs12-cert-bag OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_pkcs_12_CertBag)); memcpy (p, oid_pkcs_12_CertBag, DIM (oid_pkcs_12_CertBag)); p += DIM (oid_pkcs_12_CertBag); /* 3. Store a [0] tag. */ p = store_tag_length (p, 0xa0, len[3]); /* 4. Store a sequence. */ p = store_tag_length (p, TAG_SEQUENCE, len[4]); /* 5. Store the x509Certificate OID. */ p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_x509Certificate_for_pkcs_12)); memcpy (p, oid_x509Certificate_for_pkcs_12, DIM (oid_x509Certificate_for_pkcs_12)); p += DIM (oid_x509Certificate_for_pkcs_12); /* 6. Store a [0] tag. */ p = store_tag_length (p, 0xa0, len[6]); /* 7. And the octet string with the actual certificate. */ p = store_tag_length (p, TAG_OCTET_STRING, buflen); memcpy (p, buffer, buflen); p += buflen; /* Append the attributes whose length we calculated at step 2b. */ if (sha1hash) { memcpy (p, data_attrtemplate, DIM (data_attrtemplate)); for (i=0; i < 8; i++) p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i]; p += DIM (data_attrtemplate); memcpy (p, sha1hash, 20); p += 20; } certseqlen = p - certseq; if (needed != certseqlen) log_debug ("length mismatch: %lu, %lu\n", (unsigned long)needed, (unsigned long)certseqlen); /* Append some pad characters; we already allocated extra space. */ n = 8 - certseqlen % 8; for (i=0; i < n; i++, certseqlen++) *p++ = n; *r_length = certseqlen; return certseq; } /* Expect the RSA key parameters in KPARMS and a password in PW. Create a PKCS structure from it and return it as well as the length in R_LENGTH; return NULL in case of an error. If CHARSET is not NULL, re-encode PW to that character set. */ unsigned char * p12_build (gcry_mpi_t *kparms, const void *cert, size_t certlen, const char *pw, const char *charset, size_t *r_length) { unsigned char *buffer = NULL; size_t n, buflen; char salt[8]; struct buffer_s seqlist[3]; int seqlistidx = 0; unsigned char sha1hash[20]; char keyidstr[8+1]; char *pwbuf = NULL; size_t pwbufsize = 0; n = buflen = 0; /* (avoid compiler warning). */ memset (sha1hash, 0, 20); *keyidstr = 0; if (charset && pw && *pw) { jnlib_iconv_t cd; const char *inptr; char *outptr; size_t inbytes, outbytes; /* We assume that the converted passphrase is at max 2 times longer than its utf-8 encoding. */ pwbufsize = strlen (pw)*2 + 1; pwbuf = gcry_malloc_secure (pwbufsize); if (!pwbuf) { log_error ("out of secure memory while converting passphrase\n"); goto failure; } cd = jnlib_iconv_open (charset, "utf-8"); if (cd == (jnlib_iconv_t)(-1)) { log_error ("can't convert passphrase to" " requested charset '%s': %s\n", charset, strerror (errno)); goto failure; } inptr = pw; inbytes = strlen (pw); outptr = pwbuf; outbytes = pwbufsize - 1; if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes, &outptr, &outbytes) == (size_t)-1) { log_error ("error converting passphrase to" " requested charset '%s': %s\n", charset, strerror (errno)); jnlib_iconv_close (cd); goto failure; } *outptr = 0; jnlib_iconv_close (cd); pw = pwbuf; } if (cert && certlen) { /* Calculate the hash value we need for the bag attributes. */ gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash, cert, certlen); sprintf (keyidstr, "%02x%02x%02x%02x", sha1hash[16], sha1hash[17], sha1hash[18], sha1hash[19]); /* Encode the certificate. */ buffer = build_cert_sequence (cert, certlen, sha1hash, keyidstr, &buflen); if (!buffer) goto failure; /* Encrypt it. */ gcry_randomize (salt, 8, GCRY_STRONG_RANDOM); crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0, pw, GCRY_CIPHER_RFC2268_40, 1); /* Encode the encrypted stuff into a bag. */ seqlist[seqlistidx].buffer = build_cert_bag (buffer, buflen, salt, &n); seqlist[seqlistidx].length = n; gcry_free (buffer); buffer = NULL; if (!seqlist[seqlistidx].buffer) goto failure; seqlistidx++; } if (kparms) { /* Encode the key. */ buffer = build_key_sequence (kparms, 0, &buflen); if (!buffer) goto failure; /* Encrypt it. */ gcry_randomize (salt, 8, GCRY_STRONG_RANDOM); crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0, pw, GCRY_CIPHER_3DES, 1); /* Encode the encrypted stuff into a bag. */ if (cert && certlen) seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt, sha1hash, keyidstr, &n); else seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt, NULL, NULL, &n); seqlist[seqlistidx].length = n; gcry_free (buffer); buffer = NULL; if (!seqlist[seqlistidx].buffer) goto failure; seqlistidx++; } seqlist[seqlistidx].buffer = NULL; seqlist[seqlistidx].length = 0; buffer = create_final (seqlist, pw, &buflen); failure: if (pwbuf) { /* Note that wipememory is not really needed due to the use of gcry_malloc_secure. */ wipememory (pwbuf, pwbufsize); gcry_free (pwbuf); } for ( ; seqlistidx; seqlistidx--) gcry_free (seqlist[seqlistidx].buffer); *r_length = buffer? buflen : 0; return buffer; } /* This is actually not a pkcs#12 function but one which creates an unencrypted a pkcs#1 private key. */ unsigned char * p12_raw_build (gcry_mpi_t *kparms, int rawmode, size_t *r_length) { unsigned char *buffer; size_t buflen; assert (rawmode == 1 || rawmode == 2); buffer = build_key_sequence (kparms, rawmode, &buflen); if (!buffer) return NULL; *r_length = buflen; return buffer; } #ifdef TEST static void cert_cb (void *opaque, const unsigned char *cert, size_t certlen) { printf ("got a certificate of %u bytes length\n", certlen); } int main (int argc, char **argv) { FILE *fp; struct stat st; unsigned char *buf; size_t buflen; gcry_mpi_t *result; int badpass; if (argc != 3) { fprintf (stderr, "usage: testp12 file passphrase\n"); return 1; } gcry_control (GCRYCTL_DISABLE_SECMEM, NULL); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL); fp = gnupg_fopen (argv[1], "rb"); if (!fp) { fprintf (stderr, "can't open '%s': %s\n", argv[1], strerror (errno)); return 1; } if (fstat (fileno(fp), &st)) { fprintf (stderr, "can't stat '%s': %s\n", argv[1], strerror (errno)); return 1; } buflen = st.st_size; buf = gcry_malloc (buflen+1); if (!buf || fread (buf, buflen, 1, fp) != 1) { fprintf (stderr, "error reading '%s': %s\n", argv[1], strerror (errno)); return 1; } fclose (fp); result = p12_parse (buf, buflen, argv[2], cert_cb, NULL, &badpass); if (result) { int i, rc; unsigned char *tmpbuf; for (i=0; result[i]; i++) { rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, &tmpbuf, NULL, result[i]); if (rc) printf ("%d: [error printing number: %s]\n", i, gpg_strerror (rc)); else { printf ("%d: %s\n", i, tmpbuf); gcry_free (tmpbuf); } } } return 0; } /* Local Variables: compile-command: "gcc -Wall -O0 -g -DTEST=1 -o minip12 minip12.c ../common/libcommon.a -L /usr/local/lib -lgcrypt -lgpg-error" End: */ #endif /* TEST */ diff --git a/sm/minip12.h b/sm/minip12.h index 39a81939d..343b733a6 100644 --- a/sm/minip12.h +++ b/sm/minip12.h @@ -1,39 +1,41 @@ /* minip12.h - Global definitions for the minimal pkcs-12 implementation. * Copyright (C) 2002, 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 MINIP12_H #define MINIP12_H #include +void p12_set_verbosity (int verbose); + gcry_mpi_t *p12_parse (const unsigned char *buffer, size_t length, const char *pw, void (*certcb)(void*, const unsigned char*, size_t), void *certcbarg, int *r_badpass); unsigned char *p12_build (gcry_mpi_t *kparms, const void *cert, size_t certlen, const char *pw, const char *charset, size_t *r_length); unsigned char *p12_raw_build (gcry_mpi_t *kparms, int rawmode, size_t *r_length); #endif /*MINIP12_H*/