Exemplo n.º 1
0
static int
xxxx_do_check( PKT_secret_key *sk, const char *tryagain_text, int mode,
               int *canceled )
{
    gpg_error_t err;
    byte *buffer;
    u16 csum=0;
    int i, res;
    size_t nbytes;

    if( sk->is_protected ) { /* remove the protection */
	DEK *dek = NULL;
	u32 keyid[4]; /* 4! because we need two of them */
	gcry_cipher_hd_t cipher_hd=NULL;
	PKT_secret_key *save_sk;

	if( sk->protect.s2k.mode == 1001 ) {
	    log_info(_("secret key parts are not available\n"));
	    return GPG_ERR_UNUSABLE_SECKEY;
	}
	if( sk->protect.algo == CIPHER_ALGO_NONE )
	    BUG();
	if( openpgp_cipher_test_algo( sk->protect.algo ) ) {
	    log_info(_("protection algorithm %d%s is not supported\n"),
			sk->protect.algo,sk->protect.algo==1?" (IDEA)":"" );
	    return GPG_ERR_CIPHER_ALGO;
	}
	if(gcry_md_test_algo (sk->protect.s2k.hash_algo))
	  {
	    log_info(_("protection digest %d is not supported\n"),
		     sk->protect.s2k.hash_algo);
	    return GPG_ERR_DIGEST_ALGO;
	  }
	keyid_from_sk( sk, keyid );
	keyid[2] = keyid[3] = 0;
	if (!sk->flags.primary)
          {
            keyid[2] = sk->main_keyid[0];
            keyid[3] = sk->main_keyid[1];
          }
	dek = passphrase_to_dek( keyid, sk->pubkey_algo, sk->protect.algo,
				 &sk->protect.s2k, mode,
                                 tryagain_text, canceled );
        if (!dek && canceled && *canceled)
	    return GPG_ERR_CANCELED;


	err = openpgp_cipher_open (&cipher_hd, sk->protect.algo,
				   GCRY_CIPHER_MODE_CFB,
				   (GCRY_CIPHER_SECURE
				    | (sk->protect.algo >= 100 ?
				       0 : GCRY_CIPHER_ENABLE_SYNC)));
        if (err)
          log_fatal ("cipher open failed: %s\n", gpg_strerror (err) );

	err = gcry_cipher_setkey (cipher_hd, dek->key, dek->keylen);
        if (err)
          log_fatal ("set key failed: %s\n", gpg_strerror (err) );

	xfree(dek);
	save_sk = copy_secret_key( NULL, sk );

	gcry_cipher_setiv ( cipher_hd, sk->protect.iv, sk->protect.ivlen );

	csum = 0;
	if( sk->version >= 4 ) {
            int ndata;
	    unsigned int ndatabits;
	    byte *p, *data;
            u16 csumc = 0;

	    i = pubkey_get_npkey(sk->pubkey_algo);

            assert ( gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE ));
            p = gcry_mpi_get_opaque ( sk->skey[i], &ndatabits );
            ndata = (ndatabits+7)/8;

            if ( ndata > 1 )
              csumc = buf16_to_u16 (p+ndata-2);
	    data = xmalloc_secure ( ndata );
	    gcry_cipher_decrypt ( cipher_hd, data, ndata, p, ndata );
	    gcry_mpi_release (sk->skey[i]); sk->skey[i] = NULL ;

	    p = data;
            if (sk->protect.sha1chk) {
                /* This is the new SHA1 checksum method to detect
                   tampering with the key as used by the Klima/Rosa
                   attack */
                sk->csum = 0;
                csum = 1;
                if( ndata < 20 )
                    log_error("not enough bytes for SHA-1 checksum\n");
                else {
                    gcry_md_hd_t h;

                    if ( gcry_md_open (&h, DIGEST_ALGO_SHA1, 1))
                        BUG(); /* Algo not available. */
                    gcry_md_write (h, data, ndata - 20);
                    gcry_md_final (h);
                    if (!memcmp (gcry_md_read (h, DIGEST_ALGO_SHA1),
                                 data + ndata - 20, 20) )
                      {
                        /* Digest does match.  We have to keep the old
                           style checksum in sk->csum, so that the
                           test used for unprotected keys does work.
                           This test gets used when we are adding new
                           keys. */
                        sk->csum = csum = checksum (data, ndata-20);
                      }
                    gcry_md_close (h);
                }
            }
            else {
                if( ndata < 2 ) {
                    log_error("not enough bytes for checksum\n");
                    sk->csum = 0;
                    csum = 1;
                }
                else {
                    csum = checksum( data, ndata-2);
                    sk->csum = data[ndata-2] << 8 | data[ndata-1];
                    if ( sk->csum != csum ) {
                        /* This is a PGP 7.0.0 workaround */
                        sk->csum = csumc; /* take the encrypted one */
                    }
                }
            }

            /* Must check it here otherwise the mpi_read_xx would fail
               because the length may have an arbitrary value */
            if( sk->csum == csum ) {
                for( ; i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
                    if ( gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_PGP,
                                        p, ndata, &nbytes))
                      {
                        /* Checksum was okay, but not correctly
                           decrypted.  */
                        sk->csum = 0;
                        csum = 1;
                        break;
                      }
                    ndata -= nbytes;
                    p += nbytes;
                }
                /* Note: at this point ndata should be 2 for a simple
                   checksum or 20 for the sha1 digest */
            }
	    xfree(data);
	}
	else {
	    for(i=pubkey_get_npkey(sk->pubkey_algo);
		    i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
                byte *p;
                size_t ndata;
                unsigned int ndatabits;

                assert (gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE));
                p = gcry_mpi_get_opaque (sk->skey[i], &ndatabits);
                ndata = (ndatabits+7)/8;
                assert (ndata >= 2);
                assert (ndata == ((p[0] << 8 | p[1]) + 7)/8 + 2);
                buffer = xmalloc_secure (ndata);
		gcry_cipher_sync (cipher_hd);
                buffer[0] = p[0];
                buffer[1] = p[1];
                gcry_cipher_decrypt (cipher_hd, buffer+2, ndata-2,
                                     p+2, ndata-2);
                csum += checksum (buffer, ndata);
                gcry_mpi_release (sk->skey[i]);

		err = gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_PGP,
				     buffer, ndata, &ndata );
		xfree (buffer);
                if (err)
                  {
                    /* Checksum was okay, but not correctly
                       decrypted.  */
                    sk->csum = 0;
                    csum = 1;
                    break;
                  }
