Beispiel #1
0
static char *hash_subject_pubkey_info(X509 *cert)
{
	_cleanup_free_ unsigned char *spki = NULL;
	char *hash = NULL;
	EVP_PKEY *pkey;
	int len;

	pkey = X509_get_pubkey(cert);
	if (!pkey)
		return NULL;

	len = i2d_PUBKEY(pkey, &spki);
	if (len <= 0)
		goto free_pkey;

	hash = cipher_sha256_b64(spki, len);
free_pkey:
	EVP_PKEY_free(pkey);
	return hash;
}
Beispiel #2
0
s32 https_cert_verify_cert(X509 *ca, X509 *cert)
{  
	s32     rv = 0;
	EVP_PKEY *pkey = NULL;

	pkey = X509_get_pubkey(ca);
	if(NULL == pkey)
	{
	    return ERR_HTTPS_CERT_UNABLE_GET_PUBKEY;
	}

	rv = X509_verify(cert, pkey);
	EVP_PKEY_free(pkey);
	if(rv < 0)
	{
	    return ERR_HTTPS_CERT_SIGNATURE_FAILURE;        
	}

	return verify_cert_time_valid(cert);
}
Beispiel #3
0
void *
badge_read_PublicKey_from_X509_cert(const char * filename, int * keylen)

{
	X509 * rc;
	EVP_PKEY * key;

	badge_read_ssl(PEM_read_bio_X509, d2i_X509_bio);

	if (!rc)
		return NULL;

	key = X509_get_pubkey(rc);
	X509_free(rc);

	if (key)
		*keylen = EVP_PKEY_size(key);

	return key;
}
Beispiel #4
0
int main(void)
{
  FILE *fp;
  RSA *pub;
  X509 *crt;
  extern qa_question_t PollardRhoQuestion;
  extern qa_question_t PollardBrentRhoQuestion;

if (!(fp = fopen("pollardrho.crt", "r")))
      return EXIT_FAILURE;

  crt = PEM_read_X509(fp, NULL, 0, NULL);
  pub = X509_get_pubkey(crt)->pkey.rsa;
  if (run_question(&PollardRhoQuestion, crt, pub) < 1)
    return EXIT_FAILURE;
  if (run_question(&PollardBrentRhoQuestion, crt, pub) < 1)
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
Beispiel #5
0
static int
cryptoMagic(X509 *x0, X509 *x1, X509 *x2,
	    const unsigned char *toHashData, int toHashLength,
	    /*XXX const*/ unsigned char *rsaSigData, int rsaSigLen,
	    DataValue *partialDigest)
{
	int rv = 0;
	EVP_PKEY *pk = X509_get_pubkey(x2);
	if (pk) {
		if (pk->type == EVP_PKEY_RSA) {
			RSA *rsa = EVP_PKEY_get1_RSA(pk);
			if (rsa) {
				X509_STORE *store = X509_STORE_new();
				if (store) {
					X509_STORE_CTX ctx;
					X509_STORE_add_cert(store, x0);
					X509_STORE_add_cert(store, x1);
					if (X509_STORE_CTX_init(&ctx, store, x2, 0) == 1) {
						X509_STORE_CTX_set_flags(&ctx, X509_V_FLAG_IGNORE_CRITICAL);
						if (X509_verify_cert(&ctx) == 1) {
							unsigned char md[SHA_DIGEST_LENGTH];
							if (partialDigest) {
								// XXX we need to flip ECID back before hashing
								flipAppleImg3Header((AppleImg3Header *)toHashData);
								doPartialSHA1(md, toHashData, toHashLength, partialDigest);
							} else {
								SHA1(toHashData, toHashLength, md);
							}
							rv = RSA_verify(NID_sha1, md, SHA_DIGEST_LENGTH, rsaSigData, rsaSigLen, rsa);
						}
						X509_STORE_CTX_cleanup(&ctx);
					}
					X509_STORE_free(store);
				}
				RSA_free(rsa);
			}
		}
		EVP_PKEY_free(pk);
	}
	return rv ? 0 : -1;
}
Beispiel #6
0
/* **************************************
 *
 * Information functions
 *
 * Print information for the end user.
 *
 ***************************************/
void
print_details (struct key_state_ssl * ks_ssl, const char *prefix)
{
  const SSL_CIPHER *ciph;
  X509 *cert;
  char s1[256];
  char s2[256];

  s1[0] = s2[0] = 0;
  ciph = SSL_get_current_cipher (ks_ssl->ssl);
  openvpn_snprintf (s1, sizeof (s1), "%s %s, cipher %s %s",
		    prefix,
		    SSL_get_version (ks_ssl->ssl),
		    SSL_CIPHER_get_version (ciph),
		    SSL_CIPHER_get_name (ciph));
  cert = SSL_get_peer_certificate (ks_ssl->ssl);
  if (cert != NULL)
    {
      EVP_PKEY *pkey = X509_get_pubkey (cert);
      if (pkey != NULL)
	{
	  if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
	      && pkey->pkey.rsa->n != NULL)
	    {
	      openvpn_snprintf (s2, sizeof (s2), ", %d bit RSA",
				BN_num_bits (pkey->pkey.rsa->n));
	    }
	  else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
		   && pkey->pkey.dsa->p != NULL)
	    {
	      openvpn_snprintf (s2, sizeof (s2), ", %d bit DSA",
				BN_num_bits (pkey->pkey.dsa->p));
	    }
	  EVP_PKEY_free (pkey);
	}
      X509_free (cert);
    }
  /* The SSL API does not allow us to look at temporary RSA/DH keys,
   * otherwise we should print their lengths too */
  msg (D_HANDSHAKE, "%s%s", s1, s2);
}
Beispiel #7
0
X509_REQ *
X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
	X509_REQ *ret;
	X509_REQ_INFO *ri;
	int i;
	EVP_PKEY *pktmp;

	ret = X509_REQ_new();
	if (ret == NULL) {
		X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE);
		goto err;
	}

	ri = ret->req_info;

	ri->version->length = 1;
	ri->version->data = malloc(1);
	if (ri->version->data == NULL)
		goto err;
	ri->version->data[0] = 0; /* version == 0 */

	if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x)))
		goto err;

	pktmp = X509_get_pubkey(x);
	i = X509_REQ_set_pubkey(ret, pktmp);
	EVP_PKEY_free(pktmp);
	if (!i)
		goto err;

	if (pkey != NULL) {
		if (!X509_REQ_sign(ret, pkey, md))
			goto err;
	}
	return (ret);

