示例#1
0
文件: verify.c 项目: intgr/gnutls
/* verifies if the certificate is properly signed.
 * returns GNUTLS_E_PK_VERIFY_SIG_FAILED on failure and 1 on success.
 * 
 * 'data' is the signed data
 * 'signature' is the signature!
 */
int
_gnutls_x509_verify_data (gnutls_digest_algorithm_t algo,
                          const gnutls_datum_t * data,
                          const gnutls_datum_t * signature,
                          gnutls_x509_crt_t issuer)
{
  gnutls_pk_params_st issuer_params;
  int ret;

  /* Read the MPI parameters from the issuer's certificate.
   */
  ret =
    _gnutls_x509_crt_get_mpis (issuer, &issuer_params);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret =
    pubkey_verify_data (gnutls_x509_crt_get_pk_algorithm (issuer, NULL), algo,
                        data, signature, &issuer_params);
  if (ret < 0)
    {
      gnutls_assert ();
    }

  /* release all allocated MPIs
   */
  gnutls_pk_params_release(&issuer_params);

  return ret;
}
示例#2
0
/* Extracts DSA and RSA parameters from a certificate.
 */
int
_gnutls_x509_crt_get_mpis (gnutls_x509_crt_t cert,
			   bigint_t * params, int *params_size)
{
  int pk_algorithm;

  /* Read the algorithm's OID
   */
  pk_algorithm = gnutls_x509_crt_get_pk_algorithm (cert, NULL);

  return get_mpis (pk_algorithm, cert->cert,
		   "tbsCertificate.subjectPublicKeyInfo", params,
		   params_size);
}
示例#3
0
/* Check if the number of bits of the key in the certificate
 * is unacceptable.
  */
inline static int
check_bits (gnutls_x509_crt_t crt, unsigned int max_bits)
{
  int ret;
  unsigned int bits;

  ret = gnutls_x509_crt_get_pk_algorithm (crt, &bits);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  if (bits > max_bits && max_bits > 0)
    {
      gnutls_assert ();
      return GNUTLS_E_CONSTRAINT_ERROR;
    }

  return 0;
}
示例#4
0
文件: verify.c 项目: dezelin/maily
/* verifies if the certificate is properly signed.
 * returns GNUTLS_E_PK_VERIFY_SIG_FAILED on failure and 1 on success.
 * 
 * 'tbs' is the signed data
 * 'signature' is the signature!
 */
int
_gnutls_x509_verify_signature (const gnutls_datum_t * tbs,
                               const gnutls_datum_t * hash,
                               const gnutls_datum_t * signature,
                               gnutls_x509_crt_t issuer)
{
  bigint_t issuer_params[MAX_PUBLIC_PARAMS_SIZE];
  int ret, issuer_params_size, i;

  /* Read the MPI parameters from the issuer's certificate.
   */
  issuer_params_size = MAX_PUBLIC_PARAMS_SIZE;
  ret =
    _gnutls_x509_crt_get_mpis (issuer, issuer_params, &issuer_params_size);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  ret =
    pubkey_verify_sig (tbs, hash, signature,
                       gnutls_x509_crt_get_pk_algorithm (issuer, NULL),
                       issuer_params, issuer_params_size);
  if (ret < 0)
    {
      gnutls_assert ();
    }

  /* release all allocated MPIs
   */
  for (i = 0; i < issuer_params_size; i++)
    {
      _gnutls_mpi_release (&issuer_params[i]);
    }

  return ret;
}
示例#5
0
/*-
  * gnutls_x509_extract_certificate_pk_algorithm - This function returns the certificate's PublicKey algorithm
  * @cert: is a DER encoded X.509 certificate
  * @bits: if bits is non null it will hold the size of the parameters' in bits
  *
  * This function will return the public key algorithm of an X.509 
  * certificate.
  *
  * If bits is non null, it should have enough size to hold the parameters
  * size in bits. For RSA the bits returned is the modulus. 
  * For DSA the bits returned are of the public
  * exponent.
  *
  * Returns a member of the gnutls_pk_algorithm_t enumeration on success,
  * or a negative value on error.
  *
  -*/
int
gnutls_x509_extract_certificate_pk_algorithm (const gnutls_datum_t *
					      cert, int *bits)
{
  gnutls_x509_crt_t xcert;
  int result;

  result = gnutls_x509_crt_init (&xcert);
  if (result < 0)
    return result;

  result = gnutls_x509_crt_import (xcert, cert, GNUTLS_X509_FMT_DER);
  if (result < 0)
    {
      gnutls_x509_crt_deinit (xcert);
      return result;
    }

  result = gnutls_x509_crt_get_pk_algorithm (xcert, bits);

  gnutls_x509_crt_deinit (xcert);

  return result;
}
示例#6
0
文件: pubkey.c 项目: GostCrypt/GnuTLS
/**
 * gnutls_pubkey_import_x509:
 * @key: The public key
 * @crt: The certificate to be imported
 * @flags: should be zero
 *
 * This function will import the given public key to the abstract
 * #gnutls_pubkey_t type.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 2.12.0
 **/
int
gnutls_pubkey_import_x509(gnutls_pubkey_t key, gnutls_x509_crt_t crt,
			  unsigned int flags)
{
	int ret;

	gnutls_pk_params_release(&key->params);
	/* params initialized in _gnutls_x509_crt_get_mpis */

	key->pk_algorithm =
	    gnutls_x509_crt_get_pk_algorithm(crt, &key->bits);

	ret = gnutls_x509_crt_get_key_usage(crt, &key->key_usage, NULL);
	if (ret < 0)
		key->key_usage = 0;

	ret = _gnutls_x509_crt_get_mpis(crt, &key->params);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	return 0;
}
示例#7
0
文件: verify.c 项目: GostCrypt/GnuTLS
/* Checks whether the provided certificates are acceptable
 * according to verification profile specified.
 *
 * @crt: a certificate
 * @issuer: the certificates issuer (allowed to be NULL)
 * @sigalg: the signature algorithm used
 * @flags: the specified verification flags
 */
