Ejemplo n.º 1
0
/* This function recognizes the signature of the KSP itself. Note that this
 * function prepares the validation of the signature of the KSP with its
 * corresponding public key but does not actually do the validation. The
 * validation should be done with kmocrypt_signature_validate2() once the public
 * key has been obtained from the KOS.
 * This function sets the KMO error string. It returns -1 on failure.
 */
static int recognize_ksp_signature(struct kmocrypt_signature2 *self, kbuffer *buffer, uint32_t total_len) {
    int error = 0;
    uint32_t sig_len;
    size_t scanned_sig_len;
    int digest_len = gcry_md_get_algo_dlen(self->hash_algo);
    uint8_t digest[MAX_DIGEST_LEN];
    char hashname[MAX_HASH_ALGO_NAME_LEN];
    char signame[MAX_SIG_ALGO_NAME_LEN];
    
    /* Verify that we're using the correct signature algorithm. */
    if (self->sig_algo != GCRY_AC_RSA) {
    	kmo_seterror("Signature algorithm is not GCRY_AC_RSA");
	return -1;
    }
    
    /* Get the hash algorithm name. */
    strncpy(hashname, gcry_md_algo_name(self->hash_algo), MAX_HASH_ALGO_NAME_LEN);
    strntolower(hashname, MAX_HASH_ALGO_NAME_LEN);
    
    /* Get the signature algorithm name. */
    strncpy(signame, gcry_pk_algo_name(self->sig_algo), MAX_SIG_ALGO_NAME_LEN);
    strntolower(signame, MAX_SIG_ALGO_NAME_LEN);
    
    /* Hash the content of the KSP up to KSP signature part. */
    gcry_md_hash_buffer(self->hash_algo, digest, buffer->data, buffer->pos);
    
    /* Build the gcrypt hash of the KSP required to verify the signature. */
    error = gcry_sexp_build(&self->sig_hash, NULL, "(4:data(5:flags5:pkcs1)(4:hash %s %b))", 
                            hashname, digest_len, digest);
    if (error) {
        kmo_seterror("cannot build signature hash: %s", gcry_strerror(error));
	return -1;
    }
    
    /* Get the length of the signature. */
    if (total_len < 4) {
    	kmo_seterror("KSP signature section is too short");
	return -1;
    }
    
    sig_len = kbuffer_read32(buffer);
    
    if (total_len != 4 + sig_len) {
    	kmo_seterror("KSP signature section is malformed");
	return -1;
    }
    
    /* Get the signature MPI. */
    error = gcry_mpi_scan(&self->sig_mpi, GCRYMPI_FMT_PGP, kbuffer_current_pos(buffer), sig_len, &scanned_sig_len);
    if (error) {
    	kmo_seterror("invalid MPI in signature: %s", gcry_strerror(error));
	return -1;
    }
    
    if (scanned_sig_len != sig_len) {
    	kmo_seterror("invalid MPI in signature: unexpected size");
	return -1;
    }
    
    /* Skip the signature (just to be thorough, it's not strictly necessary). */
    buffer->pos += sig_len;
    
    /* Build the signature s-expression. */
    error = gcry_sexp_build(&self->sig_sexp, NULL, "(7:sig-val(%s(1:s %m)))", signame, self->sig_mpi);
    if (error) {
    	kmo_seterror("cannot build signature from MPI: %s", gcry_strerror(error));
	return -1;
    }
    
    return 0;
}
Ejemplo n.º 2
0
static void
print_keyrec(int number,struct keyrec *keyrec)
{
  int i;

  iobuf_writebyte(keyrec->uidbuf,0);
  iobuf_flush_temp(keyrec->uidbuf);
  es_printf ("(%d)\t%s  ", number, iobuf_get_temp_buffer (keyrec->uidbuf));

  if (keyrec->size>0)
    es_printf ("%d bit ", keyrec->size);

  if(keyrec->type)
    {
      const char *str;

      str = gcry_pk_algo_name (map_pk_openpgp_to_gcry (keyrec->type));

      if (str && strcmp (str, "?"))
	es_printf ("%s ",str);
      else
	es_printf ("unknown ");
    }

  switch(keyrec->desc.mode)
    {
      /* If the keyserver helper gave us a short keyid, we have no
	 choice but to use it.  Do check --keyid-format to add a 0x if
	 needed. */
    case KEYDB_SEARCH_MODE_SHORT_KID:
      es_printf ("key %s%08lX",
                 (opt.keyid_format==KF_0xSHORT
                  || opt.keyid_format==KF_0xLONG)?"0x":"",
                 (ulong)keyrec->desc.u.kid[1]);
      break;

      /* However, if it gave us a long keyid, we can honor
	 --keyid-format via keystr(). */
    case KEYDB_SEARCH_MODE_LONG_KID:
      es_printf ("key %s",keystr(keyrec->desc.u.kid));
      break;

      /* If it gave us a PGP 2.x fingerprint, not much we can do
	 beyond displaying it. */
    case KEYDB_SEARCH_MODE_FPR16:
      es_printf ("key ");
      for(i=0;i<16;i++)
	es_printf ("%02X",keyrec->desc.u.fpr[i]);
      break;

      /* If we get a modern fingerprint, we have the most
	 flexibility. */
    case KEYDB_SEARCH_MODE_FPR20:
      {
	u32 kid[2];
	keyid_from_fingerprint(keyrec->desc.u.fpr,20,kid);
	es_printf("key %s",keystr(kid));
      }
      break;

    default:
      BUG();
      break;
    }

  if(keyrec->createtime>0)
    {
      es_printf (", ");
      es_printf (_("created: %s"), strtimestamp(keyrec->createtime));
    }

  if(keyrec->expiretime>0)
    {
      es_printf (", ");
      es_printf (_("expires: %s"), strtimestamp(keyrec->expiretime));
    }

  if (keyrec->flags&1)
    es_printf (" (%s)", _("revoked"));
  if(keyrec->flags&2)
    es_printf (" (%s)", _("disabled"));
  if(keyrec->flags&4)
    es_printf (" (%s)", _("expired"));

  es_printf ("\n");
}
Ejemplo n.º 3
0
/* Return a new DEK object Using the string-to-key sepcifier S2K.  Use
   KEYID and PUBKEY_ALGO to prompt the user.  Returns NULL is the user
   selected to cancel the passphrase entry and if CANCELED is not
   NULL, sets it to true.

   MODE 0:  Allow cached passphrase
        1:  Ignore cached passphrase 
        2:  Ditto, but create a new key
        3:  Allow cached passphrase; use the S2K salt as the cache ID
        4:  Ditto, but create a new key
*/
DEK *
passphrase_to_dek_ext (u32 *keyid, int pubkey_algo,
                       int cipher_algo, STRING2KEY *s2k, int mode,
                       const char *tryagain_text, 
                       const char *custdesc, const char *custprompt,
                       int *canceled)
{
  char *pw = NULL;
  DEK *dek;
  STRING2KEY help_s2k;
  int dummy_canceled;
  char s2k_cacheidbuf[1+16+1], *s2k_cacheid = NULL;

  if (!canceled)
    canceled = &dummy_canceled;
  *canceled = 0;
  
  if ( !s2k )
    {
      assert (mode != 3 && mode != 4);
      /* This is used for the old rfc1991 mode 
       * Note: This must match the code in encode.c with opt.rfc1991 set */
      s2k = &help_s2k;
      s2k->mode = 0;
      s2k->hash_algo = S2K_DIGEST_ALGO;
    }

  /* Create a new salt or what else to be filled into the s2k for a
     new key.  */
  if ((mode == 2 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
    {
      gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
      if ( s2k->mode == 3 )
        {
          /* We delay the encoding until it is really needed.  This is
             if we are going to dynamically calibrate it, we need to
             call out to gpg-agent and that should not be done during
             option processing in main().  */
          if (!opt.s2k_count)
            opt.s2k_count = encode_s2k_iterations (0);
          s2k->count = opt.s2k_count;
        }
    }

  /* If we do not have a passphrase available in NEXT_PW and status
     information are request, we print them now. */
  if ( !next_pw && is_status_enabled() ) 
    {
      char buf[50];
      
      if ( keyid )
        {
          u32 used_kid[2];
          char *us;
          
          if ( keyid[2] && keyid[3] ) 
            {
              used_kid[0] = keyid[2];
              used_kid[1] = keyid[3];
            }
          else
            {
              used_kid[0] = keyid[0];
              used_kid[1] = keyid[1];
            }
          
          us = get_long_user_id_string ( keyid );
          write_status_text ( STATUS_USERID_HINT, us );
          xfree(us);
          
          snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
                    (ulong)keyid[0], (ulong)keyid[1],
                    (ulong)used_kid[0], (ulong)used_kid[1],
                    pubkey_algo );
          
          write_status_text ( STATUS_NEED_PASSPHRASE, buf );
	}
      else
        {
          snprintf (buf, sizeof buf -1, "%d %d %d",
                    cipher_algo, s2k->mode, s2k->hash_algo );
          write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
	}
    }

  /* If we do have a keyID, we do not have a passphrase available in
     NEXT_PW, we are not running in batch mode and we do not want to
     ignore the passphrase cache (mode!=1), print a prompt with
     information on that key. */
  if ( keyid && !opt.batch && !next_pw && mode!=1 )
    {
      PKT_public_key *pk = xmalloc_clear( sizeof *pk );
      char *p;
      
      p = get_user_id_native(keyid);
      tty_printf ("\n");
      tty_printf (_("You need a passphrase to unlock the secret key for\n"
                    "user: \"%s\"\n"),p);
      xfree(p);

      if ( !get_pubkey( pk, keyid ) )
        {
          const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
          
          tty_printf (_("%u-bit %s key, ID %s, created %s"),
                      nbits_from_pk( pk ), s?s:"?", keystr(keyid),
                      strtimestamp(pk->timestamp) );
          if ( keyid[2] && keyid[3]
               && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
            {
              if ( keystrlen () > 10 )
                {
                  tty_printf ("\n");
                  tty_printf (_("         (subkey on main key ID %s)"),
                              keystr(&keyid[2]) );
                }
              else
                tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
            }
          tty_printf("\n");
	}

      tty_printf("\n");
      if (pk)
        free_public_key( pk );
    }

  if ( next_pw ) 
    {
      /* Simply return the passphrase we already have in NEXT_PW. */
      pw = next_pw;
      next_pw = NULL;
    }
  else if ( have_static_passphrase () ) 
    {
      /* Return the passphrase we have stored in FD_PASSWD. */
      pw = xmalloc_secure ( strlen(fd_passwd)+1 );
      strcpy ( pw, fd_passwd );
    }
  else 
    {
      if ((mode == 3 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
	{
	  memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
	  *s2k_cacheidbuf = 'S';
	  bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
	  s2k_cacheid = s2k_cacheidbuf;
	}

      /* Divert to the gpg-agent. */
      pw = passphrase_get (keyid, mode == 2, s2k_cacheid,
                           (mode == 2 || mode == 4)? opt.passphrase_repeat : 0,
                           tryagain_text, custdesc, custprompt, canceled);
      if (*canceled)
        {
          xfree (pw);
	  write_status( STATUS_MISSING_PASSPHRASE );
          return NULL;
        }
    }
    
  if ( !pw || !*pw )
    write_status( STATUS_MISSING_PASSPHRASE );

  /* Hash the passphrase and store it in a newly allocated DEK object.
     Keep a copy of the passphrase in LAST_PW for use by
     get_last_passphrase(). */
  dek = xmalloc_secure_clear ( sizeof *dek );
  dek->algo = cipher_algo;
  if ( (!pw || !*pw) && (mode == 2 || mode == 4))
    dek->keylen = 0;
  else
    hash_passphrase (dek, pw, s2k);
  if (s2k_cacheid)
    memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
  xfree(last_pw);
  last_pw = pw;
  return dek;
}
Ejemplo n.º 4
0
/*
 * Ask the GPG Agent for the passphrase.
 * Mode 0:  Allow cached passphrase
 *      1:  No cached passphrase; that is we are asking for a new passphrase
 *          FIXME: Only partially implemented
 *
 * Note that TRYAGAIN_TEXT must not be translated.  If CANCELED is not
 * NULL, the function does set it to 1 if the user canceled the
 * operation.  If CACHEID is not NULL, it will be used as the cacheID
 * for the gpg-agent; if is NULL and a key fingerprint can be
 * computed, this will be used as the cacheid.
 */
static char *
passphrase_get ( u32 *keyid, int mode, const char *cacheid, int repeat,
                 const char *tryagain_text,
                 const char *custom_description,
                 const char *custom_prompt, int *canceled)
{
  int rc;
  char *atext = NULL;
  char *pw = NULL;
  PKT_public_key *pk = xmalloc_clear( sizeof *pk );
  byte fpr[MAX_FINGERPRINT_LEN];
  int have_fpr = 0;
  char *orig_codeset;
  char *my_prompt;
  char hexfprbuf[20*2+1];
  const char *my_cacheid;
  int check = (mode == 1);

  if (canceled)
    *canceled = 0;

#if MAX_FINGERPRINT_LEN < 20
#error agent needs a 20 byte fingerprint
#endif

  memset (fpr, 0, MAX_FINGERPRINT_LEN );
  if( keyid && get_pubkey( pk, keyid ) )
    {
      if (pk)
        free_public_key( pk );      
      pk = NULL; /* oops: no key for some reason */
    }
  
  orig_codeset = i18n_switchto_utf8 ();

  if (custom_description)
    atext = native_to_utf8 (custom_description);
  else if ( !mode && pk && keyid )
    { 
      char *uid;
      size_t uidlen;
      const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
      const char *timestr;
      char *maink;
      
      if ( !algo_name )
        algo_name = "?";

#define KEYIDSTRING _(" (main key ID %s)")

      maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
      if( keyid[2] && keyid[3] && keyid[0] != keyid[2] 
          && keyid[1] != keyid[3] )
        sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
      else
        *maink = 0;
      
      uid = get_user_id ( keyid, &uidlen ); 
      timestr = strtimestamp (pk->timestamp);

#undef KEYIDSTRING

#define PROMPTSTRING _("Please enter the passphrase to unlock the" \
		       " secret key for the OpenPGP certificate:\n" \
		       "\"%.*s\"\n" \
		       "%u-bit %s key, ID %s,\n" \
                       "created %s%s.\n" )

      atext = xmalloc ( 100 + strlen (PROMPTSTRING)  
                        + uidlen + 15 + strlen(algo_name) + keystrlen()
                        + strlen (timestr) + strlen (maink) );
      sprintf (atext, PROMPTSTRING,
               (int)uidlen, uid,
               nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
               maink  );
      xfree (uid);
      xfree (maink);

#undef PROMPTSTRING

      { 
        size_t dummy;
        fingerprint_from_pk( pk, fpr, &dummy );
        have_fpr = 1;
      }
      
    }
  else
    atext = xstrdup ( _("Enter passphrase\n") );
                

  if (!mode && cacheid)
    my_cacheid = cacheid;
  else if (!mode && have_fpr)
    my_cacheid = bin2hex (fpr, 20, hexfprbuf);
  else
    my_cacheid = NULL;

  if (tryagain_text)
    tryagain_text = _(tryagain_text);

  my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;

  rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext,
                             repeat, check, &pw);
  
  xfree (my_prompt);
  xfree (atext); atext = NULL;

  i18n_switchback (orig_codeset);


  if (!rc)
    ;
  else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
    {
      log_info (_("cancelled by user\n") );
      if (canceled)
        *canceled = 1;
    }
  else 
    {
      log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
      /* Due to limitations in the API of the upper layers they
         consider an error as no passphrase entered.  This works in
         most cases but not during key creation where this should
         definitely not happen and let it continue without requiring a
         passphrase.  Given that now all the upper layers handle a
         cancel correctly, we simply set the cancel flag now for all
         errors from the agent.  */ 
      if (canceled)
        *canceled = 1;

      write_status_error ("get_passphrase", rc);
    }

  if (pk)
    free_public_key( pk );
  if (rc)
    {
      xfree (pw);
      return NULL;
    }
  return pw;
}
Ejemplo n.º 5
0
static int
do_encode_md (gcry_md_hd_t md, int algo, int pkalgo, unsigned int nbits,
              gcry_sexp_t pkey, gcry_mpi_t *r_val)
{
  int n;
  size_t nframe;
  unsigned char *frame;

  if (pkalgo == GCRY_PK_DSA || pkalgo == GCRY_PK_ECDSA)
    {
      unsigned int qbits;

      if ( pkalgo == GCRY_PK_ECDSA )
        qbits = gcry_pk_get_nbits (pkey);
      else
        qbits = get_dsa_qbits (pkey);

      if ( (qbits%8) )
	{
	  log_error(_("DSA requires the hash length to be a"
		      " multiple of 8 bits\n"));
	  return gpg_error (GPG_ERR_INTERNAL);
	}

      /* Don't allow any Q smaller than 160 bits.  We don't want
	 someone to issue signatures from a key with a 16-bit Q or
	 something like that, which would look correct but allow
	 trivial forgeries.  Yes, I know this rules out using MD5 with
	 DSA. ;) */
      if (qbits < 160)
	{
	  log_error (_("%s key uses an unsafe (%u bit) hash\n"),
                     gcry_pk_algo_name (pkalgo), qbits);
	  return gpg_error (GPG_ERR_INTERNAL);
	}

      /* Check if we're too short.  Too long is safe as we'll
	 automatically left-truncate. */
      nframe = gcry_md_get_algo_dlen (algo);
      if (nframe < qbits/8)
        {
	  log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
                     (unsigned int)nframe*8,
                     gcry_pk_get_nbits (pkey),
                     gcry_pk_algo_name (pkalgo));
          /* FIXME: we need to check the requirements for ECDSA.  */
          if (nframe < 20 || pkalgo == GCRY_PK_DSA  )
            return gpg_error (GPG_ERR_INTERNAL);
        }

      frame = xtrymalloc (nframe);
      if (!frame)
        return out_of_core ();
      memcpy (frame, gcry_md_read (md, algo), nframe);
      n = nframe;
      /* Truncate.  */
      if (n > qbits/8)
        n = qbits/8;
    }
  else
    {
      int i;
      unsigned char asn[100];
      size_t asnlen;
      size_t len;

      nframe = (nbits+7) / 8;

      asnlen = DIM(asn);
      if (!algo || gcry_md_test_algo (algo))
        return gpg_error (GPG_ERR_DIGEST_ALGO);
      if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
        {
          log_error ("no object identifier for algo %d\n", algo);
          return gpg_error (GPG_ERR_INTERNAL);
        }

      len = gcry_md_get_algo_dlen (algo);

      if ( len + asnlen + 4  > nframe )
        {
          log_error ("can't encode a %d bit MD into a %d bits frame\n",
                     (int)(len*8), (int)nbits);
          return gpg_error (GPG_ERR_INTERNAL);
        }

      /* We encode the MD in this way:
       *
       *	   0  A PAD(n bytes)   0  ASN(asnlen bytes)  MD(len bytes)
       *
       * PAD consists of FF bytes.
       */
      frame = xtrymalloc (nframe);
      if (!frame)
        return out_of_core ();
      n = 0;
      frame[n++] = 0;
      frame[n++] = 1; /* block type */
      i = nframe - len - asnlen -3 ;
      assert ( i > 1 );
      memset ( frame+n, 0xff, i ); n += i;
      frame[n++] = 0;
      memcpy ( frame+n, asn, asnlen ); n += asnlen;
      memcpy ( frame+n, gcry_md_read(md, algo), len ); n += len;
      assert ( n == nframe );
    }
  if (DBG_CRYPTO)
    {
      int j;
      log_debug ("encoded hash:");
      for (j=0; j < nframe; j++)
        log_printf (" %02X", frame[j]);
      log_printf ("\n");
    }

  gcry_mpi_scan (r_val, GCRYMPI_FMT_USG, frame, n, &nframe);
  xfree (frame);
  return 0;
}
Ejemplo n.º 6
0
static void
print_keyrec(int number,struct keyrec *keyrec)
{
  int i;

  iobuf_writebyte(keyrec->uidbuf,0);
  iobuf_flush_temp(keyrec->uidbuf);
  es_printf ("(%d)\t%s  ", number, iobuf_get_temp_buffer (keyrec->uidbuf));

  if (keyrec->size>0)
    es_printf ("%d bit ", keyrec->size);

  if(keyrec->type)
    {
      const char *str = gcry_pk_algo_name (keyrec->type);

      if(str)
	es_printf ("%s ",str);
      else
	es_printf ("unknown ");
    }

  switch(keyrec->desc.mode)
    {
      /* If the keyserver helper gave us a short keyid, we have no
	 choice but to use it.  Do check --keyid-format to add a 0x if
	 needed. */
    case KEYDB_SEARCH_MODE_SHORT_KID:
      es_printf ("key %s%08lX",
                 (opt.keyid_format==KF_0xSHORT
                  || opt.keyid_format==KF_0xLONG)?"0x":"",
                 (ulong)keyrec->desc.u.kid[1]);
      break;

      /* However, if it gave us a long keyid, we can honor
	 --keyid-format */
    case KEYDB_SEARCH_MODE_LONG_KID:
      es_printf ("key %s",keystr(keyrec->desc.u.kid));
      break;

    case KEYDB_SEARCH_MODE_FPR16:
      es_printf ("key ");
      for(i=0;i<16;i++)
	es_printf ("%02X",keyrec->desc.u.fpr[i]);
      break;

    case KEYDB_SEARCH_MODE_FPR20:
      es_printf ("key ");
      for(i=0;i<20;i++)
	es_printf ("%02X", keyrec->desc.u.fpr[i]);
      break;

    default:
      BUG();
      break;
    }

  if(keyrec->createtime>0)
    {
      es_printf (", ");
      es_printf (_("created: %s"), strtimestamp(keyrec->createtime));
    }

  if(keyrec->expiretime>0)
    {
      es_printf (", ");
      es_printf (_("expires: %s"), strtimestamp(keyrec->expiretime));
    }

  if (keyrec->flags&1)
    es_printf (" (%s)", _("revoked"));
  if(keyrec->flags&2)
    es_printf (" (%s)", _("disabled"));
  if(keyrec->flags&4)
    es_printf (" (%s)", _("expired"));

  es_printf ("\n");
}