err:
	X509_REQ_free(ret);
	return (NULL);
}
Beispiel #8
0
static int
ssl_set_pkey(CERT *c, EVP_PKEY *pkey)
{
	int i;

	i = ssl_cert_type(NULL, pkey);
	if (i < 0) {
		SSLerr(SSL_F_SSL_SET_PKEY, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
		return (0);
	}

	if (c->pkeys[i].x509 != NULL) {
		EVP_PKEY *pktmp;
		pktmp = X509_get_pubkey(c->pkeys[i].x509);
		EVP_PKEY_copy_parameters(pktmp, pkey);
		EVP_PKEY_free(pktmp);
		ERR_clear_error();

		/*
		 * Don't check the public/private key, this is mostly
		 * for smart cards.
		 */
		if ((pkey->type == EVP_PKEY_RSA) &&
			(RSA_flags(pkey->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK))
;
		else
		if (!X509_check_private_key(c->pkeys[i].x509, pkey)) {
			X509_free(c->pkeys[i].x509);
			c->pkeys[i].x509 = NULL;
			return 0;
		}
	}

	EVP_PKEY_free(c->pkeys[i].privatekey);
	CRYPTO_add(&pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
	c->pkeys[i].privatekey = pkey;
	c->key = &(c->pkeys[i]);

	c->valid = 0;
	return (1);
}
/****** X509 UTILS *********************************************************/
DSA* dsaKeyFromCertFile(char *filename) {
	X509 *cacert;
	FILE *fp;

	if (!(fp = fopen(filename, "r")))
		critical_error("Error reading certificate file");
	if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL)))
		critical_error("Error reading  certificate in file");
	fclose(fp);

	EVP_PKEY *ca_pkey = X509_get_pubkey(cacert);
	DSA* ca_dsa = EVP_PKEY_get1_DSA(ca_pkey);

	free(ca_pkey);
	X509_free(cacert);

	if (ca_dsa == NULL)
		critical_error("Can't read DSA key from certificate");

	return ca_dsa;
}
Beispiel #10
0
BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* PublicKeyLength)
{
	BYTE* ptr;
	int length;
	BOOL status = TRUE;
	EVP_PKEY* pkey = NULL;

	pkey = X509_get_pubkey(cert->px509);
	if (!pkey)
	{
		WLog_ERR(TAG,  "X509_get_pubkey() failed");
		status = FALSE;
		goto exit;
	}

	length = i2d_PublicKey(pkey, NULL);
	if (length < 1)
	{
		WLog_ERR(TAG,  "i2d_PublicKey() failed");
		status = FALSE;
		goto exit;
	}

	*PublicKeyLength = (DWORD) length;
	*PublicKey = (BYTE*) malloc(length);
	ptr = (BYTE*) (*PublicKey);
	if (!ptr)
	{
		status = FALSE;
		goto exit;
	}

	i2d_PublicKey(pkey, &ptr);

exit:
	if (pkey)
		EVP_PKEY_free(pkey);

	return status;
}
Beispiel #11
0
/* self sign */
static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext, const EVP_MD *digest, 
						CONF *conf, char *section)
	{

	EVP_PKEY *pktmp;

	pktmp = X509_get_pubkey(x);
	EVP_PKEY_copy_parameters(pktmp,pkey);
	EVP_PKEY_save_parameters(pktmp,1);
	EVP_PKEY_free(pktmp);

	if (!X509_set_issuer_name(x,X509_get_subject_name(x))) goto err;
	if (X509_gmtime_adj(X509_get_notBefore(x),0) == NULL) goto err;

	/* Lets just make it 12:00am GMT, Jan 1 1970 */
	/* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
	/* 28 days to be certified */

	if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
		goto err;

	if (!X509_set_pubkey(x,pkey)) goto err;
	if (clrext)
		{
		while (X509_get_ext_count(x) > 0) X509_delete_ext(x, 0);
		}
	if (conf)
		{
		X509V3_CTX ctx;
		X509_set_version(x,2); /* version 3 certificate */
                X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
                X509V3_set_nconf(&ctx, conf);
                if (!X509V3_EXT_add_nconf(conf, &ctx, section, x)) goto err;
		}
	if (!X509_sign(x,pkey,digest)) goto err;
	return 1;
err:
	ERR_print_errors(bio_err);
	return 0;
	}