static unsigned is_level_acceptable(
	gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer,
	gnutls_sign_algorithm_t sigalg, unsigned flags)
{
	gnutls_certificate_verification_profiles_t profile = GNUTLS_VFLAGS_TO_PROFILE(flags);
	const mac_entry_st *entry;
	int issuer_pkalg = 0, pkalg, ret;
	unsigned bits = 0, issuer_bits = 0, sym_bits = 0;
	gnutls_pk_params_st params;
	gnutls_sec_param_t sp;
	int hash;

	if (profile == 0)
		return 1;

	pkalg = gnutls_x509_crt_get_pk_algorithm(crt, &bits);
	if (pkalg < 0)
		return gnutls_assert_val(0);

	if (issuer) {
		issuer_pkalg = gnutls_x509_crt_get_pk_algorithm(issuer, &issuer_bits);
		if (issuer_pkalg < 0)
			return gnutls_assert_val(0);
	}

	switch (profile) {
		CASE_SEC_PARAM(GNUTLS_PROFILE_VERY_WEAK, GNUTLS_SEC_PARAM_VERY_WEAK);
		CASE_SEC_PARAM(GNUTLS_PROFILE_LOW, GNUTLS_SEC_PARAM_LOW);
		CASE_SEC_PARAM(GNUTLS_PROFILE_LEGACY, GNUTLS_SEC_PARAM_LEGACY);
		CASE_SEC_PARAM(GNUTLS_PROFILE_MEDIUM, GNUTLS_SEC_PARAM_MEDIUM);
		CASE_SEC_PARAM(GNUTLS_PROFILE_HIGH, GNUTLS_SEC_PARAM_HIGH);
		CASE_SEC_PARAM(GNUTLS_PROFILE_ULTRA, GNUTLS_SEC_PARAM_ULTRA);
		case GNUTLS_PROFILE_SUITEB128:
		case GNUTLS_PROFILE_SUITEB192: {
			unsigned curve, issuer_curve;

			/* check suiteB params validity: rfc5759 */

			if (gnutls_x509_crt_get_version(crt) != 3) {
				_gnutls_debug_log("SUITEB: certificate uses an unacceptable version number\n");
				return gnutls_assert_val(0);
			}

			if (sigalg != GNUTLS_SIGN_ECDSA_SHA256 && sigalg != GNUTLS_SIGN_ECDSA_SHA384) {
				_gnutls_debug_log("SUITEB: certificate is not signed using ECDSA-SHA256 or ECDSA-SHA384\n");
				return gnutls_assert_val(0);
			}

			if (pkalg != GNUTLS_PK_EC) {
				_gnutls_debug_log("SUITEB: certificate does not contain ECC parameters\n");
				return gnutls_assert_val(0);
			}

			if (issuer_pkalg != GNUTLS_PK_EC) {
				_gnutls_debug_log("SUITEB: certificate's issuer does not have ECC parameters\n");
				return gnutls_assert_val(0);
			}

			ret = _gnutls_x509_crt_get_mpis(crt, &params);
			if (ret < 0) {
				_gnutls_debug_log("SUITEB: cannot read certificate params\n");
				return gnutls_assert_val(0);
			}

			curve = params.flags;
			gnutls_pk_params_release(&params);

			if (curve != GNUTLS_ECC_CURVE_SECP256R1 &&
				curve != GNUTLS_ECC_CURVE_SECP384R1) {
				_gnutls_debug_log("SUITEB: certificate's ECC params do not contain SECP256R1 or SECP384R1\n");
				return gnutls_assert_val(0);
			}

			if (profile == GNUTLS_PROFILE_SUITEB192) {
				if (curve != GNUTLS_ECC_CURVE_SECP384R1) {
					_gnutls_debug_log("SUITEB192: certificate does not use SECP384R1\n");
					return gnutls_assert_val(0);
				}
			}

			if (issuer != NULL) {
				if (gnutls_x509_crt_get_version(issuer) != 3) {
					_gnutls_debug_log("SUITEB: certificate's issuer uses an unacceptable version number\n");
					return gnutls_assert_val(0);
				}

				ret = _gnutls_x509_crt_get_mpis(issuer, &params);
				if (ret < 0) {
					_gnutls_debug_log("SUITEB: cannot read certificate params\n");
					return gnutls_assert_val(0);
				}

				issuer_curve = params.flags;
				gnutls_pk_params_release(&params);

				if (issuer_curve != GNUTLS_ECC_CURVE_SECP256R1 &&
					issuer_curve != GNUTLS_ECC_CURVE_SECP384R1) {
					_gnutls_debug_log("SUITEB: certificate's issuer ECC params do not contain SECP256R1 or SECP384R1\n");
					return gnutls_assert_val(0);
				}

				if (issuer_curve < curve) {
					_gnutls_debug_log("SUITEB: certificate's issuer ECC params are weaker than the certificate's\n");
					return gnutls_assert_val(0);
				}

				if (sigalg == GNUTLS_SIGN_ECDSA_SHA256 && 
					issuer_curve == GNUTLS_ECC_CURVE_SECP384R1) {
					_gnutls_debug_log("SUITEB: certificate is signed with ECDSA-SHA256 when using SECP384R1\n");
					return gnutls_assert_val(0);
				}
			}

			break;
		}
	}

	return 1;
}
示例#8
0
unsigned char *crypto_decrypt_signature(crypto_ctx *ctx,
                                        const unsigned char *sig_data,
                                        size_t sig_len,
                                        size_t *out_len,
                                        unsigned int padding,
                                        crypto_error **error)
{
    unsigned char *buf = NULL, *rec_hash = NULL;
    gnutls_datum_t n = { NULL, 0 }, e = { NULL, 0 };
    int err, algo;
    gcry_sexp_t key = NULL, sig = NULL, decrypted = NULL, child = NULL;
    gcry_mpi_t n_mpi = NULL, e_mpi = NULL, sig_mpi = NULL, dec_mpi = NULL;
    size_t buf_len = 0, hash_len = 0;

    if (!ctx) {
        crypto_error_set(error, 1, 0, "invalid crypto context");
        return NULL;
    }

    if (!ctx->num) {
        crypto_error_set(error, 1, 0, "no certificates in the stack");
        return NULL;
    }

    algo = gnutls_x509_crt_get_pk_algorithm(ctx->stack[ctx->num - 1], NULL);
    if (algo != GNUTLS_PK_RSA) {
        crypto_error_set(error, 1, 0, "certificate public key algorithm not RSA");
        return NULL;
    }

    err = gnutls_x509_crt_get_pk_rsa_raw(ctx->stack[ctx->num - 1], &n, &e);
    if (err != GNUTLS_E_SUCCESS) {
        crypto_error_set(error, 1, 0, "error getting certificate public key");
        return NULL;
    }

    err = gcry_mpi_scan(&n_mpi, GCRYMPI_FMT_USG, n.data, n.size, NULL);
    if (err) {
        crypto_error_set(error, 1, 0, "invalid RSA key 'n' format");
        goto out;
    }

    err = gcry_mpi_scan(&e_mpi, GCRYMPI_FMT_USG, e.data, e.size, NULL);
    if (err) {
        crypto_error_set(error, 1, 0, "invalid RSA key 'e' format");
        goto out;
    }

    err = gcry_sexp_build(&key, NULL, "(public-key (rsa (n %m) (e %m)))", n_mpi, e_mpi);
    if (err) {
        crypto_error_set(error, 1, 0, "could not create public-key expression");
        goto out;
    }

    err = gcry_mpi_scan(&sig_mpi, GCRYMPI_FMT_USG, sig_data, sig_len, NULL);
    if (err) {
        crypto_error_set(error, 1, 0, "invalid signature format");
        goto out;
    }

    err = gcry_sexp_build(&sig, NULL, "(data (flags raw) (value %m))", sig_mpi);
    if (err) {
        crypto_error_set(error, 1, 0, "could not create signature expression");
        goto out;
    }

    /* encrypt is equivalent to public key decryption for RSA keys */
    err = gcry_pk_encrypt(&decrypted, sig, key);
    if (err) {
        crypto_error_set(error, 1, 0, "could not decrypt signature");
        goto out;
    }

    child = gcry_sexp_find_token(decrypted, "a", 1);
    if (!child) {
        crypto_error_set(error, 1, 0, "could not get decrypted signature result");
        goto out;
    }

    dec_mpi = gcry_sexp_nth_mpi(child, 1, GCRYMPI_FMT_USG);
    gcry_sexp_release(child);

    if (!dec_mpi) {
        crypto_error_set(error, 1, 0, "could not get decrypted signature result");
        goto out;
    }

    gcry_mpi_aprint(GCRYMPI_FMT_USG, &buf, &buf_len, dec_mpi);
    if (!buf) {
        crypto_error_set(error, 1, 0, "could not get extract decrypted signature");
        goto out;
    }

    switch (padding) {
    case CRYPTO_PAD_NONE:
        rec_hash = buf;
        hash_len = buf_len;
        buf = NULL;
        *out_len = (int) hash_len;
        break;
    case CRYPTO_PAD_PKCS1:
        rec_hash = check_pkcs1_padding(buf, buf_len, &hash_len, error);
        if (!rec_hash) {
            crypto_error_set(error, 1, 0, "could not get extract decrypted padded signature");
            goto out;
        }
        *out_len = (int) hash_len;
        break;
    default:
        crypto_error_set(error, 1, 0, "unknown padding mechanism %d", padding);
        break;
    }

out:
    if (buf)
        free(buf);
    if (dec_mpi)
        gcry_mpi_release(dec_mpi);
    if (decrypted)
        gcry_sexp_release(decrypted);
    if (key)
        gcry_sexp_release(key);
    if (sig)
        gcry_sexp_release(sig);
    if (sig_mpi)
        gcry_mpi_release(sig_mpi);
    if (n_mpi)
        gcry_mpi_release(n_mpi);
    if (e_mpi)
        gcry_mpi_release(e_mpi);
    if (n.data)
        gcry_free(n.data);
    if (e.data)
        gcry_free(e.data);

    return rec_hash;
}
示例#9
0
文件: tlssocket.cpp 项目: jplee/MILF
bool CTlsSocket::ExtractCert(const void* in, CCertificate& out)
{
	const gnutls_datum_t* datum = reinterpret_cast<const gnutls_datum_t*>(in);
	
	gnutls_x509_crt_t cert;
	if (gnutls_x509_crt_init(&cert))
	{
		m_pOwner->LogMessage(::Error, _("Could not initialize structure for peer certificates, gnutls_x509_crt_init failed"));
		return false;
	}

	if (gnutls_x509_crt_import(cert, datum, GNUTLS_X509_FMT_DER))
	{
		m_pOwner->LogMessage(::Error, _("Could not import peer certificates, gnutls_x509_crt_import failed"));
		gnutls_x509_crt_deinit(cert);
		return false;
	}

	wxDateTime expirationTime = gnutls_x509_crt_get_expiration_time(cert);
	wxDateTime activationTime = gnutls_x509_crt_get_activation_time(cert);

	// Get the serial number of the certificate
	unsigned char buffer[40];
	size_t size = sizeof(buffer);
	int res = gnutls_x509_crt_get_serial(cert, buffer, &size);
	if( res != 0 ) {
		size = 0;
	}

	wxString serial = bin2hex(buffer, size);

	unsigned int pkBits;
	int pkAlgo = gnutls_x509_crt_get_pk_algorithm(cert, &pkBits);
	wxString pkAlgoName;
	if (pkAlgo >= 0)
	{
		const char* pAlgo = gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)pkAlgo);
		if (pAlgo)
			pkAlgoName = wxString(pAlgo, wxConvUTF8);
	}

	int signAlgo = gnutls_x509_crt_get_signature_algorithm(cert);
	wxString signAlgoName;
	if (signAlgo >= 0)
	{
		const char* pAlgo = gnutls_sign_algorithm_get_name((gnutls_sign_algorithm_t)signAlgo);
		if (pAlgo)
			signAlgoName = wxString(pAlgo, wxConvUTF8);
	}

	wxString subject, issuer;

	size = 0;
	res = gnutls_x509_crt_get_dn(cert, 0, &size);
	if (size)
	{
		char* dn = new char[size + 1];
		dn[size] = 0;
		if (!(res = gnutls_x509_crt_get_dn(cert, dn, &size)))
		{
			dn[size] = 0;
			subject = wxString(dn, wxConvUTF8);
		}
		else
			LogError(res, _T("gnutls_x509_crt_get_dn"));
		delete [] dn;
	}
	else
		LogError(res, _T("gnutls_x509_crt_get_dn"));
	if (subject == _T(""))
	{
		m_pOwner->LogMessage(::Error, _("Could not get distinguished name of certificate subject, gnutls_x509_get_dn failed"));
		gnutls_x509_crt_deinit(cert);
		return false;
	}

	size = 0;
	res = gnutls_x509_crt_get_issuer_dn(cert, 0, &size);
	if (size)
	{
		char* dn = new char[++size + 1];
		dn[size] = 0;
		if (!(res = gnutls_x509_crt_get_issuer_dn(cert, dn, &size)))
		{
			dn[size] = 0;
			issuer = wxString(dn, wxConvUTF8);
		}
		else
			LogError(res, _T("gnutls_x509_crt_get_issuer_dn"));
		delete [] dn;
	}
	else
		LogError(res, _T("gnutls_x509_crt_get_issuer_dn"));
	if (issuer == _T(""))
	{
		m_pOwner->LogMessage(::Error, _("Could not get distinguished name of certificate issuer, gnutls_x509_get_issuer_dn failed"));
		gnutls_x509_crt_deinit(cert);
		return false;
	}

	wxString fingerprint_md5;
	wxString fingerprint_sha1;

	unsigned char digest[100];
	size = sizeof(digest) - 1;
	if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &size))
	{
		digest[size] = 0;
		fingerprint_md5 = bin2hex(digest, size);
	}
	size = sizeof(digest) - 1;
	if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, digest, &size))
	{
		digest[size] = 0;
		fingerprint_sha1 = bin2hex(digest, size);
	}

	gnutls_x509_crt_deinit(cert);

	out = CCertificate(
		datum->data, datum->size,
		activationTime, expirationTime,
		serial,
		pkAlgoName, pkBits,
		signAlgoName,
		fingerprint_md5,
		fingerprint_sha1,
		subject,
		issuer);

	return true;
}
示例#10
0
文件: mpi.c 项目: bf4/pidgin-mac
/* Extracts DSA and RSA parameters from a certificate.
 */