/*  		csum += checksum_mpi (sk->skey[i]); */
	    }
	}
	gcry_cipher_close ( cipher_hd );

	/* Now let's see whether we have used the correct passphrase. */
	if( csum != sk->csum ) {
	    copy_secret_key( sk, save_sk );
            passphrase_clear_cache ( keyid, NULL, sk->pubkey_algo );
	    free_secret_key( save_sk );
	    return gpg_error (GPG_ERR_BAD_PASSPHRASE);
	}

	/* The checksum may fail, so we also check the key itself. */
	res = pk_check_secret_key ( sk->pubkey_algo, sk->skey );
	if( res ) {
	    copy_secret_key( sk, save_sk );
            passphrase_clear_cache ( keyid, NULL, sk->pubkey_algo );
	    free_secret_key( save_sk );
	    return gpg_error (GPG_ERR_BAD_PASSPHRASE);
	}
	free_secret_key( save_sk );
	sk->is_protected = 0;
    }
    else { /* not protected, assume it is okay if the checksum is okay */
	csum = 0;
	for(i=pubkey_get_npkey(sk->pubkey_algo);
		i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
	    csum += checksum_mpi( sk->skey[i] );
	}
	if( csum != sk->csum )
	    return GPG_ERR_CHECKSUM;
    }

    return 0;
}
Exemplo n.º 2
0
/* If keyblock_out is non-NULL, AND the exit code is zero, then it
   contains a pointer to the first keyblock found and exported.  No
   other keyblocks are exported.  The caller must free it. */