Beispiel #12
0
CRYPTO_PUBLIC_KEY *
crypto_cert_get_public_key(CRYPTO_CERT * cert, uint32 * key_len)
{
#ifdef CRYPTO_OPENSSL
	
	int nid;
	CRYPTO_PUBLIC_KEY *lkey;
	EVP_PKEY *epk = NULL;

	/* For some reason, Microsoft sets the OID of the Public RSA key to
	   the oid for "MD5 with RSA Encryption" instead of "RSA Encryption"

	   Kudos to Richard Levitte for the following (intuitive)
	   lines of code that resets the OID and lets us extract the key. */
	
	nid = OBJ_obj2nid(cert->cert_info->key->algor->algorithm);
	
	if ((nid == NID_md5WithRSAEncryption) || (nid == NID_shaWithRSAEncryption))
	{
		ASN1_OBJECT_free(cert->cert_info->key->algor->algorithm);
		cert->cert_info->key->algor->algorithm = OBJ_nid2obj(NID_rsaEncryption);
	}
	
	epk = X509_get_pubkey(cert);
	
	if (NULL == epk)
		return NULL;

	lkey = RSAPublicKey_dup((RSA *) epk->pkey.ptr);
	*key_len = RSA_size(lkey);
	EVP_PKEY_free(epk);
	
	return lkey;

#else /* built-in crypto */

	return ssl_cert_get_public_key(cert, key_len);
	
#endif
}
Beispiel #13
0
void genAlgorithmProperties(X509* cert,
                            std::string& key,
                            std::string& sig,
                            std::string& size) {
  int nid = 0;
  nid = OBJ_obj2nid(cert->cert_info->key->algor->algorithm);
  if (nid != NID_undef) {
    key = std::string(OBJ_nid2ln(nid));

    // Get EVP public key, to determine public key size.
    EVP_PKEY* pkey = nullptr;
    pkey = X509_get_pubkey(cert);
    if (pkey != nullptr) {
      if (nid == NID_rsaEncryption || nid == NID_dsa) {
        size_t key_size = 0;
        key_size = EVP_PKEY_size(pkey);
        size = std::to_string(key_size * 8);
      }

      // The EVP_size for EC keys returns the maximum buffer for storing the
      // key data, it does not indicate the size/strength of the curve.
      if (nid == NID_X9_62_id_ecPublicKey) {
        const EC_KEY* ec_pkey = pkey->pkey.ec;
        const EC_GROUP* ec_pkey_group = nullptr;
        ec_pkey_group = EC_KEY_get0_group(ec_pkey);
        int curve_nid = 0;
        curve_nid = EC_GROUP_get_curve_name(ec_pkey_group);
        if (curve_nid != NID_undef) {
          size = std::string(OBJ_nid2ln(curve_nid));
        }
      }
    }
    EVP_PKEY_free(pkey);
  }

  nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
  if (nid != NID_undef) {
    sig = std::string(OBJ_nid2ln(nid));
  }
}
bool _verify_signature(LLPointer<LLCertificate> parent, 
					   LLPointer<LLCertificate> child)
{
	bool verify_result = FALSE; 
	LLSD cert1, cert2;
	parent->getLLSD(cert1);
	child->getLLSD(cert2);
	X509 *signing_cert = parent->getOpenSSLX509();
	X509 *child_cert = child->getOpenSSLX509();
	if((signing_cert != NULL) && (child_cert != NULL))
	{
		EVP_PKEY *pkey = X509_get_pubkey(signing_cert);
		
		
		if(pkey)
		{
			int verify_code = X509_verify(child_cert, pkey);
			verify_result = ( verify_code > 0);
			EVP_PKEY_free(pkey);
		}
		else
		{
			LL_WARNS("SECAPI") << "Could not validate the cert chain signature, as the public key of the signing cert could not be retrieved" << LL_ENDL;
		}

	}
	else
	{
		LL_WARNS("SECAPI") << "Signature verification failed as there are no certs in the chain" << LL_ENDL;
	}
	if(child_cert)
	{
		X509_free(child_cert);
	}
	if(signing_cert)
	{
		X509_free(signing_cert);
	}
	return verify_result;
}
Beispiel #15
0
static EVP_PKEY *extract_pkey_from_x509(const char *x509_str) {
  X509 *x509 = NULL;
  EVP_PKEY *result = NULL;
  BIO *bio = BIO_new(BIO_s_mem());
  size_t len = strlen(x509_str);
  GPR_ASSERT(len < INT_MAX);
  BIO_write(bio, x509_str, (int)len);
  x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
  if (x509 == NULL) {
    gpr_log(GPR_ERROR, "Unable to parse x509 cert.");
    goto end;
  }
  result = X509_get_pubkey(x509);
  if (result == NULL) {
    gpr_log(GPR_ERROR, "Cannot find public key in X509 cert.");
  }

end:
  BIO_free(bio);
  if (x509 != NULL) X509_free(x509);
  return result;
}
Beispiel #16
0
int GetRSAKey(RSA **rsa,		/* freed by caller */	
	      X509 *x509Certificate)
{
    int 		rc = 0;
    EVP_PKEY 		*pkey = NULL;
    
    if (rc == 0) {
	pkey = X509_get_pubkey(x509Certificate);
	if (pkey == NULL) {
	    printf("Error: Cannot get certificate public key\n");
	    rc = -1;
	}
    }
    if (rc == 0) {
	*rsa = EVP_PKEY_get1_RSA(pkey);
	if (*rsa == NULL) {
	    printf("Error: Cannot extract certificate RSA public key\n");
	    rc = -1;
	}
    }
    return rc;
}
Beispiel #17
0
void * wi_socket_ssl_pubkey(wi_socket_t *socket) {
#ifdef WI_SSL
	RSA			*rsa = NULL;
	X509		*x509 = NULL;
	EVP_PKEY	*pkey = NULL;

	x509 = SSL_get_peer_certificate(socket->ssl);

	if(!x509) {
		wi_error_set_ssl_error();
		
		goto end;
	}
	
	pkey = X509_get_pubkey(x509);
	
	if(!pkey) {
		wi_error_set_ssl_error();

		goto end;
	}
	
	rsa = EVP_PKEY_get1_RSA(pkey);
	
	if(!rsa)
		wi_error_set_ssl_error();

end:
	if(x509)
		X509_free(x509);
	
	if(pkey)
		EVP_PKEY_free(pkey);
	
	return rsa;
#else
	return NULL;
#endif
}
Beispiel #18
0
wi_rsa_t * wi_socket_ssl_public_key(wi_socket_t *socket) {
#ifdef HAVE_OPENSSL_SSL_H
	RSA			*rsa = NULL;
	X509		*x509 = NULL;
	EVP_PKEY	*pkey = NULL;

	x509 = SSL_get_peer_certificate(socket->ssl);

	if(!x509) {
		wi_error_set_openssl_error();
		
		goto end;
	}
	
	pkey = X509_get_pubkey(x509);
	
	if(!pkey) {
		wi_error_set_openssl_error();

		goto end;
	}
	
	rsa = EVP_PKEY_get1_RSA(pkey);
	
	if(!rsa)
		wi_error_set_openssl_error();

end:
	if(x509)
		X509_free(x509);
	
	if(pkey)
		EVP_PKEY_free(pkey);
	
	return wi_autorelease(wi_rsa_init_with_rsa(wi_rsa_alloc(), rsa));
#else
	return NULL;
#endif
}
Beispiel #19
0
int ssl_cert_type(X509 *x, EVP_PKEY *pkey)
	{
	EVP_PKEY *pk;
	int ret= -1,i;

	if (pkey == NULL)
		pk=X509_get_pubkey(x);
	else
		pk=pkey;
	if (pk == NULL) goto err;

	i=pk->type;
	if (i == EVP_PKEY_RSA)
		{
		ret=SSL_PKEY_RSA_ENC;
		}
	else if (i == EVP_PKEY_DSA)
		{
		ret=SSL_PKEY_DSA_SIGN;
		}
#ifndef OPENSSL_NO_EC
	else if (i == EVP_PKEY_EC)
		{
		ret = SSL_PKEY_ECC;
		}	
#endif
	else if (i == NID_id_GostR3410_94 || i == NID_id_GostR3410_94_cc) 
		{
		ret = SSL_PKEY_GOST94;
		}
	else if (i == NID_id_GostR3410_2001 || i == NID_id_GostR3410_2001_cc) 
		{
		ret = SSL_PKEY_GOST01;
		}
err:
	if(!pkey) EVP_PKEY_free(pk);
	return(ret);
	}
