LCOV - code coverage report
Current view: top level - g10 - sign.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 467 724 64.5 %
Date: 2015-11-05 17:10:59 Functions: 14 17 82.4 %

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

Generated by: LCOV version 1.11