LCOV - code coverage report
Current view: top level - g10 - sign.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 495 736 67.3 %
Date: 2016-09-12 12:29:17 Functions: 15 17 88.2 %

          Line data    Source code
       1             : /* sign.c - sign data
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
       3             :  *               2007, 2010, 2012 Free Software Foundation, Inc.
       4             :  *
       5             :  * This file is part of GnuPG.
       6             :  *
       7             :  * GnuPG is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU General Public License as published by
       9             :  * the Free Software Foundation; either version 3 of the License, or
      10             :  * (at your option) any later version.
      11             :  *
      12             :  * GnuPG is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU General Public License
      18             :  * along with this program; if not, see <http://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : #include <stdio.h>
      23             : #include <stdlib.h>
      24             : #include <string.h>
      25             : #include <errno.h>
      26             : 
      27             : #include "gpg.h"
      28             : #include "options.h"
      29             : #include "packet.h"
      30             : #include "status.h"
      31             : #include "iobuf.h"
      32             : #include "keydb.h"
      33             : #include "util.h"
      34             : #include "main.h"
      35             : #include "filter.h"
      36             : #include "ttyio.h"
      37             : #include "trustdb.h"
      38             : #include "status.h"
      39             : #include "i18n.h"
      40             : #include "pkglue.h"
      41             : #include "sysutils.h"
      42             : #include "call-agent.h"
      43             : #include "mbox-util.h"
      44             : 
      45             : #ifdef HAVE_DOSISH_SYSTEM
      46             : #define LF "\r\n"
      47             : #else
      48             : #define LF "\n"
      49             : #endif
      50             : 
      51             : static int recipient_digest_algo=0;
      52             : 
      53             : /****************
      54             :  * Create notations and other stuff.  It is assumed that the stings in
      55             :  * STRLIST are already checked to contain only printable data and have
      56             :  * a valid NAME=VALUE format.
      57             :  */
      58             : static void
      59         136 : mk_notation_policy_etc (PKT_signature *sig,
      60             :                         PKT_public_key *pk, PKT_public_key *pksk)
      61             : {
      62             :   const char *string;
      63         136 :   char *p = NULL;
      64         136 :   strlist_t pu = NULL;
      65         136 :   struct notation *nd = NULL;
      66             :   struct expando_args args;
      67             : 
      68         136 :   log_assert (sig->version >= 4);
      69             : 
      70         136 :   memset (&args, 0, sizeof(args));
      71         136 :   args.pk = pk;
      72         136 :   args.pksk = pksk;
      73             : 
      74             :   /* Notation data. */
      75         136 :   if (IS_SIG(sig) && opt.sig_notations)
      76           0 :     nd = opt.sig_notations;
      77         136 :   else if (IS_CERT(sig) && opt.cert_notations)
      78           0 :     nd = opt.cert_notations;
      79             : 
      80         136 :   if (nd)
      81             :     {
      82             :       struct notation *item;
      83             : 
      84           0 :       for (item = nd; item; item = item->next)
      85             :         {
      86           0 :           item->altvalue = pct_expando (item->value,&args);
      87           0 :           if (!item->altvalue)
      88           0 :             log_error (_("WARNING: unable to %%-expand notation "
      89             :                          "(too large).  Using unexpanded.\n"));
      90             :         }
      91             : 
      92           0 :       keygen_add_notations (sig, nd);
      93             : 
      94           0 :       for (item = nd; item; item = item->next)
      95             :         {
      96           0 :           xfree (item->altvalue);
      97           0 :           item->altvalue = NULL;
      98             :         }
      99             :     }
     100             : 
     101             :   /* Set policy URL. */
     102         136 :   if (IS_SIG(sig) && opt.sig_policy_url)
     103           0 :     pu = opt.sig_policy_url;
     104         136 :   else if (IS_CERT(sig) && opt.cert_policy_url)
     105           0 :     pu = opt.cert_policy_url;
     106             : 
     107         136 :   for (; pu; pu = pu->next)
     108             :     {
     109           0 :       string = pu->d;
     110             : 
     111           0 :       p = pct_expando (string, &args);
     112           0 :       if (!p)
     113             :         {
     114           0 :           log_error(_("WARNING: unable to %%-expand policy URL "
     115             :                       "(too large).  Using unexpanded.\n"));
     116           0 :           p = xstrdup(string);
     117             :         }
     118             : 
     119           0 :       build_sig_subpkt (sig, (SIGSUBPKT_POLICY
     120           0 :                               | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
     121             :                         p, strlen (p));
     122             : 
     123           0 :       xfree (p);
     124             :     }
     125             : 
     126             :   /* Preferred keyserver URL. */
     127         136 :   if (IS_SIG(sig) && opt.sig_keyserver_url)
     128           0 :     pu = opt.sig_keyserver_url;
     129             : 
     130         136 :   for (; pu; pu = pu->next)
     131             :     {
     132           0 :       string = pu->d;
     133             : 
     134           0 :       p = pct_expando (string, &args);
     135           0 :       if (!p)
     136             :         {
     137           0 :           log_error (_("WARNING: unable to %%-expand preferred keyserver URL"
     138             :                        " (too large).  Using unexpanded.\n"));
     139           0 :           p = xstrdup (string);
     140             :         }
     141             : 
     142           0 :       build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS
     143           0 :                               | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)),
     144             :                         p, strlen (p));
     145           0 :       xfree (p);
     146             :     }
     147             : 
     148             :   /* Set signer's user id.  */
     149         136 :   if (IS_SIG (sig) && !opt.flags.disable_signer_uid)
     150             :     {
     151             :       char *mbox;
     152             : 
     153             :       /* For now we use the uid which was used to locate the key.  */
     154         131 :       if (pksk->user_id && (mbox = mailbox_from_userid (pksk->user_id->name)))
     155             :         {
     156          12 :           if (DBG_LOOKUP)
     157           0 :             log_debug ("setting Signer's UID to '%s'\n", mbox);
     158          12 :           build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox));
     159          12 :           xfree (mbox);
     160             :         }
     161         119 :       else if (opt.sender_list)
     162             :         {
     163             :           /* If a list of --sender was given we scan that list and use
     164             :            * the first one matching a user id of the current key.  */
     165             : 
     166             :           /* FIXME: We need to get the list of user ids for the PKSK
     167             :            * packet.  That requires either a function to look it up
     168             :            * again or we need to extend the key packet struct to link
     169             :            * to the primary key which in turn could link to the user
     170             :            * ids.  Too much of a change right now.  Let's take just
     171             :            * one from the supplied list and hope that the caller
     172             :            * passed a matching one.  */
     173           0 :           build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
     174           0 :                             opt.sender_list->d, strlen (opt.sender_list->d));
     175             :         }
     176             :     }
     177         136 : }
     178             : 
     179             : 
     180             : /*
     181             :  * Helper to hash a user ID packet.
     182             :  */
     183             : static void
     184           2 : hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
     185             : {
     186             :   byte buf[5];
     187             : 
     188             :   (void)sigversion;
     189             : 
     190           2 :   if (uid->attrib_data)
     191             :     {
     192           0 :       buf[0] = 0xd1;                   /* Indicates an attribute packet.  */
     193           0 :       buf[1] = uid->attrib_len >> 24;  /* Always use 4 length bytes.  */
     194           0 :       buf[2] = uid->attrib_len >> 16;
     195           0 :       buf[3] = uid->attrib_len >>  8;
     196           0 :       buf[4] = uid->attrib_len;
     197             :     }
     198             :   else
     199             :     {
     200           2 :       buf[0] = 0xb4;                   /* Indicates a userid packet.  */
     201           2 :       buf[1] = uid->len >> 24;         /* Always use 4 length bytes.  */
     202           2 :       buf[2] = uid->len >> 16;
     203           2 :       buf[3] = uid->len >>  8;
     204           2 :       buf[4] = uid->len;
     205             :     }
     206           2 :   gcry_md_write( md, buf, 5 );
     207             : 
     208           2 :   if (uid->attrib_data)
     209           0 :     gcry_md_write (md, uid->attrib_data, uid->attrib_len );
     210             :   else
     211           2 :     gcry_md_write (md, uid->name, uid->len );
     212           2 : }
     213             : 
     214             : 
     215             : /*
     216             :  * Helper to hash some parts from the signature
     217             :  */
     218             : static void
     219         136 : hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
     220             : {
     221             :   byte buf[6];
     222             :   size_t n;
     223             : 
     224         136 :   gcry_md_putc (md, sig->version);
     225         136 :   gcry_md_putc (md, sig->sig_class);
     226         136 :   gcry_md_putc (md, sig->pubkey_algo);
     227         136 :   gcry_md_putc (md, sig->digest_algo);
     228         136 :   if (sig->hashed)
     229             :     {
     230         136 :       n = sig->hashed->len;
     231         136 :       gcry_md_putc (md, (n >> 8) );
     232         136 :       gcry_md_putc (md,  n       );
     233         136 :       gcry_md_write (md, sig->hashed->data, n );
     234         136 :       n += 6;
     235             :     }
     236             :   else
     237             :     {
     238           0 :       gcry_md_putc (md, 0);  /* Always hash the length of the subpacket.  */
     239           0 :       gcry_md_putc (md, 0);
     240           0 :       n = 6;
     241             :     }
     242             :   /* Add some magic.  */
     243         136 :   buf[0] = sig->version;
     244         136 :   buf[1] = 0xff;
     245         136 :   buf[2] = n >> 24;         /* (n is only 16 bit, so this is always 0) */
     246         136 :   buf[3] = n >> 16;
     247         136 :   buf[4] = n >>  8;
     248         136 :   buf[5] = n;
     249         136 :   gcry_md_write (md, buf, 6);
     250         136 : }
     251             : 
     252             : 
     253             : /* Perform the sign operation.  If CACHE_NONCE is given the agent is
     254             :    advised to use that cached passphrase fro the key.  */
     255             : static int
     256         136 : do_sign (PKT_public_key *pksk, PKT_signature *sig,
     257             :          gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
     258             : {
     259             :   gpg_error_t err;
     260             :   byte *dp;
     261             :   char *hexgrip;
     262             : 
     263         136 :   if (pksk->timestamp > sig->timestamp )
     264             :     {
     265           0 :       ulong d = pksk->timestamp - sig->timestamp;
     266           0 :       log_info (ngettext("key %s was created %lu second"
     267             :                          " in the future (time warp or clock problem)\n",
     268             :                          "key %s was created %lu seconds"
     269             :                          " in the future (time warp or clock problem)\n",
     270             :                          d), keystr_from_pk (pksk), d);
     271           0 :       if (!opt.ignore_time_conflict)
     272           0 :         return gpg_error (GPG_ERR_TIME_CONFLICT);
     273             :     }
     274             : 
     275         136 :   print_pubkey_algo_note (pksk->pubkey_algo);
     276             : 
     277         136 :   if (!mdalgo)
     278           5 :     mdalgo = gcry_md_get_algo (md);
     279             : 
     280         136 :   print_digest_algo_note (mdalgo);
     281         136 :   dp = gcry_md_read  (md, mdalgo);
     282         136 :   sig->digest_algo = mdalgo;
     283         136 :   sig->digest_start[0] = dp[0];
     284         136 :   sig->digest_start[1] = dp[1];
     285         136 :   sig->data[0] = NULL;
     286         136 :   sig->data[1] = NULL;
     287             : 
     288             : 
     289         136 :   err = hexkeygrip_from_pk (pksk, &hexgrip);
     290         136 :   if (!err)
     291             :     {
     292             :       char *desc;
     293             :       gcry_sexp_t s_sigval;
     294             : 
     295         136 :       desc = gpg_format_keydesc (pksk, FORMAT_KEYDESC_NORMAL, 1);
     296         408 :       err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
     297         272 :                           pksk->keyid, pksk->main_keyid, pksk->pubkey_algo,
     298         136 :                           dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
     299             :                           &s_sigval);
     300         136 :       xfree (desc);
     301             : 
     302         136 :       if (err)
     303             :         ;
     304         136 :       else if (pksk->pubkey_algo == GCRY_PK_RSA
     305         118 :                || pksk->pubkey_algo == GCRY_PK_RSA_S)
     306          18 :         sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
     307         118 :       else if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
     308             :         {
     309           0 :           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE);
     310           0 :           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE);
     311             :         }
     312             :       else
     313             :         {
     314         118 :           sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG);
     315         118 :           sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG);
     316             :         }
     317             : 
     318         136 :       gcry_sexp_release (s_sigval);
     319             :     }
     320         136 :   xfree (hexgrip);
     321             : 
     322         136 :   if (err)
     323           0 :     log_error (_("signing failed: %s\n"), gpg_strerror (err));
     324             :   else
     325             :     {
     326         136 :       if (opt.verbose)
     327             :         {
     328           0 :           char *ustr = get_user_id_string_native (sig->keyid);
     329           0 :           log_info (_("%s/%s signature from: \"%s\"\n"),
     330           0 :                     openpgp_pk_algo_name (pksk->pubkey_algo),
     331           0 :                     openpgp_md_algo_name (sig->digest_algo),
     332             :                     ustr);
     333           0 :           xfree (ustr);
     334             :         }
     335             :     }
     336         136 :   return err;
     337             : }
     338             : 
     339             : 
     340             : int
     341           5 : complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
     342             :               const char *cache_nonce)
     343             : {
     344             :   int rc;
     345             : 
     346             :   /* if (!(rc = check_secret_key (pksk, 0))) */
     347           5 :   rc = do_sign (pksk, sig, md, 0, cache_nonce);
     348           5 :   return rc;
     349             : }
     350             : 
     351             : 
     352             : /* Return true if the key seems to be on a version 1 OpenPGP card.
     353             :    This works by asking the agent and may fail if the card has not yet
     354             :    been used with the agent.  */
     355             : static int
     356          56 : openpgp_card_v1_p (PKT_public_key *pk)
     357             : {
     358             :   gpg_error_t err;
     359             :   int result;
     360             : 
     361             :   /* Shortcut if we are not using RSA: The v1 cards only support RSA
     362             :      thus there is no point in looking any further.  */
     363          56 :   if (!is_RSA (pk->pubkey_algo))
     364           0 :     return 0;
     365             : 
     366          56 :   if (!pk->flags.serialno_valid)
     367             :     {
     368             :       char *hexgrip;
     369             : 
     370          14 :       err = hexkeygrip_from_pk (pk, &hexgrip);
     371          14 :       if (err)
     372             :         {
     373           0 :           log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
     374           0 :           return 0; /* Ooops.  */
     375             :         }
     376             : 
     377          14 :       xfree (pk->serialno);
     378          14 :       agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL);
     379          14 :       xfree (hexgrip);
     380          14 :       pk->flags.serialno_valid = 1;
     381             :     }
     382             : 
     383          56 :   if (!pk->serialno)
     384          56 :     result = 0; /* Error from a past agent_get_keyinfo or no card.  */
     385             :   else
     386             :     {
     387             :       /* The version number of the card is included in the serialno.  */
     388           0 :       result = !strncmp (pk->serialno, "D2760001240101", 14);
     389             :     }
     390          56 :   return result;
     391             : }
     392             : 
     393             : 
     394             : 
     395             : static int
     396         287 : match_dsa_hash (unsigned int qbytes)
     397             : {
     398         287 :   if (qbytes <= 20)
     399         203 :     return DIGEST_ALGO_SHA1;
     400             : 
     401          84 :   if (qbytes <= 28)
     402           0 :     return DIGEST_ALGO_SHA224;
     403             : 
     404          84 :   if (qbytes <= 32)
     405          28 :     return DIGEST_ALGO_SHA256;
     406             : 
     407          56 :   if (qbytes <= 48)
     408          28 :     return DIGEST_ALGO_SHA384;
     409             : 
     410          28 :   if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */
     411          28 :     return DIGEST_ALGO_SHA512;
     412             : 
     413           0 :   return DEFAULT_DIGEST_ALGO;
     414             :   /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
     415             :      answer we have if a digest larger than 512 bits is requested.  */
     416             : }
     417             : 
     418             : 
     419             : /*
     420             :   First try --digest-algo.  If that isn't set, see if the recipient
     421             :   has a preferred algorithm (which is also filtered through
     422             :   --personal-digest-prefs).  If we're making a signature without a
     423             :   particular recipient (i.e. signing, rather than signing+encrypting)
     424             :   then take the first algorithm in --personal-digest-prefs that is
     425             :   usable for the pubkey algorithm.  If --personal-digest-prefs isn't
     426             :   set, then take the OpenPGP default (i.e. SHA-1).
     427             : 
     428             :   Note that Ed25519+EdDSA takes an input of arbitrary length and thus
     429             :   we don't enforce any particular algorithm like we do for standard
     430             :   ECDSA. However, we use SHA256 as the default algorithm.
     431             : 
     432             :   Possible improvement: Use the highest-ranked usable algorithm from
     433             :   the signing key prefs either before or after using the personal
     434             :   list?
     435             : */
     436             : static int
     437         508 : hash_for (PKT_public_key *pk)
     438             : {
     439         508 :   if (opt.def_digest_algo)
     440             :     {
     441          64 :       return opt.def_digest_algo;
     442             :     }
     443         444 :   else if (recipient_digest_algo)
     444             :     {
     445         104 :       return recipient_digest_algo;
     446             :     }
     447         340 :   else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA
     448           0 :            && openpgp_oid_is_ed25519 (pk->pkey[0]))
     449             :     {
     450           0 :       if (opt.personal_digest_prefs)
     451           0 :         return opt.personal_digest_prefs[0].value;
     452             :       else
     453           0 :         return DIGEST_ALGO_SHA256;
     454             :     }
     455         340 :   else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
     456         140 :            || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
     457             :     {
     458         284 :       unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
     459             : 
     460         284 :       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
     461          84 :         qbytes = ecdsa_qbits_from_Q (qbytes);
     462         284 :       qbytes = qbytes/8;
     463             : 
     464             :       /* It's a DSA key, so find a hash that is the same size as q or
     465             :          larger.  If q is 160, assume it is an old DSA key and use a
     466             :          160-bit hash unless --enable-dsa2 is set, in which case act
     467             :          like a new DSA key that just happens to have a 160-bit q
     468             :          (i.e. allow truncation).  If q is not 160, by definition it
     469             :          must be a new DSA key. */
     470             : 
     471         284 :       if (opt.personal_digest_prefs)
     472             :         {
     473             :           prefitem_t *prefs;
     474             : 
     475           0 :           if (qbytes != 20 || opt.flags.dsa2)
     476             :             {
     477           0 :               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
     478           0 :                 if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
     479           0 :                   return prefs->value;
     480             :             }
     481             :           else
     482             :             {
     483           0 :               for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
     484           0 :                 if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
     485           0 :                   return prefs->value;
     486             :             }
     487             :         }
     488             : 
     489         284 :       return match_dsa_hash(qbytes);
     490             :     }
     491          56 :   else if (openpgp_card_v1_p (pk))
     492             :     {
     493             :       /* The sk lives on a smartcard, and old smartcards only handle
     494             :          SHA-1 and RIPEMD/160.  Newer smartcards (v2.0) don't have
     495             :          this restriction anymore.  Fortunately the serial number
     496             :          encodes the version of the card and thus we know that this
     497             :          key is on a v1 card. */
     498           0 :       if(opt.personal_digest_prefs)
     499             :         {
     500             :           prefitem_t *prefs;
     501             : 
     502           0 :           for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
     503           0 :             if (prefs->value==DIGEST_ALGO_SHA1
     504           0 :                 || prefs->value==DIGEST_ALGO_RMD160)
     505           0 :               return prefs->value;
     506             :         }
     507             : 
     508           0 :       return DIGEST_ALGO_SHA1;
     509             :     }
     510          56 :   else if (opt.personal_digest_prefs)
     511             :     {
     512             :       /* It's not DSA, so we can use whatever the first hash algorithm
     513             :          is in the pref list */
     514           0 :       return opt.personal_digest_prefs[0].value;
     515             :     }
     516             :   else
     517          56 :     return DEFAULT_DIGEST_ALGO;
     518             : }
     519             : 
     520             : 
     521             : static void
     522           0 : print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
     523             : {
     524             :   byte array[MAX_FINGERPRINT_LEN];
     525             :   char buf[100+MAX_FINGERPRINT_LEN*2];
     526             :   size_t n;
     527             : 
     528           0 :   snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
     529           0 :             what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
     530           0 :             (ulong)sig->timestamp );
     531           0 :   fingerprint_from_pk (pk, array, &n);
     532           0 :   bin2hex (array, n, buf + strlen (buf));
     533             : 
     534           0 :   write_status_text( STATUS_SIG_CREATED, buf );
     535           0 : }
     536             : 
     537             : 
     538             : /*
     539             :  * Loop over the secret certificates in SK_LIST and build the one pass
     540             :  * signature packets.  OpenPGP says that the data should be bracket by
     541             :  * the onepass-sig and signature-packet; so we build these onepass
     542             :  * packet here in reverse order
     543             :  */
     544             : static int
     545         105 : write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
     546             : {
     547             :     int skcount;
     548             :     SK_LIST sk_rover;
     549             : 
     550         210 :     for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
     551         105 :         skcount++;
     552             : 
     553         210 :     for (; skcount; skcount--) {
     554             :         PKT_public_key *pk;
     555             :         PKT_onepass_sig *ops;
     556             :         PACKET pkt;
     557             :         int i, rc;
     558             : 
     559         105 :         for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
     560         105 :             if (++i == skcount)
     561         105 :                 break;
     562             :         }
     563             : 
     564         105 :         pk = sk_rover->pk;
     565         105 :         ops = xmalloc_clear (sizeof *ops);
     566         105 :         ops->sig_class = sigclass;
     567         105 :         ops->digest_algo = hash_for (pk);
     568         105 :         ops->pubkey_algo = pk->pubkey_algo;
     569         105 :         keyid_from_pk (pk, ops->keyid);
     570         105 :         ops->last = (skcount == 1);
     571             : 
     572         105 :         init_packet(&pkt);
     573         105 :         pkt.pkttype = PKT_ONEPASS_SIG;
     574         105 :         pkt.pkt.onepass_sig = ops;
     575         105 :         rc = build_packet (out, &pkt);
     576         105 :         free_packet (&pkt);
     577         105 :         if (rc) {
     578           0 :             log_error ("build onepass_sig packet failed: %s\n",
     579             :                        gpg_strerror (rc));
     580           0 :             return rc;
     581             :         }
     582             :     }
     583             : 
     584         105 :     return 0;
     585             : }
     586             : 
     587             : /*
     588             :  * Helper to write the plaintext (literal data) packet
     589             :  */
     590             : static int
     591         105 : write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
     592             : {
     593         105 :     PKT_plaintext *pt = NULL;
     594             :     u32 filesize;
     595         105 :     int rc = 0;
     596             : 
     597         105 :     if (!opt.no_literal)
     598         105 :       pt=setup_plaintext_name(fname,inp);
     599             : 
     600             :     /* try to calculate the length of the data */
     601         105 :     if ( !iobuf_is_pipe_filename (fname) && *fname )
     602          89 :       {
     603             :         off_t tmpsize;
     604             :         int overflow;
     605             : 
     606          89 :         if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
     607           0 :             && !overflow && opt.verbose)
     608           0 :           log_info (_("WARNING: '%s' is an empty file\n"), fname);
     609             : 
     610             :         /* We can't encode the length of very large files because
     611             :            OpenPGP uses only 32 bit for file sizes.  So if the size of
     612             :            a file is larger than 2^32 minus some bytes for packet
     613             :            headers, we switch to partial length encoding. */
     614          89 :         if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
     615          89 :           filesize = tmpsize;
     616             :         else
     617           0 :           filesize = 0;
     618             : 
     619             :         /* Because the text_filter modifies the length of the
     620             :          * data, it is not possible to know the used length
     621             :          * without a double read of the file - to avoid that
     622             :          * we simple use partial length packets. */
     623          89 :         if ( ptmode == 't' || ptmode == 'u' || ptmode == 'm')
     624           3 :           filesize = 0;
     625             :       }
     626             :     else
     627          16 :       filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
     628             : 
     629         105 :     if (!opt.no_literal) {
     630             :         PACKET pkt;
     631             : 
     632             :         /* Note that PT has been initialized above in no_literal mode.  */
     633         105 :         pt->timestamp = make_timestamp ();
     634         105 :         pt->mode = ptmode;
     635         105 :         pt->len = filesize;
     636         105 :         pt->new_ctb = !pt->len;
     637         105 :         pt->buf = inp;
     638         105 :         init_packet(&pkt);
     639         105 :         pkt.pkttype = PKT_PLAINTEXT;
     640         105 :         pkt.pkt.plaintext = pt;
     641             :         /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
     642         105 :         if( (rc = build_packet (out, &pkt)) )
     643           0 :             log_error ("build_packet(PLAINTEXT) failed: %s\n",
     644             :                        gpg_strerror (rc) );
     645         105 :         pt->buf = NULL;
     646         105 :         free_packet (&pkt);
     647             :     }
     648             :     else {
     649             :         byte copy_buffer[4096];
     650             :         int  bytes_copied;
     651             : 
     652           0 :         while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
     653           0 :             if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
     654           0 :                 log_error ("copying input to output failed: %s\n",
     655             :                            gpg_strerror (rc));
     656           0 :                 break;
     657             :             }
     658           0 :         wipememory(copy_buffer,4096); /* burn buffer */
     659             :     }
     660             :     /* fixme: it seems that we never freed pt/pkt */
     661             : 
     662         105 :     return rc;
     663             : }
     664             : 
     665             : /*
     666             :  * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
     667             :  * hash which will not be changes here.
     668             :  */
     669             : static int
     670         131 : write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
     671             :                          int sigclass, u32 timestamp, u32 duration,
     672             :                          int status_letter, const char *cache_nonce)
     673             : {
     674             :   SK_LIST sk_rover;
     675             : 
     676             :   /* Loop over the certificates with secret keys. */
     677         262 :   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
     678             :     {
     679             :       PKT_public_key *pk;
     680             :       PKT_signature *sig;
     681             :       gcry_md_hd_t md;
     682             :       int rc;
     683             : 
     684         131 :       pk = sk_rover->pk;
     685             : 
     686             :       /* Build the signature packet.  */
     687         131 :       sig = xmalloc_clear (sizeof *sig);
     688         131 :       if (duration || opt.sig_policy_url
     689         131 :           || opt.sig_notations || opt.sig_keyserver_url)
     690           0 :         sig->version = 4;
     691             :       else
     692         131 :         sig->version = pk->version;
     693             : 
     694         131 :       keyid_from_pk (pk, sig->keyid);
     695         131 :       sig->digest_algo = hash_for (pk);
     696         131 :       sig->pubkey_algo = pk->pubkey_algo;
     697         131 :       if (timestamp)
     698           0 :         sig->timestamp = timestamp;
     699             :       else
     700         131 :         sig->timestamp = make_timestamp();
     701         131 :       if (duration)
     702           0 :         sig->expiredate = sig->timestamp + duration;
     703         131 :       sig->sig_class = sigclass;
     704             : 
     705         131 :       if (gcry_md_copy (&md, hash))
     706           0 :         BUG ();
     707             : 
     708         131 :       if (sig->version >= 4)
     709             :         {
     710         131 :           build_sig_subpkt_from_sig (sig, pk);
     711         131 :           mk_notation_policy_etc (sig, NULL, pk);
     712             :         }
     713             : 
     714         131 :       hash_sigversion_to_magic (md, sig);
     715         131 :       gcry_md_final (md);
     716             : 
     717         131 :       rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
     718         131 :       gcry_md_close (md);
     719         131 :       if (!rc)
     720             :         {
     721             :           /* Write the packet.  */
     722             :           PACKET pkt;
     723             : 
     724         131 :           init_packet (&pkt);
     725         131 :           pkt.pkttype = PKT_SIGNATURE;
     726         131 :           pkt.pkt.signature = sig;
     727         131 :           rc = build_packet (out, &pkt);
     728         131 :           if (!rc && is_status_enabled())
     729           0 :             print_status_sig_created (pk, sig, status_letter);
     730         131 :           free_packet (&pkt);
     731         131 :           if (rc)
     732           0 :             log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
     733             :         }
     734         131 :       if (rc)
     735           0 :         return rc;
     736             :     }
     737             : 
     738         131 :   return 0;
     739             : }
     740             : 
     741             : 
     742             : /****************
     743             :  * Sign the files whose names are in FILENAME.
     744             :  * If DETACHED has the value true,
     745             :  * make a detached signature.  If FILENAMES->d is NULL read from stdin
     746             :  * and ignore the detached mode.  Sign the file with all secret keys
     747             :  * which can be taken from LOCUSR, if this is NULL, use the default one
     748             :  * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
     749             :  * signed data for these users.
     750             :  * If OUTFILE is not NULL; this file is used for output and the function
     751             :  * does not ask for overwrite permission; output is then always
     752             :  * uncompressed, non-armored and in binary mode.
     753             :  */
     754             : int
     755         114 : sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
     756             :            int encryptflag, strlist_t remusr, const char *outfile )
     757             : {
     758             :     const char *fname;
     759             :     armor_filter_context_t *afx;
     760             :     compress_filter_context_t zfx;
     761             :     md_filter_context_t mfx;
     762             :     text_filter_context_t tfx;
     763             :     progress_filter_context_t *pfx;
     764             :     encrypt_filter_context_t efx;
     765         114 :     IOBUF inp = NULL, out = NULL;
     766             :     PACKET pkt;
     767         114 :     int rc = 0;
     768         114 :     PK_LIST pk_list = NULL;
     769         114 :     SK_LIST sk_list = NULL;
     770         114 :     SK_LIST sk_rover = NULL;
     771         114 :     int multifile = 0;
     772         114 :     u32 duration=0;
     773             : 
     774         114 :     pfx = new_progress_context ();
     775         114 :     afx = new_armor_context ();
     776         114 :     memset( &zfx, 0, sizeof zfx);
     777         114 :     memset( &mfx, 0, sizeof mfx);
     778         114 :     memset( &efx, 0, sizeof efx);
     779         114 :     init_packet( &pkt );
     780             : 
     781         114 :     if( filenames ) {
     782         111 :         fname = filenames->d;
     783         111 :         multifile = !!filenames->next;
     784             :     }
     785             :     else
     786           3 :         fname = NULL;
     787             : 
     788         114 :     if( fname && filenames->next && (!detached || encryptflag) )
     789           0 :         log_bug("multiple files can only be detached signed");
     790             : 
     791         114 :     if(encryptflag==2
     792           1 :        && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
     793           0 :       goto leave;
     794             : 
     795         114 :     if (opt.ask_sig_expire && !opt.batch)
     796           0 :       duration = ask_expire_interval(1,opt.def_sig_expire);
     797             :     else
     798         114 :       duration = parse_expire_string(opt.def_sig_expire);
     799             : 
     800             :     /* Note: In the old non-agent version the following call used to
     801             :        unprotect the secret key.  This is now done on demand by the agent.  */
     802         114 :     if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
     803           0 :         goto leave;
     804             : 
     805         114 :     if (encryptflag
     806          28 :         && (rc=build_pk_list (ctrl, remusr, &pk_list)))
     807           0 :       goto leave;
     808             : 
     809             :     /* prepare iobufs */
     810         114 :     if( multifile )  /* have list of filenames */
     811           2 :         inp = NULL; /* we do it later */
     812             :     else {
     813         112 :       inp = iobuf_open(fname);
     814         112 :       if (inp && is_secured_file (iobuf_get_fd (inp)))
     815             :         {
     816           0 :           iobuf_close (inp);
     817           0 :           inp = NULL;
     818           0 :           gpg_err_set_errno (EPERM);
     819             :         }
     820         112 :       if( !inp )
     821             :         {
     822           0 :           rc = gpg_error_from_syserror ();
     823           0 :           log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]",
     824           0 :                      strerror(errno) );
     825           0 :           goto leave;
     826             :         }
     827             : 
     828         112 :         handle_progress (pfx, inp, fname);
     829             :     }
     830             : 
     831         114 :     if( outfile ) {
     832           0 :         if (is_secured_filename ( outfile )) {
     833           0 :             out = NULL;
     834           0 :             gpg_err_set_errno (EPERM);
     835             :         }
     836             :         else
     837           0 :           out = iobuf_create (outfile, 0);
     838           0 :         if( !out )
     839             :           {
     840           0 :             rc = gpg_error_from_syserror ();
     841           0 :             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
     842           0 :             goto leave;
     843             :           }
     844           0 :         else if( opt.verbose )
     845           0 :             log_info(_("writing to '%s'\n"), outfile );
     846             :     }
     847         203 :     else if( (rc = open_outfile (-1, fname,
     848         203 :                                  opt.armor? 1: detached? 2:0, 0, &out)))
     849           0 :         goto leave;
     850             : 
     851             :     /* prepare to calculate the MD over the input */
     852         114 :     if( opt.textmode && !outfile && !multifile )
     853             :       {
     854           3 :         memset( &tfx, 0, sizeof tfx);
     855           3 :         iobuf_push_filter( inp, text_filter, &tfx );
     856             :       }
     857             : 
     858         114 :     if ( gcry_md_open (&mfx.md, 0, 0) )
     859           0 :       BUG ();
     860         114 :     if (DBG_HASHING)
     861           0 :       gcry_md_debug (mfx.md, "sign");
     862             : 
     863             :     /* If we're encrypting and signing, it is reasonable to pick the
     864             :        hash algorithm to use out of the recipient key prefs.  This is
     865             :        best effort only, as in a DSA2 and smartcard world there are
     866             :        cases where we cannot please everyone with a single hash (DSA2
     867             :        wants >160 and smartcards want =160).  In the future this could
     868             :        be more complex with different hashes for each sk, but the
     869             :        current design requires a single hash for all SKs. */
     870         114 :     if(pk_list)
     871             :       {
     872          28 :         if(opt.def_digest_algo)
     873             :           {
     874           4 :             if(!opt.expert &&
     875           2 :                select_algo_from_prefs(pk_list,PREFTYPE_HASH,
     876             :                                       opt.def_digest_algo,
     877           2 :                                       NULL)!=opt.def_digest_algo)
     878           1 :           log_info(_("WARNING: forcing digest algorithm %s (%d)"
     879             :                      " violates recipient preferences\n"),
     880             :                    gcry_md_algo_name (opt.def_digest_algo),
     881             :                    opt.def_digest_algo );
     882             :           }
     883             :         else
     884             :           {
     885          26 :             int algo, smartcard=0;
     886             :             union pref_hint hint;
     887             : 
     888          26 :             hint.digest_length = 0;
     889             : 
     890             :             /* Of course, if the recipient asks for something
     891             :                unreasonable (like the wrong hash for a DSA key) then
     892             :                don't do it.  Check all sk's - if any are DSA or live
     893             :                on a smartcard, then the hash has restrictions and we
     894             :                may not be able to give the recipient what they want.
     895             :                For DSA, pass a hint for the largest q we have.  Note
     896             :                that this means that a q>160 key will override a q=160
     897             :                key and force the use of truncation for the q=160 key.
     898             :                The alternative would be to ignore the recipient prefs
     899             :                completely and get a different hash for each DSA key in
     900             :                hash_for().  The override behavior here is more or less
     901             :                reasonable as it is under the control of the user which
     902             :                keys they sign with for a given message and the fact
     903             :                that the message with multiple signatures won't be
     904             :                usable on an implementation that doesn't understand
     905             :                DSA2 anyway. */
     906             : 
     907          52 :             for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
     908             :               {
     909          26 :                 if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA
     910           2 :                     || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
     911             :                   {
     912          24 :                     int temp_hashlen = (gcry_mpi_get_nbits
     913          24 :                                         (sk_rover->pk->pkey[1]));
     914             : 
     915          24 :                     if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
     916           0 :                       temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen);
     917          24 :                     temp_hashlen = (temp_hashlen+7)/8;
     918             : 
     919             :                     /* Pick a hash that is large enough for our
     920             :                        largest q */
     921             : 
     922          24 :                     if (hint.digest_length<temp_hashlen)
     923          24 :                       hint.digest_length=temp_hashlen;
     924             :                   }
     925             :                 /* FIXME: need to check gpg-agent for this. */
     926             :                 /* else if (sk_rover->pk->is_protected */
     927             :                 /*          && sk_rover->pk->protect.s2k.mode == 1002) */
     928             :                 /*   smartcard = 1;  */
     929             :               }
     930             : 
     931             :             /* Current smartcards only do 160-bit hashes.  If we have
     932             :                to have a >160-bit hash, then we can't use the
     933             :                recipient prefs as we'd need both =160 and >160 at the
     934             :                same time and recipient prefs currently require a
     935             :                single hash for all signatures.  All this may well have
     936             :                to change as the cards add algorithms. */
     937             : 
     938          26 :             if (!smartcard || (smartcard && hint.digest_length==20))
     939          26 :               if ( (algo=
     940          26 :                    select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
     941          26 :                 recipient_digest_algo=algo;
     942             :           }
     943             :       }
     944             : 
     945         228 :     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
     946         114 :       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
     947             : 
     948         114 :     if( !multifile )
     949         112 :         iobuf_push_filter( inp, md_filter, &mfx );
     950             : 
     951         114 :     if( detached && !encryptflag)
     952          16 :         afx->what = 2;
     953             : 
     954         114 :     if( opt.armor && !outfile  )
     955          25 :         push_armor_filter (afx, out);
     956             : 
     957         114 :     if( encryptflag ) {
     958          28 :         efx.pk_list = pk_list;
     959             :         /* fixme: set efx.cfx.datalen if known */
     960          28 :         iobuf_push_filter( out, encrypt_filter, &efx );
     961             :     }
     962             : 
     963         114 :     if (opt.compress_algo && !outfile && !detached)
     964             :       {
     965          98 :         int compr_algo=opt.compress_algo;
     966             : 
     967             :         /* If not forced by user */
     968          98 :         if(compr_algo==-1)
     969             :           {
     970             :             /* If we're not encrypting, then select_algo_from_prefs
     971             :                will fail and we'll end up with the default.  If we are
     972             :                encrypting, select_algo_from_prefs cannot fail since
     973             :                there is an assumed preference for uncompressed data.
     974             :                Still, if it did fail, we'll also end up with the
     975             :                default. */
     976             : 
     977          98 :             if((compr_algo=
     978          98 :                 select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
     979          70 :               compr_algo=default_compress_algo();
     980             :           }
     981           0 :         else if(!opt.expert && pk_list
     982           0 :                 && select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
     983             :                                           compr_algo,NULL)!=compr_algo)
     984           0 :           log_info(_("WARNING: forcing compression algorithm %s (%d)"
     985             :                      " violates recipient preferences\n"),
     986             :                    compress_algo_to_string(compr_algo),compr_algo);
     987             : 
     988             :         /* algo 0 means no compression */
     989          98 :         if( compr_algo )
     990          98 :           push_compress_filter(out,&zfx,compr_algo);
     991             :       }
     992             : 
     993             :     /* Write the one-pass signature packets if needed */
     994         114 :     if (!detached) {
     995          98 :         rc = write_onepass_sig_packets (sk_list, out,
     996          98 :                                         opt.textmode && !outfile ? 0x01:0x00);
     997          98 :         if (rc)
     998           0 :             goto leave;
     999             :     }
    1000             : 
    1001         114 :     write_status_begin_signing (mfx.md);
    1002             : 
    1003             :     /* Setup the inner packet. */
    1004         114 :     if( detached ) {
    1005          16 :         if( multifile ) {
    1006             :             strlist_t sl;
    1007             : 
    1008           2 :             if( opt.verbose )
    1009           0 :                 log_info(_("signing:") );
    1010             :             /* must walk reverse trough this list */
    1011          18 :             for( sl = strlist_last(filenames); sl;
    1012          14 :                         sl = strlist_prev( filenames, sl ) ) {
    1013          14 :                 inp = iobuf_open(sl->d);
    1014          14 :                 if (inp && is_secured_file (iobuf_get_fd (inp)))
    1015             :                   {
    1016           0 :                     iobuf_close (inp);
    1017           0 :                     inp = NULL;
    1018           0 :                     gpg_err_set_errno (EPERM);
    1019             :                   }
    1020          14 :                 if( !inp )
    1021             :                   {
    1022           0 :                     rc = gpg_error_from_syserror ();
    1023           0 :                     log_error(_("can't open '%s': %s\n"),
    1024           0 :                               sl->d,strerror(errno));
    1025           0 :                     goto leave;
    1026             :                   }
    1027          14 :                 handle_progress (pfx, inp, sl->d);
    1028          14 :                 if( opt.verbose )
    1029           0 :                   log_printf (" '%s'", sl->d );
    1030          14 :                 if(opt.textmode)
    1031             :                   {
    1032           0 :                     memset( &tfx, 0, sizeof tfx);
    1033           0 :                     iobuf_push_filter( inp, text_filter, &tfx );
    1034             :                   }
    1035          14 :                 iobuf_push_filter( inp, md_filter, &mfx );
    1036          14 :                 while( iobuf_get(inp) != -1 )
    1037             :                     ;
    1038          14 :                 iobuf_close(inp); inp = NULL;
    1039             :             }
    1040           2 :             if( opt.verbose )
    1041           0 :               log_printf ("\n");
    1042             :         }
    1043             :         else {
    1044             :             /* read, so that the filter can calculate the digest */
    1045          14 :             while( iobuf_get(inp) != -1 )
    1046             :                 ;
    1047             :         }
    1048             :     }
    1049             :     else {
    1050         101 :         rc = write_plaintext_packet (out, inp, fname,
    1051         101 :                                      opt.textmode && !outfile ?
    1052           3 :                                      (opt.mimemode? 'm':'t'):'b');
    1053             :     }
    1054             : 
    1055             :     /* catch errors from above */
    1056         114 :     if (rc)
    1057           0 :         goto leave;
    1058             : 
    1059             :     /* write the signatures */
    1060         228 :     rc = write_signature_packets (sk_list, out, mfx.md,
    1061         114 :                                   opt.textmode && !outfile? 0x01 : 0x00,
    1062             :                                   0, duration, detached ? 'D':'S', NULL);
    1063         114 :     if( rc )
    1064           0 :         goto leave;
    1065             : 
    1066             : 
    1067             :   leave:
    1068         114 :     if( rc )
    1069           0 :         iobuf_cancel(out);
    1070             :     else {
    1071         114 :         iobuf_close(out);
    1072         114 :         if (encryptflag)
    1073          28 :             write_status( STATUS_END_ENCRYPTION );
    1074             :     }
    1075         114 :     iobuf_close(inp);
    1076         114 :     gcry_md_close ( mfx.md );
    1077         114 :     release_sk_list( sk_list );
    1078         114 :     release_pk_list( pk_list );
    1079         114 :     recipient_digest_algo=0;
    1080         114 :     release_progress_context (pfx);
    1081         114 :     release_armor_context (afx);
    1082         114 :     return rc;
    1083             : }
    1084             : 
    1085             : 
    1086             : 
    1087             : /****************
    1088             :  * make a clear signature. note that opt.armor is not needed
    1089             :  */
    1090             : int
    1091          10 : clearsign_file (ctrl_t ctrl,
    1092             :                 const char *fname, strlist_t locusr, const char *outfile )
    1093             : {
    1094             :     armor_filter_context_t *afx;
    1095             :     progress_filter_context_t *pfx;
    1096          10 :     gcry_md_hd_t textmd = NULL;
    1097          10 :     IOBUF inp = NULL, out = NULL;
    1098             :     PACKET pkt;
    1099          10 :     int rc = 0;
    1100          10 :     SK_LIST sk_list = NULL;
    1101          10 :     SK_LIST sk_rover = NULL;
    1102          10 :     u32 duration=0;
    1103             : 
    1104          10 :     pfx = new_progress_context ();
    1105          10 :     afx = new_armor_context ();
    1106          10 :     init_packet( &pkt );
    1107             : 
    1108          10 :     if (opt.ask_sig_expire && !opt.batch)
    1109           0 :       duration = ask_expire_interval (1,opt.def_sig_expire);
    1110             :     else
    1111          10 :       duration = parse_expire_string (opt.def_sig_expire);
    1112             : 
    1113             :     /* Note: In the old non-agent version the following call used to
    1114             :        unprotect the secret key.  This is now done on demand by the agent.  */
    1115          10 :     if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) )
    1116           0 :         goto leave;
    1117             : 
    1118             :     /* prepare iobufs */
    1119          10 :     inp = iobuf_open(fname);
    1120          10 :     if (inp && is_secured_file (iobuf_get_fd (inp)))
    1121             :       {
    1122           0 :         iobuf_close (inp);
    1123           0 :         inp = NULL;
    1124           0 :         gpg_err_set_errno (EPERM);
    1125             :       }
    1126          10 :     if( !inp ) {
    1127           0 :         rc = gpg_error_from_syserror ();
    1128           0 :         log_error (_("can't open '%s': %s\n"),
    1129           0 :                    fname? fname: "[stdin]", strerror(errno) );
    1130           0 :         goto leave;
    1131             :     }
    1132          10 :     handle_progress (pfx, inp, fname);
    1133             : 
    1134          10 :     if( outfile ) {
    1135           0 :         if (is_secured_filename (outfile) ) {
    1136           0 :             outfile = NULL;
    1137           0 :             gpg_err_set_errno (EPERM);
    1138             :         }
    1139             :         else
    1140           0 :           out = iobuf_create (outfile, 0);
    1141           0 :         if( !out )
    1142             :           {
    1143           0 :             rc = gpg_error_from_syserror ();
    1144           0 :             log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) );
    1145           0 :             goto leave;
    1146             :           }
    1147           0 :         else if( opt.verbose )
    1148           0 :             log_info(_("writing to '%s'\n"), outfile );
    1149             :     }
    1150          10 :     else if ((rc = open_outfile (-1, fname, 1, 0, &out)))
    1151           0 :         goto leave;
    1152             : 
    1153          10 :     iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
    1154             : 
    1155             :     {
    1156             :         const char *s;
    1157          10 :         int any = 0;
    1158             :         byte hashs_seen[256];
    1159             : 
    1160          10 :         memset( hashs_seen, 0, sizeof hashs_seen );
    1161          10 :         iobuf_writestr(out, "Hash: " );
    1162          20 :         for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
    1163          10 :             int i = hash_for (sk_rover->pk);
    1164             : 
    1165          10 :             if( !hashs_seen[ i & 0xff ] ) {
    1166          10 :                 s = gcry_md_algo_name ( i );
    1167          10 :                 if( s ) {
    1168          10 :                     hashs_seen[ i & 0xff ] = 1;
    1169          10 :                     if( any )
    1170           0 :                         iobuf_put(out, ',' );
    1171          10 :                     iobuf_writestr(out, s );
    1172          10 :                     any = 1;
    1173             :                 }
    1174             :             }
    1175             :         }
    1176          10 :         log_assert(any);
    1177          10 :         iobuf_writestr(out, LF );
    1178             :     }
    1179             : 
    1180          10 :     if( opt.not_dash_escaped )
    1181           1 :       iobuf_writestr( out,
    1182             :                       "NotDashEscaped: You need "GPG_NAME
    1183             :                       " to verify this message" LF );
    1184          10 :     iobuf_writestr(out, LF );
    1185             : 
    1186          10 :     if ( gcry_md_open (&textmd, 0, 0) )
    1187           0 :       BUG ();
    1188          20 :     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
    1189          10 :       gcry_md_enable (textmd, hash_for(sk_rover->pk));
    1190             : 
    1191          10 :     if ( DBG_HASHING )
    1192           0 :       gcry_md_debug ( textmd, "clearsign" );
    1193             : 
    1194          10 :     copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped,
    1195             :                         opt.escape_from);
    1196             :     /* fixme: check for read errors */
    1197             : 
    1198             :     /* now write the armor */
    1199          10 :     afx->what = 2;
    1200          10 :     push_armor_filter (afx, out);
    1201             : 
    1202             :     /* Write the signatures.  */
    1203          10 :     rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
    1204             :                                   NULL);
    1205          10 :     if( rc )
    1206           0 :         goto leave;
    1207             : 
    1208             :   leave:
    1209          10 :     if( rc )
    1210           0 :         iobuf_cancel(out);
    1211             :     else
    1212          10 :         iobuf_close(out);
    1213          10 :     iobuf_close(inp);
    1214          10 :     gcry_md_close ( textmd );
    1215          10 :     release_sk_list( sk_list );
    1216          10 :     release_progress_context (pfx);
    1217          10 :     release_armor_context (afx);
    1218          10 :     return rc;
    1219             : }
    1220             : 
    1221             : /*
    1222             :  * Sign and conventionally encrypt the given file.
    1223             :  * FIXME: Far too much code is duplicated - revamp the whole file.
    1224             :  */
    1225             : int
    1226           7 : sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr)
    1227             : {
    1228             :     armor_filter_context_t *afx;
    1229             :     progress_filter_context_t *pfx;
    1230             :     compress_filter_context_t zfx;
    1231             :     md_filter_context_t mfx;
    1232             :     text_filter_context_t tfx;
    1233             :     cipher_filter_context_t cfx;
    1234           7 :     IOBUF inp = NULL, out = NULL;
    1235             :     PACKET pkt;
    1236           7 :     STRING2KEY *s2k = NULL;
    1237           7 :     int rc = 0;
    1238           7 :     SK_LIST sk_list = NULL;
    1239           7 :     SK_LIST sk_rover = NULL;
    1240             :     int algo;
    1241           7 :     u32 duration=0;
    1242             :     int canceled;
    1243             : 
    1244           7 :     pfx = new_progress_context ();
    1245           7 :     afx = new_armor_context ();
    1246           7 :     memset( &zfx, 0, sizeof zfx);
    1247           7 :     memset( &mfx, 0, sizeof mfx);
    1248           7 :     memset( &tfx, 0, sizeof tfx);
    1249           7 :     memset( &cfx, 0, sizeof cfx);
    1250           7 :     init_packet( &pkt );
    1251             : 
    1252           7 :     if (opt.ask_sig_expire && !opt.batch)
    1253           0 :       duration = ask_expire_interval (1, opt.def_sig_expire);
    1254             :     else
    1255           7 :       duration = parse_expire_string (opt.def_sig_expire);
    1256             : 
    1257             :     /* Note: In the old non-agent version the following call used to
    1258             :        unprotect the secret key.  This is now done on demand by the agent.  */
    1259           7 :     rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG);
    1260           7 :     if (rc)
    1261           0 :         goto leave;
    1262             : 
    1263             :     /* prepare iobufs */
    1264           7 :     inp = iobuf_open(fname);
    1265           7 :     if (inp && is_secured_file (iobuf_get_fd (inp)))
    1266             :       {
    1267           0 :         iobuf_close (inp);
    1268           0 :         inp = NULL;
    1269           0 :         gpg_err_set_errno (EPERM);
    1270             :       }
    1271           7 :     if( !inp ) {
    1272           0 :         rc = gpg_error_from_syserror ();
    1273           0 :         log_error (_("can't open '%s': %s\n"),
    1274           0 :                    fname? fname: "[stdin]", strerror(errno) );
    1275           0 :         goto leave;
    1276             :     }
    1277           7 :     handle_progress (pfx, inp, fname);
    1278             : 
    1279             :     /* prepare key */
    1280           7 :     s2k = xmalloc_clear( sizeof *s2k );
    1281           7 :     s2k->mode = opt.s2k_mode;
    1282           7 :     s2k->hash_algo = S2K_DIGEST_ALGO;
    1283             : 
    1284           7 :     algo = default_cipher_algo();
    1285           7 :     if (!opt.quiet || !opt.batch)
    1286           7 :         log_info (_("%s encryption will be used\n"),
    1287             :                   openpgp_cipher_algo_name (algo) );
    1288           7 :     cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, &canceled);
    1289             : 
    1290           7 :     if (!cfx.dek || !cfx.dek->keylen) {
    1291           0 :         rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
    1292           0 :         log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
    1293           0 :         goto leave;
    1294             :     }
    1295             : 
    1296           7 :     cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo);
    1297             : 
    1298             :     /* now create the outfile */
    1299           7 :     rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out);
    1300           7 :     if (rc)
    1301           0 :         goto leave;
    1302             : 
    1303             :     /* prepare to calculate the MD over the input */
    1304           7 :     if (opt.textmode)
    1305           0 :         iobuf_push_filter (inp, text_filter, &tfx);
    1306           7 :     if ( gcry_md_open (&mfx.md, 0, 0) )
    1307           0 :       BUG ();
    1308           7 :     if ( DBG_HASHING )
    1309           0 :       gcry_md_debug (mfx.md, "symc-sign");
    1310             : 
    1311          14 :     for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
    1312           7 :       gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
    1313             : 
    1314           7 :     iobuf_push_filter (inp, md_filter, &mfx);
    1315             : 
    1316             :     /* Push armor output filter */
    1317           7 :     if (opt.armor)
    1318           0 :         push_armor_filter (afx, out);
    1319             : 
    1320             :     /* Write the symmetric key packet */
    1321             :     /*(current filters: armor)*/
    1322             :     {
    1323           7 :         PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
    1324           7 :         enc->version = 4;
    1325           7 :         enc->cipher_algo = cfx.dek->algo;
    1326           7 :         enc->s2k = *s2k;
    1327           7 :         pkt.pkttype = PKT_SYMKEY_ENC;
    1328           7 :         pkt.pkt.symkey_enc = enc;
    1329           7 :         if( (rc = build_packet( out, &pkt )) )
    1330           0 :             log_error("build symkey packet failed: %s\n", gpg_strerror (rc) );
    1331           7 :         xfree(enc);
    1332             :     }
    1333             : 
    1334             :     /* Push the encryption filter */
    1335           7 :     iobuf_push_filter( out, cipher_filter, &cfx );
    1336             : 
    1337             :     /* Push the compress filter */
    1338           7 :     if (default_compress_algo())
    1339             :       {
    1340           7 :         if (cfx.dek && cfx.dek->use_mdc)
    1341           7 :           zfx.new_ctb = 1;
    1342           7 :         push_compress_filter (out, &zfx,default_compress_algo() );
    1343             :       }
    1344             : 
    1345             :     /* Write the one-pass signature packets */
    1346             :     /*(current filters: zip - encrypt - armor)*/
    1347           7 :     rc = write_onepass_sig_packets (sk_list, out,
    1348           7 :                                     opt.textmode? 0x01:0x00);
    1349           7 :     if (rc)
    1350           0 :       goto leave;
    1351             : 
    1352           7 :     write_status_begin_signing (mfx.md);
    1353             : 
    1354             :     /* Pipe data through all filters; i.e. write the signed stuff */
    1355             :     /*(current filters: zip - encrypt - armor)*/
    1356           7 :     rc = write_plaintext_packet (out, inp, fname,
    1357           7 :                                  opt.textmode ? (opt.mimemode?'m':'t'):'b');
    1358           7 :     if (rc)
    1359           0 :         goto leave;
    1360             : 
    1361             :     /* Write the signatures */
    1362             :     /*(current filters: zip - encrypt - armor)*/
    1363           7 :     rc = write_signature_packets (sk_list, out, mfx.md,
    1364           7 :                                   opt.textmode? 0x01 : 0x00,
    1365             :                                   0, duration, 'S', NULL);
    1366           7 :     if( rc )
    1367           0 :         goto leave;
    1368             : 
    1369             : 
    1370             :   leave:
    1371           7 :     if( rc )
    1372           0 :         iobuf_cancel(out);
    1373             :     else {
    1374           7 :         iobuf_close(out);
    1375           7 :         write_status( STATUS_END_ENCRYPTION );
    1376             :     }
    1377           7 :     iobuf_close(inp);
    1378           7 :     release_sk_list( sk_list );
    1379           7 :     gcry_md_close( mfx.md );
    1380           7 :     xfree(cfx.dek);
    1381           7 :     xfree(s2k);
    1382           7 :     release_progress_context (pfx);
    1383           7 :     release_armor_context (afx);
    1384           7 :     return rc;
    1385             : }
    1386             : 
    1387             : 
    1388             : /****************
    1389             :  * Create a signature packet for the given public key certificate and
    1390             :  * the user id and return it in ret_sig. User signature class SIGCLASS
    1391             :  * user-id is not used (and may be NULL if sigclass is 0x20) If
    1392             :  * DIGEST_ALGO is 0 the function selects an appropriate one.
    1393             :  * SIGVERSION gives the minimal required signature packet version;
    1394             :  * this is needed so that special properties like local sign are not
    1395             :  * applied (actually: dropped) when a v3 key is used.  TIMESTAMP is
    1396             :  * the timestamp to use for the signature. 0 means "now" */
    1397             : int
    1398           5 : make_keysig_packet (PKT_signature **ret_sig, PKT_public_key *pk,
    1399             :                     PKT_user_id *uid, PKT_public_key *subpk,
    1400             :                     PKT_public_key *pksk,
    1401             :                     int sigclass, int digest_algo,
    1402             :                     u32 timestamp, u32 duration,
    1403             :                     int (*mksubpkt)(PKT_signature *, void *), void *opaque,
    1404             :                     const char *cache_nonce)
    1405             : {
    1406             :     PKT_signature *sig;
    1407           5 :     int rc=0;
    1408             :     int sigversion;
    1409             :     gcry_md_hd_t md;
    1410             : 
    1411           5 :     log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
    1412             :                 || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
    1413             :                 || sigclass == 0x30 || sigclass == 0x28 );
    1414             : 
    1415           5 :     sigversion = 4;
    1416           5 :     if (sigversion < pksk->version)
    1417           0 :         sigversion = pksk->version;
    1418             : 
    1419           5 :     if( !digest_algo )
    1420             :       {
    1421             :         /* Basically, this means use SHA1 always unless the user
    1422             :            specified something (use whatever they said), or it's DSA
    1423             :            (use the best match).  They still can't pick an
    1424             :            inappropriate hash for DSA or the signature will fail.
    1425             :            Note that this still allows the caller of
    1426             :            make_keysig_packet to override the user setting if it
    1427             :            must. */
    1428             : 
    1429           5 :         if(opt.cert_digest_algo)
    1430           0 :           digest_algo=opt.cert_digest_algo;
    1431           5 :         else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA)
    1432           3 :           digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
    1433           2 :         else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA
    1434           2 :                  || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA)
    1435             :           {
    1436           0 :             if (openpgp_oid_is_ed25519 (pksk->pkey[0]))
    1437           0 :               digest_algo = DIGEST_ALGO_SHA256;
    1438             :             else
    1439           0 :               digest_algo = match_dsa_hash
    1440           0 :                 (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8);
    1441             :           }
    1442             :         else
    1443           2 :           digest_algo = DEFAULT_DIGEST_ALGO;
    1444             :       }
    1445             : 
    1446           5 :     if ( gcry_md_open (&md, digest_algo, 0 ) )
    1447           0 :       BUG ();
    1448             : 
    1449             :     /* Hash the public key certificate. */
    1450           5 :     hash_public_key( md, pk );
    1451             : 
    1452           5 :     if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
    1453             :       {
    1454             :         /* hash the subkey binding/backsig/revocation */
    1455           1 :         hash_public_key( md, subpk );
    1456             :       }
    1457           4 :     else if( sigclass != 0x1F && sigclass != 0x20 )
    1458             :       {
    1459             :         /* hash the user id */
    1460           2 :         hash_uid (md, sigversion, uid);
    1461             :       }
    1462             :     /* and make the signature packet */
    1463           5 :     sig = xmalloc_clear( sizeof *sig );
    1464           5 :     sig->version = sigversion;
    1465           5 :     sig->flags.exportable=1;
    1466           5 :     sig->flags.revocable=1;
    1467           5 :     keyid_from_pk (pksk, sig->keyid);
    1468           5 :     sig->pubkey_algo = pksk->pubkey_algo;
    1469           5 :     sig->digest_algo = digest_algo;
    1470           5 :     if(timestamp)
    1471           3 :       sig->timestamp=timestamp;
    1472             :     else
    1473           2 :       sig->timestamp=make_timestamp();
    1474           5 :     if(duration)
    1475           0 :       sig->expiredate=sig->timestamp+duration;
    1476           5 :     sig->sig_class = sigclass;
    1477             : 
    1478           5 :     build_sig_subpkt_from_sig (sig, pksk);
    1479           5 :     mk_notation_policy_etc (sig, pk, pksk);
    1480             : 
    1481             :     /* Crucial that the call to mksubpkt comes LAST before the calls
    1482             :        to finalize the sig as that makes it possible for the mksubpkt
    1483             :        function to get a reliable pointer to the subpacket area. */
    1484           5 :     if (mksubpkt)
    1485           5 :         rc = (*mksubpkt)( sig, opaque );
    1486             : 
    1487           5 :     if( !rc ) {
    1488           5 :         hash_sigversion_to_magic (md, sig);
    1489           5 :         gcry_md_final (md);
    1490             : 
    1491           5 :         rc = complete_sig (sig, pksk, md, cache_nonce);
    1492             :     }
    1493             : 
    1494           5 :     gcry_md_close (md);
    1495           5 :     if( rc )
    1496           0 :         free_seckey_enc( sig );
    1497             :     else
    1498           5 :         *ret_sig = sig;
    1499           5 :     return rc;
    1500             : }
    1501             : 
    1502             : 
    1503             : 
    1504             : /****************
    1505             :  * Create a new signature packet based on an existing one.
    1506             :  * Only user ID signatures are supported for now.
    1507             :  * PK is the public key to work on.
    1508             :  * PKSK is the key used to make the signature.
    1509             :  *
    1510             :  * TODO: Merge this with make_keysig_packet.
    1511             :  */
    1512             : gpg_error_t
    1513           0 : update_keysig_packet( PKT_signature **ret_sig,
    1514             :                       PKT_signature *orig_sig,
    1515             :                       PKT_public_key *pk,
    1516             :                       PKT_user_id *uid,
    1517             :                       PKT_public_key *subpk,
    1518             :                       PKT_public_key *pksk,
    1519             :                       int (*mksubpkt)(PKT_signature *, void *),
    1520             :                       void *opaque)
    1521             : {
    1522             :     PKT_signature *sig;
    1523           0 :     gpg_error_t rc = 0;
    1524             :     int digest_algo;
    1525             :     gcry_md_hd_t md;
    1526             : 
    1527           0 :     if ((!orig_sig || !pk || !pksk)
    1528           0 :         || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
    1529           0 :         || (orig_sig->sig_class == 0x18 && !subpk))
    1530           0 :       return GPG_ERR_GENERAL;
    1531             : 
    1532           0 :     if ( opt.cert_digest_algo )
    1533           0 :       digest_algo = opt.cert_digest_algo;
    1534             :     else
    1535           0 :       digest_algo = orig_sig->digest_algo;
    1536             : 
    1537           0 :     if ( gcry_md_open (&md, digest_algo, 0 ) )
    1538           0 :       BUG ();
    1539             : 
    1540             :     /* Hash the public key certificate and the user id. */
    1541           0 :     hash_public_key( md, pk );
    1542             : 
    1543           0 :     if( orig_sig->sig_class == 0x18 )
    1544           0 :       hash_public_key( md, subpk );
    1545             :     else
    1546           0 :       hash_uid (md, orig_sig->version, uid);
    1547             : 
    1548             :     /* create a new signature packet */
    1549           0 :     sig = copy_signature (NULL, orig_sig);
    1550             : 
    1551           0 :     sig->digest_algo=digest_algo;
    1552             : 
    1553             :     /* We need to create a new timestamp so that new sig expiration
    1554             :        calculations are done correctly... */
    1555           0 :     sig->timestamp=make_timestamp();
    1556             : 
    1557             :     /* ... but we won't make a timestamp earlier than the existing
    1558             :        one. */
    1559             :     {
    1560           0 :       int tmout = 0;
    1561           0 :       while(sig->timestamp<=orig_sig->timestamp)
    1562             :         {
    1563           0 :           if (++tmout > 5 && !opt.ignore_time_conflict)
    1564             :             {
    1565           0 :               rc = gpg_error (GPG_ERR_TIME_CONFLICT);
    1566           0 :               goto leave;
    1567             :             }
    1568           0 :           gnupg_sleep (1);
    1569           0 :           sig->timestamp=make_timestamp();
    1570             :         }
    1571             :     }
    1572             : 
    1573             :     /* Note that already expired sigs will remain expired (with a
    1574             :        duration of 1) since build-packet.c:build_sig_subpkt_from_sig
    1575             :        detects this case. */
    1576             : 
    1577             :     /* Put the updated timestamp into the sig.  Note that this will
    1578             :        automagically lower any sig expiration dates to correctly
    1579             :        correspond to the differences in the timestamps (i.e. the
    1580             :        duration will shrink).  */
    1581           0 :     build_sig_subpkt_from_sig (sig, pksk);
    1582             : 
    1583           0 :     if (mksubpkt)
    1584           0 :       rc = (*mksubpkt)(sig, opaque);
    1585             : 
    1586           0 :     if (!rc) {
    1587           0 :         hash_sigversion_to_magic (md, sig);
    1588           0 :         gcry_md_final (md);
    1589             : 
    1590           0 :         rc = complete_sig (sig, pksk, md, NULL);
    1591             :     }
    1592             : 
    1593             :  leave:
    1594           0 :     gcry_md_close (md);
    1595           0 :     if( rc )
    1596           0 :         free_seckey_enc (sig);
    1597             :     else
    1598           0 :         *ret_sig = sig;
    1599           0 :     return rc;
    1600             : }

Generated by: LCOV version 1.11