Beispiel #20
0
//Get key from a cert file, return string
std::string get_key_from_certfile(const char* certfile) {
  BIO* certbio = NULL;
  certbio = BIO_new_file(certfile, "r");
  X509* cert = NULL;
  cert = PEM_read_bio_X509(certbio, NULL, NULL, NULL); 
  EVP_PKEY* key = NULL;
  key = X509_get_pubkey(cert);

  BIO* out = NULL;
  out = BIO_new(BIO_s_mem());
  PEM_write_bio_PUBKEY(out, key);

  std::string pubkey_str;
  for(;;) {
    char s[256];
    int l = BIO_read(out,s,sizeof(s));
    if(l <= 0) break;
    pubkey_str.append(s,l);;
  }

  EVP_PKEY_free(key);
  X509_free(cert);
  BIO_free_all(certbio);
  BIO_free_all(out);

  if(!pubkey_str.empty()) {
    std::size_t pos = pubkey_str.find("BEGIN PUBLIC KEY");
    if(pos != std::string::npos) {
      std::size_t pos1 = pubkey_str.find_first_of("---", pos);
      std::size_t pos2 = pubkey_str.find_first_not_of("-", pos1);
      std::size_t pos3 = pubkey_str.find_first_of("---", pos2);
      std::string str = pubkey_str.substr(pos2+1, pos3-pos2-2);
      return str;
    }
    return ("");
  }
  return pubkey_str;
}
Beispiel #21
0
@return: modulus\n\
";