int
_gnutls_x509_crt_get_mpis (gnutls_x509_crt_t cert,
			   bigint_t * params, int *params_size)
{
  int result;
  int pk_algorithm;
  gnutls_datum tmp = { NULL, 0 };

  /* Read the algorithm's OID
   */
  pk_algorithm = gnutls_x509_crt_get_pk_algorithm (cert, NULL);

  /* Read the algorithm's parameters
   */
  result = _gnutls_x509_read_value (cert->cert,
				    "tbsCertificate.subjectPublicKeyInfo.subjectPublicKey",
				    &tmp, 2);

  if (result < 0)
    {
      gnutls_assert ();
      return result;
    }

  switch (pk_algorithm)
    {
    case GNUTLS_PK_RSA:
      /* params[0] is the modulus,
       * params[1] is the exponent
       */
      if (*params_size < RSA_PUBLIC_PARAMS)
	{
	  gnutls_assert ();
	  /* internal error. Increase the bigint_ts in params */
	  result = GNUTLS_E_INTERNAL_ERROR;
	  goto error;
	}

      if ((result =
	   _gnutls_x509_read_rsa_params (tmp.data, tmp.size, params)) < 0)
	{
	  gnutls_assert ();
	  goto error;
	}
      *params_size = RSA_PUBLIC_PARAMS;

      break;
    case GNUTLS_PK_DSA:
      /* params[0] is p,
       * params[1] is q,
       * params[2] is q,
       * params[3] is pub.
       */

      if (*params_size < DSA_PUBLIC_PARAMS)
	{
	  gnutls_assert ();
	  /* internal error. Increase the bigint_ts in params */
	  result = GNUTLS_E_INTERNAL_ERROR;
	  goto error;
	}

      if ((result =
	   _gnutls_x509_read_dsa_pubkey (tmp.data, tmp.size, params)) < 0)
	{
	  gnutls_assert ();
	  goto error;
	}

      /* Now read the parameters
       */
      _gnutls_free_datum (&tmp);

      result = _gnutls_x509_read_value (cert->cert,
					"tbsCertificate.subjectPublicKeyInfo.algorithm.parameters",
					&tmp, 0);

      /* FIXME: If the parameters are not included in the certificate
       * then the issuer's parameters should be used. This is not
       * done yet.
       */

      if (result < 0)
	{
	  gnutls_assert ();
	  goto error;
	}

      if ((result =
	   _gnutls_x509_read_dsa_params (tmp.data, tmp.size, params)) < 0)
	{
	  gnutls_assert ();
	  goto error;
	}
      *params_size = DSA_PUBLIC_PARAMS;

      break;

    default:
      /* other types like DH
       * currently not supported
       */
      gnutls_assert ();
      result = GNUTLS_E_X509_CERTIFICATE_ERROR;
      goto error;
    }

  result = 0;

error:
  _gnutls_free_datum (&tmp);
  return result;
}
示例#11
0
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum *chainp;
  unsigned int verify_status;
  gnutls_x509_crt x509_cert,x509_issuer;
  gnutls_datum issuerp;
  char certbuf[256]; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session session = conn->ssl[sockindex].session;
  int rc;
  int incache;
  void *ssl_sessionid;
  CURLcode result = CURLE_OK;

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else {
    infof(data, "\t server certificate verification SKIPPED\n");
    goto after_server_cert_verification;
  }

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  /* convert the given DER or PEM encoded Certificate to the native
     gnutls_x509_crt_t format */
  gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);

  if(!rc) {
    if(data->set.ssl.verifyhost) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert expiration date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock < time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate expiration date has passed.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate expiration date FAILED\n");
  }
  else
    infof(data, "\t server certificate expiration date OK\n");

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert activation date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock > time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate not activated yet.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate activation date FAILED\n");
  }
  else
    infof(data, "\t server certificate activation date OK\n");

  /* Show:

  - ciphers used
  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

after_server_cert_verification:

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

  /* the name of the cipher used. ie 3DES. */
  ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  infof(data, "\t cipher: %s\n", ptr);

  /* the MAC algorithms name. ie SHA1 */
  ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  infof(data, "\t MAC: %s\n", ptr);

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
示例#12
0
/* This function will print information about this session's peer
 * certificate.
 */
void
print_x509_certificate_info (gnutls_session_t session)
{
  char serial[40];
  char dn[128];
  size_t size;
  unsigned int algo, bits;
  time_t expiration_time, activation_time;
  const gnutls_datum_t *cert_list;
  unsigned int cert_list_size = 0;
  gnutls_x509_crt_t cert;

  /* This function only works for X.509 certificates.
   */
  if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
    return;

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);

  printf ("Peer provided %d certificates.\n", cert_list_size);

  if (cert_list_size > 0)
    {

      /* we only print information about the first certificate.
       */
      gnutls_x509_crt_init (&cert);

      gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER);

      printf ("Certificate info:\n");

      expiration_time = gnutls_x509_crt_get_expiration_time (cert);
      activation_time = gnutls_x509_crt_get_activation_time (cert);

      printf ("\tCertificate is valid since: %s", ctime (&activation_time));
      printf ("\tCertificate expires: %s", ctime (&expiration_time));

      /* Print the serial number of the certificate.
       */
      size = sizeof (serial);
      gnutls_x509_crt_get_serial (cert, serial, &size);

      printf ("\tCertificate serial number: %s\n", bin2hex (serial, size));

      /* Extract some of the public key algorithm's parameters
       */
      algo = gnutls_x509_crt_get_pk_algorithm (cert, &bits);

      printf ("Certificate public key: %s",
	      gnutls_pk_algorithm_get_name (algo));

      /* Print the version of the X.509 
       * certificate.
       */
      printf ("\tCertificate version: #%d\n",
	      gnutls_x509_crt_get_version (cert));

      size = sizeof (dn);
      gnutls_x509_crt_get_dn (cert, dn, &size);
      printf ("\tDN: %s\n", dn);

      size = sizeof (dn);
      gnutls_x509_crt_get_issuer_dn (cert, dn, &size);
      printf ("\tIssuer's DN: %s\n", dn);

      gnutls_x509_crt_deinit (cert);

    }
}
示例#13
0
文件: verify.c 项目: gnutls/gnutls
/* verifies if the certificate is properly signed.
 * returns GNUTLS_E_PK_VERIFY_SIG_FAILED on failure and 1 on success.
 * 
 * 'data' is the signed data
 * 'signature' is the signature!
 */
static int
_gnutls_x509_verify_data(gnutls_sign_algorithm_t sign,
			 const gnutls_datum_t * data,
			 const gnutls_datum_t * signature,
			 gnutls_x509_crt_t cert,
			 gnutls_x509_crt_t issuer,
			 unsigned vflags)
{
	gnutls_pk_params_st params;
	gnutls_pk_algorithm_t issuer_pk;
	int ret;
	gnutls_x509_spki_st sign_params;
	const gnutls_sign_entry_st *se;

	/* Read the MPI parameters from the issuer's certificate.
	 */
	ret = _gnutls_x509_crt_get_mpis(issuer, &params);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	issuer_pk = gnutls_x509_crt_get_pk_algorithm(issuer, NULL);

	se = _gnutls_sign_to_entry(sign);
	if (se == NULL)
		return gnutls_assert_val(GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM);

	if (cert != NULL) {
		ret = _gnutls_x509_read_sign_params(cert->cert,
						    "signatureAlgorithm",
						    &sign_params);
		if (ret < 0) {
			gnutls_assert();
			goto cleanup;
		}

		ret = _gnutls_x509_validate_sign_params(issuer_pk,
							issuer->cert,
							"tbsCertificate."
							"subjectPublicKeyInfo."
							"algorithm",
							&sign_params);
		if (ret < 0) {
			gnutls_assert();
			goto cleanup;
		}
	} else {
		memcpy(&sign_params, &params.spki,
		       sizeof(gnutls_x509_spki_st));

		sign_params.pk = se->pk;
		if (sign_params.pk == GNUTLS_PK_RSA_PSS)
			sign_params.rsa_pss_dig = se->hash;
	}

	ret = pubkey_verify_data(se, hash_to_entry(se->hash), data, signature, &params,
				 &sign_params, vflags);
	if (ret < 0) {
		gnutls_assert();
	}

 cleanup:
	/* release all allocated MPIs
	 */
	gnutls_pk_params_release(&params);

	return ret;
}
示例#14
0
/*
 * This function is called after the TCP connect has completed. Setup the TLS
 * layer and do all necessary magic.
 */