static int
do_export_stream( IOBUF out, strlist_t users, int secret,
		  KBNODE *keyblock_out, unsigned int options, int *any )
{
    int rc = 0;
    PACKET pkt;
    KBNODE keyblock = NULL;
    KBNODE kbctx, node;
    size_t ndesc, descindex;
    KEYDB_SEARCH_DESC *desc = NULL;
    subkey_list_t subkey_list = NULL;  /* Track alreay processed subkeys. */
    KEYDB_HANDLE kdbhd;
    strlist_t sl;
    int indent = 0;

    *any = 0;
    init_packet( &pkt );
    kdbhd = keydb_new (secret);

    if (!users) {
        ndesc = 1;
        desc = xcalloc ( ndesc, sizeof *desc );
        desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
    }
    else {
        for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
            ;
        desc = xmalloc ( ndesc * sizeof *desc);
        
        for (ndesc=0, sl=users; sl; sl = sl->next) {
	    if (classify_user_id (sl->d, desc+ndesc))
                ndesc++;
            else
                log_error (_("key \"%s\" not found: %s\n"),
                           sl->d, g10_errstr (G10ERR_INV_USER_ID));
        }

        /* It would be nice to see which of the given users did
           actually match one in the keyring.  To implement this we
           need to have a found flag for each entry in desc and to set
           this we must check all those entries after a match to mark
           all matched one - currently we stop at the first match.  To
           do this we need an extra flag to enable this feature so */
    }

#ifdef ENABLE_SELINUX_HACKS
    if (secret) {
        log_error (_("exporting secret keys not allowed\n"));
        rc = G10ERR_GENERAL;
        goto leave;
    }
#endif

    while (!(rc = keydb_search2 (kdbhd, desc, ndesc, &descindex))) {
        int sha1_warned=0,skip_until_subkey=0;
	u32 sk_keyid[2];

	if (!users) 
            desc[0].mode = KEYDB_SEARCH_MODE_NEXT;

        /* Read the keyblock. */
        rc = keydb_get_keyblock (kdbhd, &keyblock );
	if( rc ) {
            log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
	    goto leave;
	}

	if((node=find_kbnode(keyblock,PKT_SECRET_KEY)))
	  {
	    PKT_secret_key *sk=node->pkt->pkt.secret_key;

	    keyid_from_sk(sk,sk_keyid);

	    /* We can't apply GNU mode 1001 on an unprotected key. */
	    if( secret == 2 && !sk->is_protected )
	      {
		log_info(_("key %s: not protected - skipped\n"),
			 keystr(sk_keyid));
		continue;
	      }

	    /* No v3 keys with GNU mode 1001. */
	    if( secret == 2 && sk->version == 3 )
	      {
		log_info(_("key %s: PGP 2.x style key - skipped\n"),
			 keystr(sk_keyid));
		continue;
	      }

            /* It does not make sense to export a key with a primary
               key on card using a non-key stub.  We simply skip those
               keys when used with --export-secret-subkeys. */
            if (secret == 2 && sk->is_protected
                && sk->protect.s2k.mode == 1002 ) 
              {
		log_info(_("key %s: key material on-card - skipped\n"),
			 keystr(sk_keyid));
		continue;
              }
	  }
	else
	  {
	    /* It's a public key export, so do the cleaning if
	       requested.  Note that both export-clean and
	       export-minimal only apply to UID sigs (0x10, 0x11,
	       0x12, and 0x13).  A designated revocation is never
	       stripped, even with export-minimal set. */

	    if(options&EXPORT_CLEAN)
	      clean_key(keyblock,opt.verbose,options&EXPORT_MINIMAL,NULL,NULL);
	  }

	/* And write it. */
	for( kbctx=NULL; (node = walk_kbnode( keyblock, &kbctx, 0 )); ) {
	    if( skip_until_subkey )
	      {
		if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY
		   || node->pkt->pkttype==PKT_SECRET_SUBKEY)
		  skip_until_subkey=0;
		else
		  continue;
	      }

	    /* We used to use comment packets, but not any longer.  In
	       case we still have comments on a key, strip them here
	       before we call build_packet(). */
	    if( node->pkt->pkttype == PKT_COMMENT )
	      continue;

            /* Make sure that ring_trust packets never get exported. */
            if (node->pkt->pkttype == PKT_RING_TRUST)
              continue;

	    /* If exact is set, then we only export what was requested
	       (plus the primary key, if the user didn't specifically
	       request it). */
	    if(desc[descindex].exact
	       && (node->pkt->pkttype==PKT_PUBLIC_SUBKEY
		   || node->pkt->pkttype==PKT_SECRET_SUBKEY))
	      {
                if (!exact_subkey_match_p (desc+descindex, node))
                  {
                    /* Before skipping this subkey, check whether any
                       other description wants an exact match on a
                       subkey and include that subkey into the output
                       too.  Need to add this subkey to a list so that
                       it won't get processed a second time.
                   
                       So the first step here is to check that list and
                       skip in any case if the key is in that list.

                       We need this whole mess because the import
                       function is not able to merge secret keys and
                       thus it is useless to output them as two
                       separate keys and have import merge them.  */
                    if (subkey_in_list_p (subkey_list, node))  
                      skip_until_subkey = 1; /* Already processed this one. */
                    else
                      {
                        size_t j;

                        for (j=0; j < ndesc; j++)
                          if (j != descindex && desc[j].exact
                              && exact_subkey_match_p (desc+j, node))
                            break;
                        if (!(j < ndesc))
                          skip_until_subkey = 1; /* No other one matching. */ 
                      }
                  }

		if(skip_until_subkey)
		  continue;

                /* Mark this one as processed. */
                {
                  subkey_list_t tmp = new_subkey_list_item (node);
                  tmp->next = subkey_list;
                  subkey_list = tmp;
                }
	      }

	    if(node->pkt->pkttype==PKT_SIGNATURE)
	      {
		/* do not export packets which are marked as not
		   exportable */
		if(!(options&EXPORT_LOCAL_SIGS)
		   && !node->pkt->pkt.signature->flags.exportable)
		  continue; /* not exportable */

		/* Do not export packets with a "sensitive" revocation
		   key unless the user wants us to.  Note that we do
		   export these when issuing the actual revocation
		   (see revoke.c). */
		if(!(options&EXPORT_SENSITIVE_REVKEYS)
		   && node->pkt->pkt.signature->revkey)
		  {
		    int i;

		    for(i=0;i<node->pkt->pkt.signature->numrevkeys;i++)
		      if(node->pkt->pkt.signature->revkey[i]->class & 0x40)
			break;

		    if(i<node->pkt->pkt.signature->numrevkeys)
		      continue;
		  }
	      }

	    /* Don't export attribs? */
	    if( !(options&EXPORT_ATTRIBUTES) &&
		node->pkt->pkttype == PKT_USER_ID &&
		node->pkt->pkt.user_id->attrib_data ) {
	      /* Skip until we get to something that is not an attrib
		 or a signature on an attrib */
	      while(kbctx->next && kbctx->next->pkt->pkttype==PKT_SIGNATURE) {
		kbctx=kbctx->next;
	      }
 
	      continue;
	    }

	    if( secret == 2 && node->pkt->pkttype == PKT_SECRET_KEY )
	      {
		/* We don't want to export the secret parts of the
		 * primary key, this is done by using GNU protection mode 1001
		 */
		int save_mode = node->pkt->pkt.secret_key->protect.s2k.mode;
		node->pkt->pkt.secret_key->protect.s2k.mode = 1001;
                if ((options&EXPORT_SEXP_FORMAT))
                  rc = build_sexp (out, node->pkt, &indent);
                else
                  rc = build_packet (out, node->pkt);
		node->pkt->pkt.secret_key->protect.s2k.mode = save_mode;
	      }
	    else if (secret == 2 && node->pkt->pkttype == PKT_SECRET_SUBKEY
                     && (opt.export_options&EXPORT_RESET_SUBKEY_PASSWD))
              {
                /* If the subkey is protected reset the passphrase to
                   export an unprotected subkey.  This feature is
                   useful in cases of a subkey copied to an unattended
                   machine where a passphrase is not required. */
                PKT_secret_key *sk_save, *sk;

                sk_save = node->pkt->pkt.secret_key;
                sk = copy_secret_key (NULL, sk_save);
                node->pkt->pkt.secret_key = sk;

                log_info (_("about to export an unprotected subkey\n"));
                switch (is_secret_key_protected (sk))
                  {
                  case -1:
                    rc = G10ERR_PUBKEY_ALGO;
                    break;
                  case 0:
                    break;
                  default:
                    if (sk->protect.s2k.mode == 1001)
                      ; /* No secret parts. */
                    else if( sk->protect.s2k.mode == 1002 ) 
                      ; /* Card key stub. */
                    else 
                      {
                        rc = check_secret_key( sk, 0 );
                      }
                    break;
                  }
                if (rc)
                  {
                    node->pkt->pkt.secret_key = sk_save;
                    free_secret_key (sk);
                    log_error (_("failed to unprotect the subkey: %s\n"),
                               g10_errstr (rc));
                    goto leave;
                  }

                if ((options&EXPORT_SEXP_FORMAT))
                  rc = build_sexp (out, node->pkt, &indent);
                else
                  rc = build_packet (out, node->pkt);

                node->pkt->pkt.secret_key = sk_save;
                free_secret_key (sk);
              }
	    else
	      {
		/* Warn the user if the secret key or any of the secret
		   subkeys are protected with SHA1 and we have
		   simple_sk_checksum set. */
		if(!sha1_warned && opt.simple_sk_checksum &&
		   (node->pkt->pkttype==PKT_SECRET_KEY ||
		    node->pkt->pkttype==PKT_SECRET_SUBKEY) &&
		   node->pkt->pkt.secret_key->protect.sha1chk)
		  {
		    /* I hope this warning doesn't confuse people. */
		    log_info(_("WARNING: secret key %s does not have a "
			       "simple SK checksum\n"),keystr(sk_keyid));

		    sha1_warned=1;
		  }

                if ((options&EXPORT_SEXP_FORMAT))
                  rc = build_sexp (out, node->pkt, &indent);
                else
                  rc = build_packet (out, node->pkt);
	      }

	    if( rc ) {
		log_error("build_packet(%d) failed: %s\n",
			    node->pkt->pkttype, g10_errstr(rc) );
		goto leave;
	    }
	}

        if ((options&EXPORT_SEXP_FORMAT) && indent)
          {
            for (; indent; indent--)
              iobuf_put (out, ')');
            iobuf_put (out, '\n');
          }

	++*any;
	if(keyblock_out)
	  {
	    *keyblock_out=keyblock;
	    break;
	  }
    }