static PyObject *
crypto_X509_modulus(crypto_X509Obj *self, PyObject *args)
{
    EVP_PKEY *pkey;
    PyObject *str;
    char *tmp_str;
    int str_len;
    BIO *bio = BIO_new(BIO_s_mem());

    if (!PyArg_ParseTuple(args, ":modulus"))
    {
        BIO_free(bio);
        return NULL;
    }

    if ((pkey = X509_get_pubkey(self->x509)) == NULL)
    {
        BIO_free(bio);
        exception_from_error_queue(crypto_Error);
        return NULL;
    }

    if (pkey->type == EVP_PKEY_RSA)
        BN_print(bio, pkey->pkey.rsa->n);
    else
    if (pkey->type == EVP_PKEY_DSA)
        BN_print(bio, pkey->pkey.dsa->pub_key);

    EVP_PKEY_free(pkey);
    str_len = BIO_get_mem_data(bio, &tmp_str);
    str = PyString_FromStringAndSize(tmp_str, str_len);
    BIO_free(bio);

    return str;
}
std::string get_public_key_from_cert(X509* cert)
{
    std::string result;

    EVP_PKEY *pKey =  X509_get_pubkey(cert);
    
    if(!pKey)
    {
        return result;
    }

    std::size_t keyLen = i2d_PublicKey(pKey, NULL);

    if(keyLen > 0)
    {
        std::vector<unsigned char> buf(keyLen, 0x00);

        unsigned char *buffer = &buf[0];

        i2d_PublicKey(pKey, &buffer);

        std::stringstream ssResult;

        ssResult << std::hex;

        for(auto value: buf)
        {
            ssResult << std::setw(2) << std::setfill('0') << (int) (value);
        }

        result = ssResult.str();
    }

    EVP_PKEY_free(pKey);

    return result; 
}
Beispiel #23
0
boolean crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* PublicKeyLength)
{
	BYTE* ptr;
	int length;
	boolean status = true;
	EVP_PKEY* pkey = NULL;

	pkey = X509_get_pubkey(cert->px509);

	if (!pkey)
	{
		printf("crypto_cert_get_public_key: X509_get_pubkey() failed\n");
		status = false;
		goto exit;
	}

	length = i2d_PublicKey(pkey, NULL);

	if (length < 1)
	{
		printf("crypto_cert_get_public_key: i2d_PublicKey() failed\n");
		status = false;
		goto exit;
	}

	*PublicKeyLength = (DWORD) length;
	*PublicKey = (BYTE*) malloc(length);
	ptr = (BYTE*) (*PublicKey);

	i2d_PublicKey(pkey, &ptr);

exit:
	if (pkey)
		EVP_PKEY_free(pkey);

	return status;
}
Beispiel #24
0
void
check_key_length (SSL *ssl)
{
  uint32_t key_bits;
  X509 *certificate;
  EVP_PKEY *public_key;
  certificate = SSL_get_peer_certificate (ssl);
  if (NULL == certificate)
  {
    die ("Getting certificate failed");
  }
  public_key = X509_get_pubkey (certificate);
  if (NULL == public_key)
  {
    die ("public key extraction failure");
  } else {
    verb_debug ("V: public key is ready for inspection");
  }

  key_bits = get_certificate_keybits (public_key);
  if (MIN_PUB_KEY_LEN >= key_bits && public_key->type != EVP_PKEY_EC)
  {
    die ("Unsafe public key size: %d bits", key_bits);
  } else {
     if (public_key->type == EVP_PKEY_EC)
       if(key_bits >= MIN_ECC_PUB_KEY_LEN
          && key_bits <= MAX_ECC_PUB_KEY_LEN)
       {
         verb_debug ("V: ECC key length appears safe");
       } else {
         die ("Unsafe ECC key size: %d bits", key_bits);
     } else {
       verb_debug ("V: key length appears safe");
     }
  }
  EVP_PKEY_free (public_key);
}
Beispiel #25
0
static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from,
                                  unsigned char *to, int padding)
{
    EVP_PKEY *pkey = NULL;
    int i = -1;

    if ((sc == NULL) || (sc->peer_key->x509 == NULL) ||
        ((pkey = X509_get_pubkey(sc->peer_key->x509)) == NULL)) {
        SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, SSL_R_NO_PUBLICKEY);
        return (-1);
    }
    if (pkey->type != EVP_PKEY_RSA) {
        SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, SSL_R_PUBLIC_KEY_IS_NOT_RSA);
        goto end;
    }

    /* we have the public key */
    i = RSA_public_encrypt(len, from, to, pkey->pkey.rsa, padding);
    if (i < 0)
        SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT, ERR_R_RSA_LIB);
 end:
    EVP_PKEY_free(pkey);
    return (i);
}
Beispiel #26
0
static EVP_PKEY_CTX *
init_ctx(int *pkeysize,
    char *keyfile, int keyform, int key_type,
    char *passargin, int pkey_op)
{
	EVP_PKEY *pkey = NULL;
	EVP_PKEY_CTX *ctx = NULL;
	char *passin = NULL;
	int rv = -1;
	X509 *x;
	if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
		|| (pkey_op == EVP_PKEY_OP_DERIVE))
	    && (key_type != KEY_PRIVKEY)) {
		BIO_printf(bio_err, "A private key is needed for this operation\n");
		goto end;
	}
	if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto end;
	}
	switch (key_type) {
	case KEY_PRIVKEY:
		pkey = load_key(bio_err, keyfile, keyform, 0,
		    passin, "Private Key");
		break;

	case KEY_PUBKEY:
		pkey = load_pubkey(bio_err, keyfile, keyform, 0,
		    NULL, "Public Key");
		break;

	case KEY_CERT:
		x = load_cert(bio_err, keyfile, keyform,
		    NULL, "Certificate");
		if (x) {
			pkey = X509_get_pubkey(x);
			X509_free(x);
		}
		break;

	}

	*pkeysize = EVP_PKEY_size(pkey);

	if (!pkey)
		goto end;

	ctx = EVP_PKEY_CTX_new(pkey, NULL);

	EVP_PKEY_free(pkey);

	if (!ctx)
		goto end;

	switch (pkey_op) {
	case EVP_PKEY_OP_SIGN:
		rv = EVP_PKEY_sign_init(ctx);
		break;

	case EVP_PKEY_OP_VERIFY:
		rv = EVP_PKEY_verify_init(ctx);
		break;

	case EVP_PKEY_OP_VERIFYRECOVER:
		rv = EVP_PKEY_verify_recover_init(ctx);
		break;

	case EVP_PKEY_OP_ENCRYPT:
		rv = EVP_PKEY_encrypt_init(ctx);
		break;

	case EVP_PKEY_OP_DECRYPT:
		rv = EVP_PKEY_decrypt_init(ctx);
		break;

	case EVP_PKEY_OP_DERIVE:
		rv = EVP_PKEY_derive_init(ctx);
		break;
	}

	if (rv <= 0) {
		EVP_PKEY_CTX_free(ctx);
		ctx = NULL;
	}
 end:

	free(passin);

	return ctx;


}
Beispiel #27
0
bool isValid() {
	static bool hasValidated = false;
	static bool validates = false;

	if ( hasValidated ) return validates;

	Environment *env = Environment::Instance();
	if ( env == NULL ) {
		cerr << "FATAL ERROR: No environment available" << endl;
		return false;
	}

	hasValidated = true;

	string licenseDir = env->configDir() + "/key";
	string licenseFile = licenseDir + "/License";
	string licenseKeyfile = licenseDir + "/License.key";
	string licenseSignature = licenseDir + "/License.signed";

	boost::filesystem::path path = SC_FS_PATH(env->shareDir())
	    / SC_FS_PATH("licenses") / SC_FS_PATH("seiscomp3.crt");

	if ( !Seiscomp::Util::fileExists(path.string().c_str()) ) {
		path = SC_FS_PATH(env->configDir())
		    / SC_FS_PATH("licenses") / SC_FS_PATH("seiscomp3.crt");
		if ( !Seiscomp::Util::fileExists(path.string()) ) {
			path = SC_FS_PATH(env->configDir())
			    / SC_FS_PATH("key") / SC_FS_PATH("License.crt");
		}
	}

	X509 *x509 = readCertificate(path.string());
	if ( x509 ) {
		ASN1_TIME* notAfter = X509_get_notAfter(x509),
		         * notBefore = X509_get_notBefore(x509);
		time_t ptime = time(NULL);

		int res = X509_cmp_time(notBefore, &ptime);
		if ( res == 0 || res > 0 ) {
			X509_free(x509);
			cerr << "FATAL ERROR: License has expired: " << path.string() << endl;
			return false;
		}

		res = X509_cmp_time(notAfter, &ptime);
		if ( res == 0 || res < 0 ) {
			X509_free(x509);
			cerr << "FATAL ERROR: License has expired: " << path.string() << endl;
			return false;
		}

		OpenSSL_add_all_algorithms();
		OpenSSL_add_all_ciphers();
		OpenSSL_add_all_digests();

		EVP_PKEY* pkey=X509_get_pubkey(x509);
		if ( !pkey ) {
			X509_free(x509);
			EVP_cleanup();
			cerr << "FATAL ERROR: License verification has failed: " << path.string() << endl;
			return false;
		}

		res = X509_verify(x509, pkey);
		if ( res != 1 ) {
			X509_free(x509);
			EVP_PKEY_free(pkey);
			EVP_cleanup();
			cerr << "FATAL ERROR: License verification has failed: " << path.string() << endl;
			return false;
		}

		char *buf;
		if ( readNID(&buf, x509, NID_netscape_comment) ) {
			licenseText = buf;
			delete buf;
		}

		EVP_PKEY_free(pkey);
		X509_free(x509);

		EVP_cleanup();

		return true;
	}

	// Read license file
	MD5_CTX ctx;
	MD5_Init(&ctx);

	unsigned char digest[MD5_DIGEST_LENGTH];
	char data[64];
	size_t len;

	ifstream f;

	try {
		f.open(licenseFile.c_str(), ios_base::in);
	}
	catch ( std::exception &e ) {
		cerr << "FATAL ERROR: Failed to open license file: " << licenseFile << endl;
		validates = false;
		return false;
	}

	if ( !f.good() ) {
		cerr << "FATAL ERROR: Failed to open license file: " << licenseFile << endl;
		validates = false;
		return false;
	}

	licenseText.clear();

	try {
		while ( (len = f.rdbuf()->sgetn(data, sizeof(data))) > 0 ) {
			licenseText.append(data, len);
			MD5_Update(&ctx, data, len);
		}
	}
	catch ( ... ) {
		cerr << "FATAL ERROR: Invalid license file: " << licenseFile << endl;
		f.close();
		validates = false;
		return false;
	}

	f.close();

	MD5_Final(digest, &ctx);

	int strength = 0;
	RSA *publicKey = readKey(licenseKeyfile.c_str(), PUBLIC, 1024, 8192, strength);
	if ( publicKey == NULL ) {
		cerr << "FATAL ERROR: Invalid key file: " << licenseKeyfile << endl;
		validates = false;
		return false;
	}

	BIO *bio_file = NULL, *b64_file;
	b64_file = BIO_new(BIO_f_base64());
	bio_file = BIO_new_file(licenseSignature.c_str(), "r");
	bio_file = BIO_push(b64_file, bio_file);

	int sigLength = strength / 8;
	unsigned char *signature = new unsigned char[sigLength];

	sigLength = BIO_read(bio_file, signature, sigLength);

	BIO_free_all(bio_file);

	if ( sigLength <= 0 ) {
		delete [] signature;
		cerr << "FATAL ERROR: Empty signature" << endl;
		validates = false;
		return false;
	}

	validates = RSA_verify(NID_md5, digest, MD5_DIGEST_LENGTH, signature, sigLength, publicKey);

	delete [] signature;

	/*
	if ( validates ) {
		cerr << "-----BEGIN LICENSE-----" << endl;
		cerr << licenseText << endl;
		cerr << "-----END LICENSE-----" << endl << endl;
	}
	*/

	return validates;
}
Beispiel #28
0
static void print_stuff(BIO *bio, SSL *s, int full)
{
    X509 *peer=NULL;
    char *p;
    static const char *space="                ";
    char buf[BUFSIZ];
    STACK_OF(X509) *sk;
    STACK_OF(X509_NAME) *sk2;
    SSL_CIPHER *c;
    X509_NAME *xn;
    int j,i;
#ifndef OPENSSL_NO_COMP
    const COMP_METHOD *comp, *expansion;
#endif

    if (full)
    {
        int got_a_chain = 0;

        sk=SSL_get_peer_cert_chain(s);
        if (sk != NULL)
        {
            got_a_chain = 1; /* we don't have it for SSL2 (yet) */

            BIO_printf(bio,"---\nCertificate chain\n");
            for (i=0; i<sk_X509_num(sk); i++)
            {
                X509_NAME_oneline(X509_get_subject_name(
                                      sk_X509_value(sk,i)),buf,sizeof buf);
                BIO_printf(bio,"%2d s:%s\n",i,buf);
                X509_NAME_oneline(X509_get_issuer_name(
                                      sk_X509_value(sk,i)),buf,sizeof buf);
                BIO_printf(bio,"   i:%s\n",buf);
                if (c_showcerts)
                    PEM_write_bio_X509(bio,sk_X509_value(sk,i));
            }
        }

        BIO_printf(bio,"---\n");
        peer=SSL_get_peer_certificate(s);
        if (peer != NULL)
        {
            BIO_printf(bio,"Server certificate\n");
            if (!(c_showcerts && got_a_chain)) /* Redundant if we showed the whole chain */
                PEM_write_bio_X509(bio,peer);
            X509_NAME_oneline(X509_get_subject_name(peer),
                              buf,sizeof buf);
            BIO_printf(bio,"subject=%s\n",buf);
            X509_NAME_oneline(X509_get_issuer_name(peer),
                              buf,sizeof buf);
            BIO_printf(bio,"issuer=%s\n",buf);
        }
        else
            BIO_printf(bio,"no peer certificate available\n");

        sk2=SSL_get_client_CA_list(s);
        if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0))
        {
            BIO_printf(bio,"---\nAcceptable client certificate CA names\n");
            for (i=0; i<sk_X509_NAME_num(sk2); i++)
            {
                xn=sk_X509_NAME_value(sk2,i);
                X509_NAME_oneline(xn,buf,sizeof(buf));
                BIO_write(bio,buf,strlen(buf));
                BIO_write(bio,"\n",1);
            }
        }
        else
        {
            BIO_printf(bio,"---\nNo client certificate CA names sent\n");
        }
        p=SSL_get_shared_ciphers(s,buf,sizeof buf);
        if (p != NULL)
        {
            /* This works only for SSL 2.  In later protocol
             * versions, the client does not know what other
             * ciphers (in addition to the one to be used
             * in the current connection) the server supports. */

            BIO_printf(bio,"---\nCiphers common between both SSL endpoints:\n");
            j=i=0;
            while (*p)
            {
                if (*p == ':')
                {
                    BIO_write(bio,space,15-j%25);
                    i++;
                    j=0;
                    BIO_write(bio,((i%3)?" ":"\n"),1);
                }
                else
                {
                    BIO_write(bio,p,1);
                    j++;
                }
                p++;
            }
            BIO_write(bio,"\n",1);
        }

        BIO_printf(bio,"---\nSSL handshake has read %ld bytes and written %ld bytes\n",
                   BIO_number_read(SSL_get_rbio(s)),
                   BIO_number_written(SSL_get_wbio(s)));
    }
    BIO_printf(bio,((s->hit)?"---\nReused, ":"---\nNew, "));
    c=SSL_get_current_cipher(s);
    BIO_printf(bio,"%s, Cipher is %s\n",
               SSL_CIPHER_get_version(c),
               SSL_CIPHER_get_name(c));
    if (peer != NULL) {
        EVP_PKEY *pktmp;
        pktmp = X509_get_pubkey(peer);
        BIO_printf(bio,"Server public key is %d bit\n",
                   EVP_PKEY_bits(pktmp));
        EVP_PKEY_free(pktmp);
    }