CURLcode
Curl_gtls_connect(struct connectdata *conn,
                  int sockindex)

{
    const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
    struct SessionHandle *data = conn->data;
    gnutls_session session;
    int rc;
    unsigned int cert_list_size;
    const gnutls_datum *chainp;
    unsigned int verify_status;
    gnutls_x509_crt x509_cert;
    char certbuf[256]; /* big enough? */
    size_t size;
    unsigned int algo;
    unsigned int bits;
    time_t clock;
    const char *ptr;
    void *ssl_sessionid;
    size_t ssl_idsize;

    /* GnuTLS only supports TLSv1 (and SSLv3?) */
    if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
        failf(data, "GnuTLS does not support SSLv2");
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* allocate a cred struct */
    rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
    if(rc < 0) {
        failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
        return CURLE_SSL_CONNECT_ERROR;
    }

    if(data->set.ssl.CAfile) {
        /* set the trusted CA cert bundle file */
        gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
                                            GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

        rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
                data->set.ssl.CAfile,
                GNUTLS_X509_FMT_PEM);
        if(rc < 0) {
            infof(data, "error reading ca cert file %s (%s)\n",
                  data->set.ssl.CAfile, gnutls_strerror(rc));
            if (data->set.ssl.verifypeer)
                return CURLE_SSL_CACERT_BADFILE;
        }
        else
            infof(data, "found %d certificates in %s\n",
                  rc, data->set.ssl.CAfile);
    }

    /* Initialize TLS session as a client */
    rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
    if(rc) {
        failf(data, "gnutls_init() failed: %d", rc);
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* convenient assign */
    session = conn->ssl[sockindex].session;

    /* Use default priorities */
    rc = gnutls_set_default_priority(session);
    if(rc < 0)
        return CURLE_SSL_CONNECT_ERROR;

    /* Sets the priority on the certificate types supported by gnutls. Priority
       is higher for types specified before others. After specifying the types
       you want, you must append a 0. */
    rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
    if(rc < 0)
        return CURLE_SSL_CONNECT_ERROR;

    if(data->set.cert) {
        if( gnutls_certificate_set_x509_key_file(
                    conn->ssl[sockindex].cred, data->set.cert,
                    data->set.key != 0 ? data->set.key : data->set.cert,
                    do_file_type(data->set.cert_type) ) ) {
            failf(data, "error reading X.509 key or certificate file");
            return CURLE_SSL_CONNECT_ERROR;
        }
    }

    /* put the credentials to the current session */
    rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
                                conn->ssl[sockindex].cred);

    /* set the connection handle (file descriptor for the socket) */
    gnutls_transport_set_ptr(session,
                             (gnutls_transport_ptr)conn->sock[sockindex]);

    /* register callback functions to send and receive data. */
    gnutls_transport_set_push_function(session, Curl_gtls_push);
    gnutls_transport_set_pull_function(session, Curl_gtls_pull);

    /* lowat must be set to zero when using custom push and pull functions. */
    gnutls_transport_set_lowat(session, 0);

    /* This might be a reconnect, so we check for a session ID in the cache
       to speed up things */

    if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
        /* we got a session id, use it! */
        gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);

        /* Informational message */
        infof (data, "SSL re-using session ID\n");
    }

    rc = handshake(conn, session, sockindex, TRUE);
    if(rc)
        /* handshake() sets its own error message with failf() */
        return rc;

    /* This function will return the peer's raw certificate (chain) as sent by
       the peer. These certificates are in raw format (DER encoded for
       X.509). In case of a X.509 then a certificate list may be present. The
       first certificate in the list is the peer's certificate, following the
       issuer's certificate, then the issuer's issuer etc. */

    chainp = gnutls_certificate_get_peers(session, &cert_list_size);
    if(!chainp) {
        if(data->set.ssl.verifyhost) {
            failf(data, "failed to get server cert");
            return CURLE_SSL_PEER_CERTIFICATE;
        }
        infof(data, "\t common name: WARNING couldn't obtain\n");
    }

    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or more
       of the gnutls_certificate_status_t enumerated elements bitwise or'd. To
       avoid denial of service attacks some default upper limits regarding the
       certificate key size and chain size are set. To override them use
       gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if (rc < 0) {
        failf(data, "server cert verify failed: %d", rc);
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
        if (data->set.ssl.verifypeer) {
            failf(data, "server certificate verification failed. CAfile: %s",
                  data->set.ssl.CAfile?data->set.ssl.CAfile:"none");
            return CURLE_SSL_CACERT;
        }
        else
            infof(data, "\t server certificate verification FAILED\n");
    }
    else
        infof(data, "\t server certificate verification OK\n");

    /* initialize an X.509 certificate structure. */
    gnutls_x509_crt_init(&x509_cert);

    /* convert the given DER or PEM encoded Certificate to the native
       gnutls_x509_crt_t format */
    gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

    size=sizeof(certbuf);
    rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                       0, /* the first and only one */
                                       FALSE,
                                       certbuf,
                                       &size);
    if(rc) {
        infof(data, "error fetching CN from cert:%s\n",
              gnutls_strerror(rc));
    }

    /* This function will check if the given certificate's subject matches the
       given hostname. This is a basic implementation of the matching described
       in RFC2818 (HTTPS), which takes into account wildcards, and the subject
       alternative name PKIX extension. Returns non zero on success, and zero on
       failure. */
    rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);

    if(!rc) {
        if (data->set.ssl.verifyhost > 1) {
            failf(data, "SSL: certificate subject name (%s) does not match "
                  "target host name '%s'", certbuf, conn->host.dispname);
            gnutls_x509_crt_deinit(x509_cert);
            return CURLE_SSL_PEER_CERTIFICATE;
        }
        else
            infof(data, "\t common name: %s (does not match '%s')\n",
                  certbuf, conn->host.dispname);
    }
    else
        infof(data, "\t common name: %s (matched)\n", certbuf);

    /* Show:

    - ciphers used
    - subject
    - start date
    - expire date
    - common name
    - issuer

    */

    /* public key algorithm's parameters */
    algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
    infof(data, "\t certificate public key: %s\n",
          gnutls_pk_algorithm_get_name(algo));

    /* version of the X.509 certificate. */
    infof(data, "\t certificate version: #%d\n",
          gnutls_x509_crt_get_version(x509_cert));


    size = sizeof(certbuf);
    gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
    infof(data, "\t subject: %s\n", certbuf);

    clock = gnutls_x509_crt_get_activation_time(x509_cert);
    showtime(data, "start date", clock);

    clock = gnutls_x509_crt_get_expiration_time(x509_cert);
    showtime(data, "expire date", clock);

    size = sizeof(certbuf);
    gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
    infof(data, "\t issuer: %s\n", certbuf);

    gnutls_x509_crt_deinit(x509_cert);

    /* compression algorithm (if any) */
    ptr = gnutls_compression_get_name(gnutls_compression_get(session));
    /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
    infof(data, "\t compression: %s\n", ptr);

    /* the name of the cipher used. ie 3DES. */
    ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
    infof(data, "\t cipher: %s\n", ptr);

    /* the MAC algorithms name. ie SHA1 */
    ptr = gnutls_mac_get_name(gnutls_mac_get(session));
    infof(data, "\t MAC: %s\n", ptr);

    if(!ssl_sessionid) {
        /* this session was not previously in the cache, add it now */

        /* get the session ID data size */
        gnutls_session_get_data(session, NULL, &ssl_idsize);
        ssl_sessionid = malloc(ssl_idsize); /* get a buffer for it */

        if(ssl_sessionid) {
            /* extract session ID to the allocated buffer */
            gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize);

            /* store this session id */
            return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize);
        }
    }

    return CURLE_OK;
}
示例#15
0
文件: tls.c 项目: maximerobin/Ufwi
unsigned int check_nuauth_cert_dn(gnutls_session *tls_session)
{
	/* we check that dn provided in nuauth certificate is valid */
	char dn[128];
	size_t size;
	int ret;

#if 0
	unsigned int algo, bits;
	time_t expiration_time,
	       activation_time;
#endif
	const gnutls_datum *cert_list;
	unsigned int cert_list_size = 0;
	gnutls_x509_crt cert;

	/* This function only works for X.509 certificates.
	*/
	if (gnutls_certificate_type_get(*tls_session) != GNUTLS_CRT_X509)
		return 0;

	cert_list = gnutls_certificate_get_peers(*tls_session, &cert_list_size);
	if (cert_list_size == 0) {
		log_area_printf(DEBUG_AREA_MAIN, DEBUG_LEVEL_WARNING,
				"TLS: cannot get the peer certificate");
		return 1;
	}

	/* we only print information about the first certificate */
	ret = gnutls_x509_crt_init(&cert);
	if (ret != 0) {
		log_area_printf	(DEBUG_AREA_MAIN, DEBUG_LEVEL_WARNING,
				"TLS: cannot init x509 cert: %s",
				gnutls_strerror(ret));
		return 0;
	}

	ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
	if (ret != 0) {
		log_area_printf
			(DEBUG_AREA_MAIN, DEBUG_LEVEL_WARNING,
			 "TLS: cannot import x509 cert: %s",
			 gnutls_strerror(ret));
		return 0;
	}

	/* TODO: verify date */
#if 0
	expiration_time = gnutls_x509_crt_get_expiration_time(cert);
	activation_time = gnutls_x509_crt_get_activation_time(cert);

	/* Extract some of the public key algorithm's parameters */
	algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
#endif
	size = sizeof(dn);
	ret = gnutls_x509_crt_get_dn(cert, dn, &size);
	if (ret != 0) {
		log_area_printf (DEBUG_AREA_MAIN, DEBUG_LEVEL_WARNING,
			 "TLS: cannot copy x509 cert name into buffer: %s",
			 gnutls_strerror(ret));
		return 0;
	}
	dn[sizeof(dn)-1] = 0;
	if (strcmp(dn, nuauth_cert_dn)) {
		log_area_printf (DEBUG_AREA_MAIN, DEBUG_LEVEL_WARNING,
			 "TLS: bad certificate DN received from nuauth server: %s",
			 dn);
		return 0;
	}
	return 1;
}
示例#16
0
文件: starttls.c 项目: Jactry/shishi
/* This function will print information about this session's peer
 * certificate. */