#ifndef OPENSSL_NO_COMP
    comp=SSL_get_current_compression(s);
    expansion=SSL_get_current_expansion(s);
    BIO_printf(bio,"Compression: %s\n",
               comp ? SSL_COMP_get_name(comp) : "NONE");
    BIO_printf(bio,"Expansion: %s\n",
               expansion ? SSL_COMP_get_name(expansion) : "NONE");
#endif
    SSL_SESSION_print(bio,SSL_get_session(s));
    BIO_printf(bio,"---\n");
    if (peer != NULL)
        X509_free(peer);
    /* flush, or debugging output gets mixed with http response */
    (void)BIO_flush(bio);
}
Beispiel #29
0
int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
                          X509 *x509)
{
    ASN1_OCTET_STRING *os;
    EVP_MD_CTX mdc_tmp, *mdc;
    int ret = 0, i;
    int md_type;
    STACK_OF(X509_ATTRIBUTE) *sk;
    BIO *btmp;
    EVP_PKEY *pkey;

    EVP_MD_CTX_init(&mdc_tmp);

    if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) {
        PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_WRONG_PKCS7_TYPE);
        goto err;
    }

    md_type = OBJ_obj2nid(si->digest_alg->algorithm);

    btmp = bio;
    for (;;) {
        if ((btmp == NULL) ||
            ((btmp = BIO_find_type(btmp, BIO_TYPE_MD)) == NULL)) {
            PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
                     PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
            goto err;
        }
        BIO_get_md_ctx(btmp, &mdc);
        if (mdc == NULL) {
            PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_INTERNAL_ERROR);
            goto err;
        }
        if (EVP_MD_CTX_type(mdc) == md_type)
            break;
        /*
         * Workaround for some broken clients that put the signature OID
         * instead of the digest OID in digest_alg->algorithm
         */
        if (EVP_MD_pkey_type(EVP_MD_CTX_md(mdc)) == md_type)
            break;
        btmp = BIO_next(btmp);
    }

    /*
     * mdc is the digest ctx that we want, unless there are attributes, in
     * which case the digest is the signed attributes
     */
    if (!EVP_MD_CTX_copy_ex(&mdc_tmp, mdc))
        goto err;

    sk = si->auth_attr;
    if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0)) {
        unsigned char md_dat[EVP_MAX_MD_SIZE], *abuf = NULL;
        unsigned int md_len;
        int alen;
        ASN1_OCTET_STRING *message_digest;

        if (!EVP_DigestFinal_ex(&mdc_tmp, md_dat, &md_len))
            goto err;
        message_digest = PKCS7_digest_from_attributes(sk);
        if (!message_digest) {
            PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
                     PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
            goto err;
        }
        if ((message_digest->length != (int)md_len) ||
            (memcmp(message_digest->data, md_dat, md_len))) {
#if 0
            {
                int ii;
                for (ii = 0; ii < message_digest->length; ii++)
                    printf("%02X", message_digest->data[ii]);
                printf(" sent\n");
                for (ii = 0; ii < md_len; ii++)
                    printf("%02X", md_dat[ii]);
                printf(" calc\n");
            }
#endif
            PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_DIGEST_FAILURE);
            ret = -1;
            goto err;
        }

        if (!EVP_VerifyInit_ex(&mdc_tmp, EVP_get_digestbynid(md_type), NULL))
            goto err;

        alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf,
                             ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY));
        if (alen <= 0) {
            PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_ASN1_LIB);
            ret = -1;
            goto err;
        }
        if (!EVP_VerifyUpdate(&mdc_tmp, abuf, alen))
            goto err;

        OPENSSL_free(abuf);
    }

    os = si->enc_digest;
    pkey = X509_get_pubkey(x509);
    if (!pkey) {
        ret = -1;
        goto err;
    }

    i = EVP_VerifyFinal(&mdc_tmp, os->data, os->length, pkey);
    EVP_PKEY_free(pkey);
    if (i <= 0) {
        PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_SIGNATURE_FAILURE);
        ret = -1;
        goto err;
    } else
        ret = 1;
 err:
    EVP_MD_CTX_cleanup(&mdc_tmp);
    return (ret);
}
Beispiel #30
-3
s32 https_verify_cert_no_contain_time(X509 *ca, X509 *cert)
{  
	s32     rv = 0;
	EVP_PKEY *pkey = NULL;

	pkey = X509_get_pubkey(ca);
	if(NULL == pkey)
	{
	    return ERR_HTTPS_CERT_UNABLE_GET_PUBKEY;
	}

	rv = X509_verify(cert, pkey);
	EVP_PKEY_free(pkey);
	if(rv < 0)
	{
	    return ERR_HTTPS_CERT_SIGNATURE_FAILURE;        
	}

	return ERROR_SUCCESS;
}