static void
logcertinfo (gnutls_session_t session)
{
  time_t now = time (NULL);
  const gnutls_datum_t *cert_list;
  unsigned cert_list_size = 0;
  gnutls_x509_crt_t cert;
  size_t i;
  int rc;

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
  if (!cert_list)
    return;

  rc = gnutls_x509_crt_init (&cert);
  if (rc < 0)
    {
      syslog (LOG_ERR | LOG_DAEMON, "TLS xci failed (%d): %s",
	      rc, gnutls_strerror (rc));
      return;
    }

  if (gnutls_certificate_type_get (session) == GNUTLS_CRT_X509)
    for (i = 0; i < cert_list_size; i++)
      {
	time_t expiration_time, activation_time;
	char *expiration_time_str = NULL, *activation_time_str = NULL;
	unsigned char *serial = NULL, *serialhex = NULL;
	char *issuer = NULL, *subject = NULL;
	size_t seriallen, issuerlen, subjectlen;
	unsigned char md5fingerprint[16], md5fingerprinthex[3 * 16 + 1];
	size_t md5fingerprintlen;
	int algo;
	unsigned bits;
	const char *keytype, *validity;

	rc = gnutls_x509_crt_import (cert, &cert_list[i],
				     GNUTLS_X509_FMT_DER);
	if (rc < 0)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xci[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	md5fingerprintlen = sizeof (md5fingerprint);
	rc = gnutls_fingerprint (GNUTLS_DIG_MD5, &cert_list[i],
				 md5fingerprint, &md5fingerprintlen);
	if (rc != GNUTLS_E_SUCCESS)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS f[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	for (i = 0; i < md5fingerprintlen; i++)
	  sprintf ((char *) &md5fingerprinthex[3 * i], "%.2x:",
		   md5fingerprint[i]);

	expiration_time = gnutls_x509_crt_get_expiration_time (cert);
	if (expiration_time == (time_t) - 1)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcget[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	activation_time = gnutls_x509_crt_get_activation_time (cert);
	if (expiration_time == (time_t) - 1)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgat[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	expiration_time_str = xstrdup (ctime (&expiration_time));
	if (expiration_time_str[strlen (expiration_time_str) - 1] == '\n')
	  expiration_time_str[strlen (expiration_time_str) - 1] = '\0';

	activation_time_str = xstrdup (ctime (&activation_time));
	if (activation_time_str[strlen (activation_time_str) - 1] == '\n')
	  activation_time_str[strlen (activation_time_str) - 1] = '\0';

	rc = gnutls_x509_crt_get_dn (cert, NULL, &subjectlen);
	if (rc != GNUTLS_E_SUCCESS && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgd[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }
	subject = xmalloc (++subjectlen);
	rc = gnutls_x509_crt_get_dn (cert, subject, &subjectlen);
	if (rc != GNUTLS_E_SUCCESS)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgd2[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	rc = gnutls_x509_crt_get_issuer_dn (cert, NULL, &issuerlen);
	if (rc != GNUTLS_E_SUCCESS && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgid[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }
	issuer = xmalloc (++issuerlen);
	rc = gnutls_x509_crt_get_issuer_dn (cert, issuer, &issuerlen);
	if (rc != GNUTLS_E_SUCCESS)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgid2[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	seriallen = 0;
	rc = gnutls_x509_crt_get_serial (cert, NULL, &seriallen);
	if (rc != GNUTLS_E_SUCCESS && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgs[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }
	serial = xmalloc (seriallen);
	rc = gnutls_x509_crt_get_serial (cert, serial, &seriallen);
	if (rc != GNUTLS_E_SUCCESS)
	  {
	    syslog (LOG_ERR | LOG_DAEMON, "TLS xcgs2[%zu] failed (%d): %s",
		    i, rc, gnutls_strerror (rc));
	    goto cleanup;
	  }

	serialhex = xmalloc (2 * seriallen + 1);
	for (i = 0; i < seriallen; i++)
	  sprintf ((char *) &serialhex[2 * i], "%.2x", serial[i]);

	algo = gnutls_x509_crt_get_pk_algorithm (cert, &bits);
	if (algo == GNUTLS_PK_RSA)
	  keytype = "RSA modulus";
	else if (algo == GNUTLS_PK_DSA)
	  keytype = "DSA exponent";
	else
	  keytype = "UNKNOWN";

	if (expiration_time < now)
	  validity = "EXPIRED";
	else if (activation_time > now)
	  validity = "NOT YET ACTIVATED";
	else
	  validity = "valid";

	/* This message can arguably belong to LOG_AUTH.  */
	syslog (LOG_INFO, "TLS client certificate `%s', issued by `%s', "
		"serial number `%s', MD5 fingerprint `%s', activated `%s', "
		"expires `%s', version #%d, key %s %d bits, currently %s",
		subject, issuer, serialhex, md5fingerprinthex,
		activation_time_str, expiration_time_str,
		gnutls_x509_crt_get_version (cert), keytype, bits, validity);

      cleanup:
	free (serialhex);
	free (serial);
	free (expiration_time_str);
	free (activation_time_str);
	free (issuer);
	free (subject);
      }

  gnutls_x509_crt_deinit (cert);

  {
    unsigned int status;

    /* Accept default syslog facility for these errors.
     * They are clearly relevant as audit traces.  */
    rc = gnutls_certificate_verify_peers2 (session, &status);
    if (rc != GNUTLS_E_SUCCESS)
      syslog (LOG_ERR, "TLS client certificate failed (%d): %s",
	      rc, gnutls_strerror (rc));
    if (status != 0)
      syslog (LOG_ERR, "TLS client certificate verify failure (%d)",
	      status);
  }
}
示例#17
0
void __certificate_properties_fill_cert_subjectPublicKeyInfo (GtkTreeStore *store,
        GtkTreeIter *parent,
        gnutls_x509_crt_t *certificate)
{
    int result;
    unsigned int bits = 0;
    const gchar * name = NULL;
    GtkTreeIter j;
    GtkTreeIter k;
    GtkTreeIter l;
    gchar *value;
    GtkTreeIter m;
    gnutls_datum_t modulus, publicExponent;
    gnutls_datum_t p, q, g, y;

    result = gnutls_x509_crt_get_pk_algorithm(*certificate, &bits);
    name = gnutls_pk_algorithm_get_name(result);

    gtk_tree_store_append(store, &j, parent);
    gtk_tree_store_set(store, &j, CERTIFICATE_PROPERTIES_COL_NAME, _("Subject Public Key Info"), -1);

    gtk_tree_store_append(store, &k, &j);
    gtk_tree_store_set(store, &k, CERTIFICATE_PROPERTIES_COL_NAME, _("Algorithm"), -1);

    gtk_tree_store_append(store, &l, &k);
    gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Algorithm"), CERTIFICATE_PROPERTIES_COL_VALUE, name, -1);

    switch (result) {
    case GNUTLS_PK_RSA:
        gtk_tree_store_append(store, &l, &k);
        gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Parameters"), CERTIFICATE_PROPERTIES_COL_VALUE, _("(unknown)"), -1);
        gtk_tree_store_append(store, &k, &j);
        gtk_tree_store_set(store, &k, CERTIFICATE_PROPERTIES_COL_NAME, _("RSA PublicKey"), -1);
        result = gnutls_x509_crt_get_pk_rsa_raw(*certificate, &modulus, &publicExponent);
        if (result < 0) {
            fprintf(stderr, "Error: (%s,%d): %s\n", __FILE__, __LINE__, gnutls_strerror(result));
            break;
        }
        value = __certificate_properties_dump_raw_data(modulus.data, modulus.size);
        gnutls_free(modulus.data);

        gtk_tree_store_append(store, &l, &k);
        gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Modulus"), CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);

        value = __certificate_properties_dump_raw_data(publicExponent.data, publicExponent.size);
        gnutls_free(publicExponent.data);
        gtk_tree_store_append(store, &l, &k);
        gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Public Exponent"), CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);
        break;
    case GNUTLS_PK_DSA:
        result = gnutls_x509_crt_get_pk_dsa_raw(*certificate, &p, &q, &g, &y);
        if (result < 0) {
            fprintf(stderr, "Error: (%s,%d): %s\n", __FILE__, __LINE__, gnutls_strerror(result));
            break;
        }
        gtk_tree_store_append(store, &l, &k);
        gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Parameters"), -1);

        value = __certificate_properties_dump_raw_data(p.data, p.size);
        gnutls_free(p.data);
        gtk_tree_store_append(store, &m, &l);
        gtk_tree_store_set(store, &m, CERTIFICATE_PROPERTIES_COL_NAME, "p", CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);

        value = __certificate_properties_dump_raw_data(q.data, q.size);
        gnutls_free(q.data);
        gtk_tree_store_append(store, &m, &l);
        gtk_tree_store_set(store, &m, CERTIFICATE_PROPERTIES_COL_NAME, "p", CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);

        value = __certificate_properties_dump_raw_data(g.data, g.size);
        gnutls_free(g.data);
        gtk_tree_store_append(store, &m, &l);
        gtk_tree_store_set(store, &m, CERTIFICATE_PROPERTIES_COL_NAME, "g", CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);

        value = __certificate_properties_dump_raw_data(y.data, y.size);
        gnutls_free(y.data);
        gtk_tree_store_append(store, &k, &j);
        gtk_tree_store_set(store, &k, CERTIFICATE_PROPERTIES_COL_NAME, _("DSA PublicKey"), CERTIFICATE_PROPERTIES_COL_VALUE, value, -1);
        g_free(value);
        break;
    default:
        gtk_tree_store_append(store, &l, &k);
        gtk_tree_store_set(store, &l, CERTIFICATE_PROPERTIES_COL_NAME, _("Parameters"), CERTIFICATE_PROPERTIES_COL_VALUE, _("(unknown)"), -1);
        gtk_tree_store_append(store, &k, &j);
        gtk_tree_store_set(store, &k, CERTIFICATE_PROPERTIES_COL_NAME, _("Subject Public Key"), CERTIFICATE_PROPERTIES_COL_VALUE, _("(unknown)"), -1);
        break;
    }
}
示例#18
0
/* Like above but it accepts a parsed certificate instead.
 */
int
_gnutls_x509_crt_to_gcert (gnutls_cert * gcert,
			   gnutls_x509_crt_t cert, unsigned int flags)
{
  int ret = 0;

  memset (gcert, 0, sizeof (gnutls_cert));
  gcert->cert_type = GNUTLS_CRT_X509;

  if (!(flags & CERT_NO_COPY))
    {
#define SMALL_DER 512
      opaque *der;
      size_t der_size = SMALL_DER;

      /* initially allocate a bogus size, just in case the certificate
       * fits in it. That way we minimize the DER encodings performed.
       */
      der = gnutls_malloc (SMALL_DER);
      if (der == NULL)
	{
	  gnutls_assert ();
	  return GNUTLS_E_MEMORY_ERROR;
	}

      ret =
	gnutls_x509_crt_export (cert, GNUTLS_X509_FMT_DER, der, &der_size);
      if (ret < 0 && ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
	{
	  gnutls_assert ();
	  gnutls_free (der);
	  return ret;
	}

      if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
	{
	  der = gnutls_realloc (der, der_size);
	  if (der == NULL)
	    {
	      gnutls_assert ();
	      return GNUTLS_E_MEMORY_ERROR;
	    }

	  ret =
	    gnutls_x509_crt_export (cert, GNUTLS_X509_FMT_DER, der,
				    &der_size);
	  if (ret < 0)
	    {
	      gnutls_assert ();
	      gnutls_free (der);
	      return ret;
	    }
	}

      gcert->raw.data = der;
      gcert->raw.size = der_size;
    }
  else
    /* now we have 0 or a bitwise or of things to decode */
    flags ^= CERT_NO_COPY;


  if (flags & CERT_ONLY_EXTENSIONS || flags == 0)
    {
      gnutls_x509_crt_get_key_usage (cert, &gcert->key_usage, NULL);
      gcert->version = gnutls_x509_crt_get_version (cert);
    }
  gcert->subject_pk_algorithm = gnutls_x509_crt_get_pk_algorithm (cert, NULL);

  if (flags & CERT_ONLY_PUBKEY || flags == 0)
    {
      gcert->params_size = MAX_PUBLIC_PARAMS_SIZE;
      ret =
	_gnutls_x509_crt_get_mpis (cert, gcert->params, &gcert->params_size);
      if (ret < 0)
	{
	  gnutls_assert ();
	  return ret;
	}
    }

  return 0;

}
示例#19
0
int CTlsSocket::VerifyCertificate()
{
	if (m_tlsState != handshake)
	{
		m_pOwner->LogMessage(Debug_Warning, _T("VerifyCertificate called at wrong time"));
		return FZ_REPLY_ERROR;
	}

	m_tlsState = verifycert;

	if (gnutls_certificate_type_get(m_session) != GNUTLS_CRT_X509)
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("Unsupported certificate type"));
		Failure(0);
		return FZ_REPLY_ERROR;
	}

	unsigned int cert_list_size;
	const gnutls_datum_t* const cert_list = gnutls_certificate_get_peers(m_session, &cert_list_size);
	if (!cert_list || !cert_list_size)
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("gnutls_certificate_get_peers returned no certificates"));
		Failure(0);
		return FZ_REPLY_ERROR;
	}

	if (m_implicitTrustedCert.data)
	{
		if (m_implicitTrustedCert.size != cert_list[0].size ||
			memcmp(m_implicitTrustedCert.data, cert_list[0].data, cert_list[0].size))
		{
			m_pOwner->LogMessage(::Error, _("Primary connection and data connection certificates don't match."));
			Failure(0);
			return FZ_REPLY_ERROR;
		}
		
		TrustCurrentCert(true);
		return FZ_REPLY_OK;
	}

	gnutls_x509_crt_t cert;
	if (gnutls_x509_crt_init(&cert))
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("gnutls_x509_crt_init failed"));
		Failure(0);
		return FZ_REPLY_ERROR;
	}

	if (gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER))
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("gnutls_x509_crt_import failed"));
		Failure(0);
		gnutls_x509_crt_deinit(cert);
		return FZ_REPLY_ERROR;
	}

	wxDateTime expirationTime = gnutls_x509_crt_get_expiration_time(cert);
	wxDateTime activationTime = gnutls_x509_crt_get_activation_time(cert);

	// Get the serial number of the certificate
	unsigned char buffer[40];
	size_t size = sizeof(buffer);
	int res = gnutls_x509_crt_get_serial(cert, buffer, &size);

	wxString serial = bin2hex(buffer, size);

	unsigned int bits;
	int algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);

	wxString algoName;
	const char* pAlgo = gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)algo);
	if (pAlgo)
		algoName = wxString(pAlgo, wxConvUTF8);

	//int version = gnutls_x509_crt_get_version(cert);
	
	wxString subject, issuer;

	size = 0;
	res = gnutls_x509_crt_get_dn(cert, 0, &size);
	if (size)
	{
		char* dn = new char[size + 1];
		dn[size] = 0;
		if (!(res = gnutls_x509_crt_get_dn(cert, dn, &size)))
		{
			dn[size] = 0;
			subject = wxString(dn, wxConvUTF8);
		}
		else
			LogError(res);
		delete [] dn;
	}
	else
		LogError(res);
	if (subject == _T(""))
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("gnutls_x509_get_dn failed"));
		Failure(0);
		gnutls_x509_crt_deinit(cert);
		return FZ_REPLY_ERROR;
	}

	size = 0;
	res = gnutls_x509_crt_get_issuer_dn(cert, 0, &size);
	if (size)
	{
		char* dn = new char[size + 1];
		dn[size] = 0;
		if (!(res = gnutls_x509_crt_get_issuer_dn(cert, dn, &size)))
		{
			dn[size] = 0;
			issuer = wxString(dn, wxConvUTF8);
		}
		else
			LogError(res);
		delete [] dn;
	}
	else
		LogError(res);
	if (issuer == _T(""))
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("gnutls_x509_get_issuer_dn failed"));
		Failure(0);
		gnutls_x509_crt_deinit(cert);
		return FZ_REPLY_ERROR;
	}

	wxString fingerprint_md5;
	wxString fingerprint_sha1;

	unsigned char digest[100];
	size = sizeof(digest) - 1;
	if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &size))
	{
		digest[size] = 0;
		fingerprint_md5 = bin2hex(digest, size);
	}
	size = sizeof(digest) - 1;
	if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, digest, &size))
	{
		digest[size] = 0;
		fingerprint_sha1 = bin2hex(digest, size);
	}

	CCertificateNotification *pNotification = new CCertificateNotification(
		m_pOwner->GetCurrentServer()->GetHost(),
		m_pOwner->GetCurrentServer()->GetPort(),
		cert_list->data, cert_list->size,
		activationTime, expirationTime,
		serial,
		algoName, bits,
		fingerprint_md5,
		fingerprint_sha1,
		subject,
		issuer);

	pNotification->requestNumber = m_pOwner->GetEngine()->GetNextAsyncRequestNumber();
	
	m_pOwner->GetEngine()->AddNotification(pNotification);

	m_pOwner->LogMessage(Status, _("Verifying certificate..."));

	return FZ_REPLY_WOULDBLOCK;
}
示例#20
0
int CTlsSocket::VerifyCertificate()
{
	if (m_tlsState != handshake)
	{
		m_pOwner->LogMessage(::Debug_Warning, _T("VerifyCertificate called at wrong time"));
		return FZ_REPLY_ERROR;
	}

	m_tlsState = verifycert;

	if (gnutls_certificate_type_get(m_session) != GNUTLS_CRT_X509)
	{
		m_pOwner->LogMessage(::Error, _("Unsupported certificate type"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	unsigned int status = 0;
	if (gnutls_certificate_verify_peers2(m_session, &status) < 0)
	{
		m_pOwner->LogMessage(::Error, _("Failed to verify peer certificate"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	if (status & GNUTLS_CERT_REVOKED)
	{
		m_pOwner->LogMessage(::Error, _("Beware! Certificate has been revoked"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	if (status & GNUTLS_CERT_SIGNER_NOT_CA)
	{
		m_pOwner->LogMessage(::Error, _("Incomplete chain, top certificate is not self-signed certificate authority certificate"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	if (m_require_root_trust && status & GNUTLS_CERT_SIGNER_NOT_FOUND)
	{
		m_pOwner->LogMessage(::Error, _("Root certificate is not trusted"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	unsigned int cert_list_size;
	const gnutls_datum_t* cert_list = gnutls_certificate_get_peers(m_session, &cert_list_size);
	if (!cert_list || !cert_list_size)
	{
		m_pOwner->LogMessage(::Error, _("gnutls_certificate_get_peers returned no certificates"));
		Failure(0, ECONNABORTED);
		return FZ_REPLY_ERROR;
	}

	if (m_implicitTrustedCert.data)
	{
		if (m_implicitTrustedCert.size != cert_list[0].size ||
			memcmp(m_implicitTrustedCert.data, cert_list[0].data, cert_list[0].size))
		{
			m_pOwner->LogMessage(::Error, _("Primary connection and data connection certificates don't match."));
			Failure(0, ECONNABORTED);
			return FZ_REPLY_ERROR;
		}

		TrustCurrentCert(true);

		if (m_tlsState != conn)
			return FZ_REPLY_ERROR;
		return FZ_REPLY_OK;
	}

	std::vector<CCertificate> certificates;
	for (unsigned int i = 0; i < cert_list_size; i++)
	{
		gnutls_x509_crt_t cert;
		if (gnutls_x509_crt_init(&cert))
		{
			m_pOwner->LogMessage(::Error, _("Could not initialize structure for peer certificates, gnutls_x509_crt_init failed"));
			Failure(0, ECONNABORTED);
			return FZ_REPLY_ERROR;
		}

		if (gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER))
		{
			m_pOwner->LogMessage(::Error, _("Could not import peer certificates, gnutls_x509_crt_import failed"));
			Failure(0, ECONNABORTED);
			gnutls_x509_crt_deinit(cert);
			return FZ_REPLY_ERROR;
		}

		wxDateTime expirationTime = gnutls_x509_crt_get_expiration_time(cert);
		wxDateTime activationTime = gnutls_x509_crt_get_activation_time(cert);

		// Get the serial number of the certificate
		unsigned char buffer[40];
		size_t size = sizeof(buffer);
		int res = gnutls_x509_crt_get_serial(cert, buffer, &size);

		wxString serial = bin2hex(buffer, size);

		unsigned int bits;
		int algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);

		wxString algoName;
		const char* pAlgo = gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)algo);
		if (pAlgo)
			algoName = wxString(pAlgo, wxConvUTF8);

		//int version = gnutls_x509_crt_get_version(cert);

		wxString subject, issuer;

		size = 0;
		res = gnutls_x509_crt_get_dn(cert, 0, &size);
		if (size)
		{
			char* dn = new char[size + 1];
			dn[size] = 0;
			if (!(res = gnutls_x509_crt_get_dn(cert, dn, &size)))
			{
				dn[size] = 0;
				subject = wxString(dn, wxConvUTF8);
			}
			else
				LogError(res);
			delete [] dn;
		}
		else
			LogError(res);
		if (subject == _T(""))
		{
			m_pOwner->LogMessage(::Error, _("Could not get distinguished name of certificate subject, gnutls_x509_get_dn failed"));
			Failure(0, ECONNABORTED);
			gnutls_x509_crt_deinit(cert);
			return FZ_REPLY_ERROR;
		}

		size = 0;
		res = gnutls_x509_crt_get_issuer_dn(cert, 0, &size);
		if (size)
		{
			char* dn = new char[++size + 1];
			dn[size] = 0;
			if (!(res = gnutls_x509_crt_get_issuer_dn(cert, dn, &size)))
			{
				dn[size] = 0;
				issuer = wxString(dn, wxConvUTF8);
			}
			else
				LogError(res);
			delete [] dn;
		}
		else
			LogError(res);
		if (issuer == _T(""))
		{
			m_pOwner->LogMessage(::Error, _("Could not get distinguished name of certificate issuer, gnutls_x509_get_issuer_dn failed"));
			Failure(0, ECONNABORTED);
			gnutls_x509_crt_deinit(cert);
			return FZ_REPLY_ERROR;
		}

		wxString fingerprint_md5;
		wxString fingerprint_sha1;

		unsigned char digest[100];
		size = sizeof(digest) - 1;
		if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &size))
		{
			digest[size] = 0;
			fingerprint_md5 = bin2hex(digest, size);
		}
		size = sizeof(digest) - 1;
		if (!gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, digest, &size))
		{
			digest[size] = 0;
			fingerprint_sha1 = bin2hex(digest, size);
		}

		certificates.push_back(CCertificate(
			cert_list->data, cert_list->size,
			activationTime, expirationTime,
			serial,
			algoName, bits,
			fingerprint_md5,
			fingerprint_sha1,
			subject,
			issuer));

		cert_list++;
	}

	CCertificateNotification *pNotification = new CCertificateNotification(
		m_pOwner->GetCurrentServer()->GetHost(),
		m_pOwner->GetCurrentServer()->GetPort(),
		GetCipherName(),
		GetMacName(),
		certificates);

	m_pOwner->SendAsyncRequest(pNotification);

	m_pOwner->LogMessage(Status, _("Verifying certificate..."));

	return FZ_REPLY_WOULDBLOCK;
}
示例#21
0
         void gtlsGeneric::logX509CertificateInfo(LogWrapperType _logwrapper,
                                                  gnutls_session_t _session)
         {
            char serial[40];
            char dn[128];
            size_t size;
            unsigned int algo, bits;
            time_t expiration_time, activation_time;
            const gnutls_datum_t *cert_list;
            int cert_list_size = 0;
            gnutls_x509_crt_t cert;

            if (gnutls_certificate_type_get (_session) != GNUTLS_CRT_X509)
               {
                  BTG_NOTICE(_logwrapper, "Not a x509 certificate, abort.");
                  return;
               }

            cert_list = gnutls_certificate_get_peers(_session, reinterpret_cast<unsigned int*>(&cert_list_size));

            BTG_NOTICE(_logwrapper, "Peer provided " << cert_list_size << " certificates.");

            if (cert_list_size > 0)
               {

                  /* we only print information about the first certificate.
                   */
                  gnutls_x509_crt_init (&cert);

                  gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);

                  BTG_NOTICE(_logwrapper, "Certificate info:");

                  expiration_time = gnutls_x509_crt_get_expiration_time (cert);
                  activation_time = gnutls_x509_crt_get_activation_time (cert);

                  BTG_NOTICE(_logwrapper, "   Certificate is valid since: " << ctime (&activation_time));
                  BTG_NOTICE(_logwrapper, "   Certificate expires: " << ctime (&expiration_time));

                  /* Print the serial number of the certificate.
                   */
                  size = sizeof (serial);
                  gnutls_x509_crt_get_serial (cert, serial, &size);

                  size = sizeof (serial);
                  BTG_NOTICE(_logwrapper, "   Certificate serial number: " << bin2hex(serial, size));

                  /* Extract some of the public key algorithm's parameters
                   */
                  algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);

                  BTG_NOTICE(_logwrapper, "Certificate public key: " << gnutls_pk_algorithm_get_name(static_cast<gnutls_pk_algorithm_t>(algo)));

                  /* Print the version of the X.509
                   * certificate.
                   */
                  BTG_NOTICE(_logwrapper, "   Certificate version: #" << gnutls_x509_crt_get_version(cert));

                  size = sizeof(dn);
                  gnutls_x509_crt_get_dn(cert, dn, &size);
                  BTG_NOTICE(_logwrapper, "   DN: " << dn);

                  size = sizeof(dn);
                  gnutls_x509_crt_get_issuer_dn (cert, dn, &size);
                  BTG_NOTICE(_logwrapper, "   Issuer's DN: " << dn);

                  gnutls_x509_crt_deinit(cert);
               }
         }
示例#22
0
文件: gtls.c 项目: CopySpotter/curl
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum_t *chainp;
  unsigned int verify_status = 0;
  gnutls_x509_crt_t x509_cert, x509_issuer;
  gnutls_datum_t issuerp;
  char certbuf[256] = ""; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session_t session = conn->ssl[sockindex].session;
  int rc;
  bool incache;
  void *ssl_sessionid;
#ifdef HAS_ALPN
  gnutls_datum_t proto;
#endif
  CURLcode result = CURLE_OK;

  gnutls_protocol_t version = gnutls_protocol_get_version(session);

  /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */
  ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),
                                     gnutls_cipher_get(session),
                                     gnutls_mac_get(session));

  infof(data, "SSL connection using %s / %s\n",
        gnutls_protocol_get_name(version), ptr);

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.certinfo && chainp) {
    unsigned int i;

    result = Curl_ssl_init_certinfo(data, cert_list_size);
    if(result)
      return result;

    for(i = 0; i < cert_list_size; i++) {
      const char *beg = (const char *) chainp[i].data;
      const char *end = beg + chainp[i].size;

      result = Curl_extract_certinfo(conn, i, beg, end);
      if(result)
        return result;
    }
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else
    infof(data, "\t server certificate verification SKIPPED\n");

#ifdef HAS_OCSP
  if(data->set.ssl.verifystatus) {
    if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {
      gnutls_datum_t status_request;
      gnutls_ocsp_resp_t ocsp_resp;

      gnutls_ocsp_cert_status_t status;
      gnutls_x509_crl_reason_t reason;

      rc = gnutls_ocsp_status_request_get(session, &status_request);

      infof(data, "\t server certificate status verification FAILED\n");

      if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
        failf(data, "No OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      if(rc < 0) {
        failf(data, "Invalid OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      gnutls_ocsp_resp_init(&ocsp_resp);

      rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);
      if(rc < 0) {
        failf(data, "Invalid OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      rc = gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,
                                       &status, NULL, NULL, NULL, &reason);

      switch(status) {
      case GNUTLS_OCSP_CERT_GOOD:
        break;

      case GNUTLS_OCSP_CERT_REVOKED: {
        const char *crl_reason;

        switch(reason) {
          default:
          case GNUTLS_X509_CRLREASON_UNSPECIFIED:
            crl_reason = "unspecified reason";
            break;

          case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:
            crl_reason = "private key compromised";
            break;

          case GNUTLS_X509_CRLREASON_CACOMPROMISE:
            crl_reason = "CA compromised";
            break;

          case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:
            crl_reason = "affiliation has changed";
            break;

          case GNUTLS_X509_CRLREASON_SUPERSEDED:
            crl_reason = "certificate superseded";
            break;

          case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:
            crl_reason = "operation has ceased";
            break;

          case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:
            crl_reason = "certificate is on hold";
            break;

          case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:
            crl_reason = "will be removed from delta CRL";
            break;

          case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:
            crl_reason = "privilege withdrawn";
            break;

          case GNUTLS_X509_CRLREASON_AACOMPROMISE:
            crl_reason = "AA compromised";
            break;
        }

        failf(data, "Server certificate was revoked: %s", crl_reason);
        break;
      }

      default:
      case GNUTLS_OCSP_CERT_UNKNOWN:
        failf(data, "Server certificate status is unknown");
        break;
      }

      gnutls_ocsp_resp_deinit(ocsp_resp);

      return CURLE_SSL_INVALIDCERTSTATUS;
    }
    else
      infof(data, "\t server certificate status verification OK\n");
  }
  else
    infof(data, "\t server certificate status verification SKIPPED\n");
#endif

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  if(chainp)
    /* convert the given DER or PEM encoded Certificate to the native
       gnutls_x509_crt_t format */
    gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);
    gnutls_x509_crt_deinit(x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data, "\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
#if GNUTLS_VERSION_NUMBER < 0x030306
  /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
     addresses. */
  if(!rc) {
#ifdef ENABLE_IPV6
    #define use_addr in6_addr
#else
    #define use_addr in_addr
#endif
    unsigned char addrbuf[sizeof(struct use_addr)];
    unsigned char certaddr[sizeof(struct use_addr)];
    size_t addrlen = 0, certaddrlen;
    int i;
    int ret = 0;

    if(Curl_inet_pton(AF_INET, conn->host.name, addrbuf) > 0)
      addrlen = 4;
#ifdef ENABLE_IPV6
    else if(Curl_inet_pton(AF_INET6, conn->host.name, addrbuf) > 0)
      addrlen = 16;
#endif

    if(addrlen) {
      for(i=0; ; i++) {
        certaddrlen = sizeof(certaddr);
        ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
                                                   &certaddrlen, NULL);
        /* If this happens, it wasn't an IP address. */
        if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
          continue;
        if(ret < 0)
          break;
        if(ret != GNUTLS_SAN_IPADDRESS)
          continue;
        if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
          rc = 1;
          break;
        }
      }
    }
  }
#endif
  if(!rc) {
    if(data->set.ssl.verifyhost) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert expiration date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate expiration date verify FAILED\n");
  }
  else {
    if(certclock < time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate expiration date has passed.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate expiration date FAILED\n");
    }
    else
      infof(data, "\t server certificate expiration date OK\n");
  }

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert activation date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate activation date verify FAILED\n");
  }
  else {
    if(certclock > time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate not activated yet.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate activation date FAILED\n");
    }
    else
      infof(data, "\t server certificate activation date OK\n");
  }

  ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  if(ptr) {
    result = pkp_pin_peer_pubkey(data, x509_cert, ptr);
    if(result != CURLE_OK) {
      failf(data, "SSL: public key does not match pinned public key!");
      gnutls_x509_crt_deinit(x509_cert);
      return result;
    }
  }

  /* Show:

  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

#ifdef HAS_ALPN
  if(data->set.ssl_enable_alpn) {
    rc = gnutls_alpn_get_selected_protocol(session, &proto);
    if(rc == 0) {
      infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
          proto.data);

#ifdef USE_NGHTTP2
      if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
         !memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
                 NGHTTP2_PROTO_VERSION_ID_LEN)) {
        conn->negnpn = CURL_HTTP_VERSION_2;
      }
      else
#endif
      if(proto.size == ALPN_HTTP_1_1_LENGTH &&
         !memcmp(ALPN_HTTP_1_1, proto.data, ALPN_HTTP_1_1_LENGTH)) {
        conn->negnpn = CURL_HTTP_VERSION_1_1;
      }
    }
    else
      infof(data, "ALPN, server did not agree to a protocol\n");
  }
#endif

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize = 0;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
示例#23
0
/* This function will print information about this session's peer
 * certificate.
 */
void
print_x509_certificate_info (gnutls_session_t session)
{
  char serial[40];
  char dn[256];
  size_t size;
  unsigned int algo, bits;
  time_t expiration_time, activation_time;
  const gnutls_datum_t *cert_list;
  unsigned int cert_list_size = 0;
  gnutls_x509_crt_t cert;
  gnutls_datum_t cinfo;

  /* This function only works for X.509 certificates.
   */
  if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
    return;

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);

  printf ("Peer provided %d certificates.\n", cert_list_size);

  if (cert_list_size > 0)
    {
      int ret;

      /* we only print information about the first certificate.
       */
      gnutls_x509_crt_init (&cert);

      gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER);

      printf ("Certificate info:\n");

      /* This is the preferred way of printing short information about
         a certificate. */

      ret = gnutls_x509_crt_print (cert, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
      if (ret == 0)
	{
	  printf ("\t%s\n", cinfo.data);
	  gnutls_free (cinfo.data);
	}

      /* If you want to extract fields manually for some other reason,
         below are popular example calls. */

      expiration_time = gnutls_x509_crt_get_expiration_time (cert);
      activation_time = gnutls_x509_crt_get_activation_time (cert);

      printf ("\tCertificate is valid since: %s", ctime (&activation_time));
      printf ("\tCertificate expires: %s", ctime (&expiration_time));

      /* Print the serial number of the certificate.
       */
      size = sizeof (serial);
      gnutls_x509_crt_get_serial (cert, serial, &size);

      printf ("\tCertificate serial number: %s\n", bin2hex (serial, size));

      /* Extract some of the public key algorithm's parameters
       */
      algo = gnutls_x509_crt_get_pk_algorithm (cert, &bits);

      printf ("Certificate public key: %s",
	      gnutls_pk_algorithm_get_name (algo));

      /* Print the version of the X.509
       * certificate.
       */
      printf ("\tCertificate version: #%d\n",
	      gnutls_x509_crt_get_version (cert));

      size = sizeof (dn);
      gnutls_x509_crt_get_dn (cert, dn, &size);
      printf ("\tDN: %s\n", dn);

      size = sizeof (dn);
      gnutls_x509_crt_get_issuer_dn (cert, dn, &size);
      printf ("\tIssuer's DN: %s\n", dn);

      gnutls_x509_crt_deinit (cert);

    }
}
示例#24
0
int
_gnutls_x509_verify_algorithm (gnutls_mac_algorithm_t * hash,
			       const gnutls_datum_t * signature,
			       const gnutls_x509_crt_t issuer)
{
  bigint_t issuer_params[MAX_PUBLIC_PARAMS_SIZE];
  opaque digest[MAX_HASH_SIZE];
  gnutls_datum_t decrypted;
  int issuer_params_size;
  int digest_size;
  int ret, i;

  issuer_params_size = MAX_PUBLIC_PARAMS_SIZE;
  ret =
    _gnutls_x509_crt_get_mpis (issuer, issuer_params, &issuer_params_size);
  if (ret < 0)
    {
      gnutls_assert ();
      return ret;
    }

  switch (gnutls_x509_crt_get_pk_algorithm (issuer, NULL))
    {
    case GNUTLS_PK_DSA:

      if (hash)
	*hash = _gnutls_dsa_q_to_hash (issuer_params[1]);

      ret = 0;
      break;

    case GNUTLS_PK_RSA:

      ret =
	_gnutls_pkcs1_rsa_decrypt (&decrypted, signature,
				   issuer_params, issuer_params_size, 1);


      if (ret < 0)
	{
	  gnutls_assert ();
	  goto cleanup;
	}

      digest_size = sizeof (digest);
      if ((ret =
	   decode_ber_digest_info (&decrypted, hash, digest,
				   &digest_size)) != 0)
	{
	  gnutls_assert ();
	  _gnutls_free_datum (&decrypted);
	  goto cleanup;
	}

      _gnutls_free_datum (&decrypted);
      if (digest_size != _gnutls_hash_get_algo_len (*hash))
	{
	  gnutls_assert ();
	  ret = GNUTLS_E_ASN1_GENERIC_ERROR;
	  goto cleanup;
	}

      ret = 0;
      break;

    default:
      gnutls_assert ();
      ret = GNUTLS_E_INTERNAL_ERROR;
    }

cleanup:
  /* release allocated mpis */
  for (i = 0; i < issuer_params_size; i++)
    {
      _gnutls_mpi_release (&issuer_params[i]);
    }

  return ret;

}