Exemple #1
0
/**
 * ssl_cache_trusted_cert - Cache a trusted certificate
 * @param c Certificate
 * @retval >0 Number of elements in the cache
 * @retval  0 Error
 */
static int ssl_cache_trusted_cert(X509 *c)
{
  mutt_debug(LL_DEBUG1, "trusted\n");
  if (!SslSessionCerts)
    SslSessionCerts = sk_X509_new_null();
  return sk_X509_push(SslSessionCerts, X509_dup(c));
}
Exemple #2
0
int main(){
	PKCS7 *p7;	
	int		len;
	unsigned char *der,*p;
	FILE *fp;
	X509 *x;
	BIO  *in;
	X509_ALGOR *md;
	PKCS7_SIGNER_INFO *si;

	p7=PKCS7_new();
	PKCS7_set_type(p7,NID_pkcs7_signed);
	p7->d.sign->cert=sk_X509_new_null();
	in=BIO_new_file("b64cert.cer","r");
	x=PEM_read_bio_X509(in,NULL,NULL,NULL);
	sk_X509_push(p7->d.sign->cert,x);
	md=X509_ALGOR_new();
	md->algorithm=OBJ_nid2obj(NID_md5);
	sk_X509_ALGOR_push(p7->d.sign->md_algs,md);
	si=PKCS7_SIGNER_INFO_new();
	ASN1_INTEGER_set(si->version,2);
	ASN1_INTEGER_set(si->issuer_and_serial->serial,333);
	sk_PKCS7_SIGNER_INFO_push(p7->d.sign->signer_info,si);
	len=i2d_PKCS7(p7,NULL);
	der=(unsigned char *)malloc(len);
	p=der;
	len=i2d_PKCS7(p7,&p);
	fp=fopen("p7_sign.cer","wb");
	fwrite(der,1,len,fp);
	fclose(fp);
	free(der);
	PKCS7_free(p7);
	return 0;
}
Exemple #3
0
void pki_pkcs7::signBio(pki_x509 *crt, BIO *bio)
{
	pki_key *privkey;
	EVP_PKEY *pk;
	STACK_OF(X509) *certstack;
	if (!crt)
		return;
	privkey = crt->getRefKey();
	if (!privkey)
		throw errorEx("No private key for signing found", getClassName());
	certstack = sk_X509_new_null();

	pki_x509 *signer = crt->getSigner();
	if (signer == crt)
		signer = NULL;
	while (signer != NULL ) {
		sk_X509_push(certstack, signer->getCert());
	        openssl_error();
		if (signer == signer->getSigner() )
			signer = NULL;
		else
			signer = signer->getSigner();
	}
	if (p7)
		PKCS7_free(p7);
	pk = privkey->decryptKey();
	p7 = PKCS7_sign(crt->getCert(), pk, certstack, bio, PKCS7_BINARY);
	EVP_PKEY_free(pk);
	openssl_error();
	sk_X509_free(certstack);
}
Exemple #4
0
/**
 * xmlSecOpenSSLX509StoreAdoptCert:
 * @store:              the pointer to X509 key data store klass.
 * @cert:               the pointer to OpenSSL X509 certificate.
 * @type:               the certificate type (trusted/untrusted).
 *
 * Adds trusted (root) or untrusted certificate to the store.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecOpenSSLX509StoreAdoptCert(xmlSecKeyDataStorePtr store, X509* cert, xmlSecKeyDataType type) {
    xmlSecOpenSSLX509StoreCtxPtr ctx;
    int ret;

    xmlSecAssert2(xmlSecKeyDataStoreCheckId(store, xmlSecOpenSSLX509StoreId), -1);
    xmlSecAssert2(cert != NULL, -1);

    ctx = xmlSecOpenSSLX509StoreGetCtx(store);
    xmlSecAssert2(ctx != NULL, -1);

    if((type & xmlSecKeyDataTypeTrusted) != 0) {
        xmlSecAssert2(ctx->xst != NULL, -1);

        ret = X509_STORE_add_cert(ctx->xst, cert);
        if(ret != 1) {
            xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                               "X509_STORE_add_cert");
            return(-1);
        }
        /* add cert increments the reference */
        X509_free(cert);
    } else {
        xmlSecAssert2(ctx->untrusted != NULL, -1);

        ret = sk_X509_push(ctx->untrusted, cert);
        if(ret < 1) {
            xmlSecOpenSSLError(xmlSecKeyDataStoreGetName(store),
                               "sk_X509_push");
            return(-1);
        }
    }
    return(0);
}
Exemple #5
0
TrustedObject::TrustedObject() {

	// add keys
	pub = EVP_PKEY_new();
	priv = EVP_PKEY_new();
	untrustPub = EVP_PKEY_new();

	cryptsuite::loadRSAPublicKey(TRUSTED_PUB, &pub);
	cryptsuite::loadRSAPrivateKey(TRUSTED_PRIV, &priv);
	cryptsuite::loadRSAPublicKey(UNTRUSTED_PUB, &untrustPub);

	// load trusted certificate
	if ( ! cryptsuite::loadX509Cert(TRUSTED_CERT, &CA) ) {
		fprintf(fpErr, "Error: Could not load CA cert\n");
	}

	// create X509 context
	ctx = X509_STORE_CTX_new();
	if (ctx == NULL) {
		fprintf(fpErr, "Error: Failed to create certificate store\n");
	}

	// add trusted certificate to stack
	STACK_OF(X509) *sk = sk_X509_new_null();
	sk_X509_push(sk, CA);
	if ( X509_STORE_CTX_init(ctx, NULL, NULL, NULL) != 1) {
		fprintf(fpErr, "Error: Failed to init cert store\n");
	} 
	X509_STORE_CTX_trusted_stack(ctx, sk);
}
int PKCS7_add_certificate(PKCS7 *p7, X509 *x509)
	{
	int i;
	STACK_OF(X509) **sk;

	i=OBJ_obj2nid(p7->type);
	switch (i)
		{
	case NID_pkcs7_signed:
		sk= &(p7->d.sign->cert);
		break;
	case NID_pkcs7_signedAndEnveloped:
		sk= &(p7->d.signed_and_enveloped->cert);
		break;
	default:
		PKCS7err(PKCS7_F_PKCS7_ADD_CERTIFICATE,PKCS7_R_WRONG_CONTENT_TYPE);
		return(0);
		}

	if (*sk == NULL)
		*sk=sk_X509_new_null();
	CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509);
	sk_X509_push(*sk,x509);
	return(1);
	}
Exemple #7
0
STACK_OF(X509) *TS_CONF_load_certs(const char *file)
	{
	BIO *certs = NULL;
	STACK_OF(X509) *othercerts = NULL;
	STACK_OF(X509_INFO) *allcerts = NULL;
	int i;

	if (!(certs = BIO_new_file(file, "r"))) goto end;

	if (!(othercerts = sk_X509_new_null())) goto end;
	allcerts = PEM_X509_INFO_read_bio(certs, NULL, NULL, NULL);
	for(i = 0; i < sk_X509_INFO_num(allcerts); i++)
		{
		X509_INFO *xi = sk_X509_INFO_value(allcerts, i);
		if (xi->x509)
			{
			sk_X509_push(othercerts, xi->x509);
			xi->x509 = NULL;
			}
		}
end:
	if (othercerts == NULL)
		fprintf(stderr, "unable to load certificates: %s\n", file);
	sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
	BIO_free(certs);
	return othercerts;
	}
Exemple #8
0
static int ssl_cache_trusted_cert (X509 *c)
{
        dprint (1, (debugfile, "trusted: %s\n", c->name));
        if (!SslSessionCerts)
                SslSessionCerts = sk_X509_new_null();
        return (sk_X509_push (SslSessionCerts, X509_dup(c)));
}
Exemple #9
0
STACK_OF(X509) *TS_CONF_load_certs(const char *file)
{
    BIO *certs = NULL;
    STACK_OF(X509) *othercerts = NULL;
    STACK_OF(X509_INFO) *allcerts = NULL;
    int i;

    if ((certs = BIO_new_file(file, "r")) == NULL)
        goto end;
    if ((othercerts = sk_X509_new_null()) == NULL)
        goto end;

    allcerts = PEM_X509_INFO_read_bio(certs, NULL, NULL, NULL);
    for (i = 0; i < sk_X509_INFO_num(allcerts); i++) {
        X509_INFO *xi = sk_X509_INFO_value(allcerts, i);
        if (xi->x509) {
            sk_X509_push(othercerts, xi->x509);
            xi->x509 = NULL;
        }
    }
 end:
    if (othercerts == NULL)
        TSerr(TS_F_TS_CONF_LOAD_CERTS, TS_R_CANNOT_LOAD_CERT);
    sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
    BIO_free(certs);
    return othercerts;
}
Exemple #10
0
void openssl_pkcs7_sign()
{
	int len;
	BIO *in;
	X509 *x;
	FILE *fp;
	PKCS7 *p7;
	X509_ALGOR *md;
	PKCS7_SIGNER_INFO *si;
	char name[MAX1_LEN], tmp[MAX1_LEN];
	unsigned char *der, *p, buf[SHA_DIGEST_LENGTH] = "pkcs7 sign";

	p7 = PKCS7_new();
	PKCS7_set_type(p7, NID_pkcs7_data);
	ASN1_OCTET_STRING_set(p7->d.data, buf, SHA_DIGEST_LENGTH);
	len = i2d_PKCS7(p7, NULL);
	der = (unsigned char *)malloc(len);
	p = der;
	len = i2d_PKCS7(p7, &p);
	fp = fopen("/tmp/test.cer", "wb");
	fwrite(der, 1, len, fp);
	fclose(fp);
	free(der);
	PKCS7_free(p7);

	p7 = PKCS7_new();
	PKCS7_set_type(p7, NID_pkcs7_signed);
	p7->d.sign->cert = sk_X509_new_null();
	in = BIO_new_file("/tmp/test.cer", "r");
	x = PEM_read_bio_X509(in, NULL, NULL, NULL);
	sk_X509_push(p7->d.sign->cert, x);
	BIO_free(in);

	md = X509_ALGOR_new();
	md->algorithm = OBJ_nid2obj(NID_md5);
	sk_X509_ALGOR_push(p7->d.sign->md_algs, md);

	si = PKCS7_SIGNER_INFO_new();
	ASN1_INTEGER_set(si->version, 2);
	ASN1_INTEGER_set(si->issuer_and_serial->serial, 333);
	sk_PKCS7_SIGNER_INFO_push(p7->d.sign->signer_info, si);

	len = i2d_PKCS7(p7, NULL);
	der = (unsigned char *)malloc(len);
	p = der;
	len = i2d_PKCS7(p7, &p);
	fp = fopen("/tmp/test.cer", "wb");
	fwrite(der, 1, len, fp);
	fclose(fp);
	free(der);

	fp = fopen("/tmp/test.cer", "rb");
	len = fread(tmp, 1, MAX1_LEN, fp);
	fclose(fp);
	p = (unsigned char *)&tmp;
	d2i_PKCS7(&p7, (const unsigned char **)&p, len);
	OBJ_obj2txt(name, MAX1_LEN, p7->type, 0);

	PKCS7_free(p7);
}
Exemple #11
0
STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms)
{
    STACK_OF(X509) *certs = NULL;
    CMS_CertificateChoices *cch;
    STACK_OF(CMS_CertificateChoices) **pcerts;
    int i;
    pcerts = cms_get0_certificate_choices(cms);
    if (!pcerts)
        return NULL;
    for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) {
        cch = sk_CMS_CertificateChoices_value(*pcerts, i);
        if (cch->type == 0) {
            if (!certs) {
                certs = sk_X509_new_null();
                if (!certs)
                    return NULL;
            }
            if (!sk_X509_push(certs, cch->d.certificate)) {
                sk_X509_pop_free(certs, X509_free);
                return NULL;
            }
            CRYPTO_add(&cch->d.certificate->references, 1, CRYPTO_LOCK_X509);
        }
    }
    return certs;

}
Exemple #12
0
int PKCS7_add_certificate(PKCS7 *p7, X509 *x509)
{
    int i;
    STACK_OF(X509) **sk;

    i = OBJ_obj2nid(p7->type);
    switch (i) {
    case NID_pkcs7_signed:
        sk = &(p7->d.sign->cert);
        break;
    case NID_pkcs7_signedAndEnveloped:
        sk = &(p7->d.signed_and_enveloped->cert);
        break;
    default:
        PKCS7err(PKCS7_F_PKCS7_ADD_CERTIFICATE, PKCS7_R_WRONG_CONTENT_TYPE);
        return (0);
    }

    if (*sk == NULL)
        *sk = sk_X509_new_null();
    if (*sk == NULL) {
        PKCS7err(PKCS7_F_PKCS7_ADD_CERTIFICATE, ERR_R_MALLOC_FAILURE);
        return 0;
    }
    X509_up_ref(x509);
    if (!sk_X509_push(*sk, x509)) {
        X509_free(x509);
        return 0;
    }
    return (1);
}
Exemple #13
0
STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
	{
	STACK_OF(X509) *signers = NULL;
	STACK_OF(CMS_SignerInfo) *sinfos;
	CMS_SignerInfo *si;
	int i;
	sinfos = CMS_get0_SignerInfos(cms);
	for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++)
		{
		si = sk_CMS_SignerInfo_value(sinfos, i);
		if (si->signer)
			{
			if (!signers)
				{
				signers = sk_X509_new_null();
				if (!signers)
					return NULL;
				}
			if (!sk_X509_push(signers, si->signer))
				{
				sk_X509_free(signers);
				return NULL;
				}
			}
		}
	return signers;
	}
Exemple #14
0
STACK_OF(X509) *get_cert_store(int *ids){
    STACK_OF(X509) *store = sk_X509_new(NULL);
    while(ids && ((*ids) != -1)){
        sk_X509_push(store, get_cert(*ids));
        ids++;
    }
    return store;
}
Exemple #15
0
int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert)
	{
	if (!resp->certs && !(resp->certs = sk_X509_new_null()))
		return 0;

	if(!sk_X509_push(resp->certs, cert)) return 0;
	CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
	return 1;
	}
Exemple #16
0
int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert)
{
    if (resp->certs == NULL
        && (resp->certs = sk_X509_new_null()) == NULL)
        return 0;

    if (!sk_X509_push(resp->certs, cert))
        return 0;
    X509_up_ref(cert);
    return 1;
}
// VerifyChain verifies the certificate chain in chain
// according to the verification options given as opts.
bool X509VerifierPrivate::VerifyChain(std::vector<X509Certificate> chain, const X509VerifierOptions &opts) {
	bool status = false;
	X509_STORE_CTX *ctx = X509_STORE_CTX_new();
	STACK_OF(X509) *untrusted = sk_X509_new_null();

	// Ensure that we have a chain to check on.
	if (chain.empty()) {
		goto out;
	}

	// If we've been passed a DNS name in opts,
	// we should check whether the leaf certificate
	// matches that before doing the more expensive
	// checks.
	if (!opts.dns_name.empty()) {
		if (!X509HostnameVerifier::VerifyHostname(chain.at(0), opts.dns_name)) {
			std::cerr << "X509VerifierPrivate - hostname verification failed" << std::endl;
			goto out;
		}
	}

	// Extract our chain into the format that OpenSSL
	// expects for verification.
	for (X509Certificate &cert : chain) {
		X509 *cur = cert.dptr_->AsOpenSSLX509();
		sk_X509_push(untrusted, cur);
	}

	// Set up the X509_STORE_CTX to verify according to opts.
	X509_STORE_CTX_init(ctx, store_, sk_X509_value(untrusted, 0), untrusted);
	// If a time is not specified in opts, use the current system time.
	if (opts.time == 0) {
		X509_STORE_CTX_set_time(ctx, 0, std::time(nullptr));
	} else {
		X509_STORE_CTX_set_time(ctx, 0, opts.time);
	}
	// If a dns_name is specified in opts, use the SSL server policy.
	if (!opts.dns_name.empty()) {
		X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_SSL_SERVER);
		X509_STORE_CTX_set_trust(ctx, X509_TRUST_SSL_SERVER);
	}

	if (X509_verify_cert(ctx) == 1) {
		status = true;
	} else {
		std::cerr << "X509VerifierPrivate - verification error: " << X509_verify_cert_error_string(ctx->error) << std::endl;
	}

out:
	sk_X509_pop_free(untrusted, X509_free);
	X509_STORE_CTX_free(ctx);
	return status;
}
Exemple #18
0
RTDECL(int) RTCrStoreConvertToOpenSslCertStack(RTCRSTORE hStore, uint32_t fFlags, void **ppvOpenSslStack)
{
    PRTCRSTOREINT pThis = (PRTCRSTOREINT)hStore;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTCRSTOREINT_MAGIC, VERR_INVALID_HANDLE);

    /*
     * Use the pfnCertFindAll method to add all certificates to the store we're returning.
     */
    int rc;
    STACK_OF(X509) *pOsslStack = sk_X509_new_null();
    if (pOsslStack)
    {
        RTCRSTORECERTSEARCH Search;
        rc = pThis->pProvider->pfnCertFindAll(pThis->pvProvider, &Search);
        if (RT_SUCCESS(rc))
        {
            do
            {
                PCRTCRCERTCTX pCertCtx = pThis->pProvider->pfnCertSearchNext(pThis->pvProvider, &Search);
                if (!pCertCtx)
                    break;

                if (pCertCtx->fFlags & RTCRCERTCTX_F_ENC_X509_DER)
                {
                    X509 *pOsslCert = NULL;
                    const unsigned char *pabEncoded = (const unsigned char *)pCertCtx->pabEncoded;
                    if (d2i_X509(&pOsslCert, &pabEncoded, pCertCtx->cbEncoded) == pOsslCert)
                    {
                        if (!sk_X509_push(pOsslStack, pOsslCert))
                        {
                            rc = VERR_NO_MEMORY;
                            X509_free(pOsslCert);
                        }
                    }
                }

                RTCrCertCtxRelease(pCertCtx);
            } while (RT_SUCCESS(rc));

            pThis->pProvider->pfnCertSearchDestroy(pThis->pvProvider, &Search);
            if (RT_SUCCESS(rc))
            {
                *ppvOpenSslStack = pOsslStack;
                return VINF_SUCCESS;
            }
        }
        sk_X509_pop_free(pOsslStack, X509_free);
    }
    else
        rc = VERR_NO_MEMORY;
    return rc;
}
static STACK_OF(X509) *
convert_certificate_chain_to_openssl (GTlsCertificateOpenssl *chain)
{
  GTlsCertificate *cert;
  STACK_OF(X509) *openssl_chain;

  openssl_chain = sk_X509_new_null ();

  for (cert = G_TLS_CERTIFICATE (chain); cert; cert = g_tls_certificate_get_issuer (cert))
    sk_X509_push (openssl_chain, g_tls_certificate_openssl_get_cert (G_TLS_CERTIFICATE_OPENSSL (cert)));

  return openssl_chain;
}
Exemple #20
0
void pki_pkcs7::encryptBio(pki_x509 *crt, BIO *bio)
{
	STACK_OF(X509) *certstack;
	if (!crt)
		return;
	certstack = sk_X509_new_null();
	sk_X509_push(certstack, crt->getCert());
	openssl_error();
	if (p7)
		PKCS7_free(p7);
	p7 = PKCS7_encrypt(certstack, bio, EVP_des_ede3_cbc(), PKCS7_BINARY);
	openssl_error();
	sk_X509_free(certstack);
}
Exemple #21
0
static STACK_OF(X509) *
chain_from_pem_file(const uschar * file)
{
BIO * bp;
X509 * x;
STACK_OF(X509) * sk;

if (!(sk = sk_X509_new_null())) return NULL;
if (!(bp = BIO_new_file(CS file, "r"))) return NULL;
while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
  sk_X509_push(sk, x);
BIO_free(bp);
return sk;
}
Exemple #22
0
int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert)
	{
	OCSP_SIGNATURE *sig;
	if (!req->optionalSignature)
		req->optionalSignature = OCSP_SIGNATURE_new();
	sig = req->optionalSignature;
	if (!sig) return 0;
	if (!cert) return 1;
	if (!sig->certs && !(sig->certs = sk_X509_new_null()))
		return 0;

	if(!sk_X509_push(sig->certs, cert)) return 0;
	CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
	return 1;
	}
Exemple #23
0
/**
 * Parses X.509 PEM formatted certificates from file. The file can contain multiple
 * certificates. You can just use 'cat' command in linux to add multiple PEM formatted
 * X.509 certificates to one file (e.g. <code>cat cert1.pem cert2.pem > certs.pem</code>).
 * NB! This struct must be freed using sk_X509_free() function from OpenSSL or
 * with X509Stack_scope struct.
 *
 * @param path PEM formatted X.509 certificates file path.
 * @return returns stack of parsed X.509 certificates.
 * @throws IOException throws exception if the file does not contain X.509
 *         PEM formatted certificate(s).
 */
STACK_OF(X509)* digidoc::X509Cert::loadX509Stack(const std::string& path) throw(IOException)
{
    // Create an empty X.509 stack.
    STACK_OF(X509)* stack = sk_X509_new_null();
    if(stack == NULL)
    {
        THROW_IOEXCEPTION("Failed to create X.509 certificate stack.");
    }

    // Initialize OpenSSL file.
    BIO* file = BIO_new(BIO_s_file()); BIO_scope fileScope(&file);
    if(file == NULL)
    {
        THROW_IOEXCEPTION("Failed to open X.509 certificates file '%s': %s",
                path.c_str(), ERR_reason_error_string(ERR_get_error()));
    }

    // Open file, which can contain multiple X.509 certificates.
    if(BIO_read_filename(file, path.c_str()) <= 0)
    {
        THROW_IOEXCEPTION("Failed to open X.509 certificates file '%s': %s",
                path.c_str(), ERR_reason_error_string(ERR_get_error()));
    }

    // Read certificates info from the file.
    STACK_OF(X509_INFO)* certsInfo = PEM_X509_INFO_read_bio(file, NULL, NULL, NULL);
    if(certsInfo == NULL)
    {
        THROW_IOEXCEPTION("Failed to read X.509 certificates from file '%s': %s",
                path.c_str(), ERR_reason_error_string(ERR_get_error()));
    }

    // Put all found certificates to the stack.
    for(int i = 0; i < sk_X509_INFO_num(certsInfo); i++)
    {
        X509_INFO* xi = sk_X509_INFO_value(certsInfo, i);
        if(xi->x509 != NULL)
        {
            sk_X509_push(stack, xi->x509);
            xi->x509 = NULL;
        }
    }

    // Release resources.
    sk_X509_INFO_pop_free(certsInfo, X509_INFO_free);

    return stack;
}
Exemple #24
0
static STACK_OF(X509) *
read_fullchain(const char *file, int *count)
{
	int i;
	BIO *bio;
	STACK_OF(X509_INFO) *xis = NULL;
	X509_INFO *xi;
	STACK_OF(X509) *rv = NULL;

	*count = 0;

	if ((bio = BIO_new_file(file, "r")) == NULL) {
		warn("Unable to read a certificate from %s", file);
		return NULL;
	}
	if ((xis = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL)) == NULL) {
		warnx("Unable to read PEM format from %s", file);
		return NULL;
	}
	BIO_free(bio);

	if (sk_X509_INFO_num(xis) <= 0) {
		warnx("No certificates in file %s", file);
		goto end;
	}
	if ((rv = sk_X509_new_null()) == NULL) {
		warnx("malloc failed");
		goto end;
	}

	for (i = 0; i < sk_X509_INFO_num(xis); i++) {
		xi = sk_X509_INFO_value(xis, i);
		if (xi->x509 == NULL)
		    continue;
		if (!sk_X509_push(rv, xi->x509)) {
			warnx("unable to build x509 chain");
			sk_X509_pop_free(rv, X509_free);
			rv = NULL;
			goto end;
		}
		xi->x509 = NULL;
		(*count)++;
	}
end:
	sk_X509_INFO_pop_free(xis, X509_INFO_free);
	return rv;
}
Exemple #25
0
/**
 * Returns a list of all x509 certificates in a PKCS12 object.
 */
static STACK_OF(X509) *pkcs12_listCerts(PKCS12 *p12) {
    STACK_OF(X509) *x509s = sk_X509_new_null();
    if (!x509s) return NULL;
    
    // Extract all PKCS7 safes
    STACK_OF(PKCS7) *pkcs7s = PKCS12_unpack_authsafes(p12);
    if (!pkcs7s) {
        certutil_updateErrorString();
        sk_X509_free(x509s);
        return NULL;
    }
    
    // For each PKCS7 safe
    int nump = sk_PKCS7_num(pkcs7s);
    for (int p = 0; p < nump; p++) {
        PKCS7 *p7 = sk_PKCS7_value(pkcs7s, p);
        if (!p7) continue;
        STACK_OF(PKCS12_SAFEBAG) *safebags = PKCS12_unpack_p7data(p7);
        if (!safebags) {
            certutil_updateErrorString();
            continue;
        }
        
        // For each PKCS12 safebag
        int numb = sk_PKCS12_SAFEBAG_num(safebags);
        for (int i = 0; i < numb; i++) {
            PKCS12_SAFEBAG *bag = sk_PKCS12_SAFEBAG_value(safebags, i);
            if (!bag) continue;
            
            if (M_PKCS12_bag_type(bag) == NID_certBag) {
                // Extract x509 cert
                X509 *x509 = PKCS12_certbag2x509(bag);
                if (x509 == NULL) {
                    certutil_updateErrorString();
                } else {
                    sk_X509_push(x509s, x509);
                }
            }
        }
        
        sk_PKCS12_SAFEBAG_pop_free(safebags, PKCS12_SAFEBAG_free);
    }
    
    sk_PKCS7_pop_free(pkcs7s, PKCS7_free);
    return x509s;
}
Exemple #26
0
/* This function must be called before trying to sign any file.
 * It loads string for errors, and ciphers are auto-loaded by OpenSSL now.
 * If this function fails it may be because the certificate cannot
 * be validated.
 *
 * returns: true if can initialize and validate certificates, otherwise false */
bool initialize_signature(void)
{
	int ret = -1;
	time_t mod_sec = 0;
	struct tm *alttime;
	struct stat statt;

	string_or_die(&CERTNAME, "%s/%s", cert_path, SWUPDCERT);

	ERR_load_crypto_strings();
	ERR_load_PKCS7_strings();
	EVP_add_digest(EVP_sha256());

	if (!get_pubkey()) {
		goto fail;
	}

	ret = validate_certificate();
	if (ret) {
		printf("Failed to verify certificate: %s\n", X509_verify_cert_error_string(ret));
		if (ret == X509_V_ERR_CERT_NOT_YET_VALID) {
			/* If we can retrieve an approx. good system time, report out to user */
			if (stat("/usr/lib/os-release", &statt) != -1) {
				mod_sec = statt.st_mtim.tv_sec;
				char timebuf[30];
				alttime = localtime(&mod_sec);
				strftime(timebuf, sizeof(timebuf), "%F", alttime);
				printf("System clock should be at least %s\n", timebuf);
			}
		}
		goto fail;
	}

	/* Push our trust cert(s) to the stack, which is a set of certificates
	 * in which to search for the signer's cert. */
	x509_stack = sk_X509_new_null();
	if (!x509_stack) {
		goto fail;
	}
	sk_X509_push(x509_stack, cert);

	return true;
fail:
	return false;
}
Exemple #27
0
/* 
功能:验证签名 
入口: 
char*certFile    证书(含匙) 
char* plainText  明文 
char* cipherText 签名 
出口: 
bool true  签名验证成功 
bool false 验证失败 
*/  
bool PKCS7_VerifySign(char*certFile,char* plainText,char* cipherText )  
{  
    /* Get X509 */  
    FILE* fp = fopen (certFile, "r");  
    if (fp == NULL)   
        return false;  
    X509* x509 = PEM_read_X509(fp, NULL, NULL, NULL);  
    fclose (fp);  
  
    if (x509 == NULL) {  
        ERR_print_errors_fp (stderr);  
        return false;  
    }  
  
    //BASE64解码  
    unsigned char *retBuf[1024*8];  
    int retBufLen = sizeof(retBuf);  
    memset(retBuf,0,sizeof(retBuf));  
    decodeBase64(cipherText,(void *)retBuf,&retBufLen);  
  
    //从签名中取PKCS7对象  
    BIO* vin = BIO_new_mem_buf(retBuf,retBufLen);  
    PKCS7 *p7 = d2i_PKCS7_bio(vin,NULL);  
  
  
    //取STACK_OF(X509)对象  
    STACK_OF(X509) *stack=sk_X509_new_null();//X509_STORE_new()  
    sk_X509_push(stack,x509);  
  
  
    //明码数据转为BIO  
    BIO *bio = BIO_new(BIO_s_mem());    
    BIO_puts(bio,plainText);  
  
    //验证签名  
    int err = PKCS7_verify(p7, stack, NULL,bio, NULL, PKCS7_NOVERIFY);  
  
    if (err != 1) {  
        ERR_print_errors_fp (stderr);  
        return false;  
    }  
  
    return true;  
}  
Exemple #28
0
static int test_resp_signer(void)
{
    OCSP_BASICRESP *bs = NULL;
    X509 *signer = NULL, *tmp;
    EVP_PKEY *key = NULL;
    STACK_OF(X509) *extra_certs = NULL;
    int ret = 0;

    /*
     * Test a response with no certs at all; get the signer from the
     * extra certs given to OCSP_resp_get0_signer().
     */
    bs = make_dummy_resp();
    extra_certs = sk_X509_new_null();
    if (!TEST_ptr(bs)
        || !TEST_ptr(extra_certs)
        || !TEST_true(get_cert_and_key(&signer, &key))
        || !TEST_true(sk_X509_push(extra_certs, signer))
        || !TEST_true(OCSP_basic_sign(bs, signer, key, EVP_sha1(),
                                      NULL, OCSP_NOCERTS)))
        goto err;
    if (!TEST_true(OCSP_resp_get0_signer(bs, &tmp, extra_certs))
        || !TEST_int_eq(X509_cmp(tmp, signer), 0))
        goto err;
    OCSP_BASICRESP_free(bs);

    /* Do it again but include the signer cert */
    bs = make_dummy_resp();
    tmp = NULL;
    if (!TEST_ptr(bs)
        || !TEST_true(OCSP_basic_sign(bs, signer, key, EVP_sha1(),
                                      NULL, 0)))
        goto err;
    if (!TEST_true(OCSP_resp_get0_signer(bs, &tmp, NULL))
        || !TEST_int_eq(X509_cmp(tmp, signer), 0))
        goto err;
    ret = 1;
 err:
    OCSP_BASICRESP_free(bs);
    sk_X509_free(extra_certs);
    X509_free(signer);
    EVP_PKEY_free(key);
    return ret;
}
Exemple #29
0
int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert)
{
    OCSP_SIGNATURE *sig;
    if (req->optionalSignature == NULL)
        req->optionalSignature = OCSP_SIGNATURE_new();
    sig = req->optionalSignature;
    if (sig == NULL)
        return 0;
    if (cert == NULL)
        return 1;
    if (sig->certs == NULL
        && (sig->certs = sk_X509_new_null()) == NULL)
        return 0;

    if (!sk_X509_push(sig->certs, cert))
        return 0;
    X509_up_ref(cert);
    return 1;
}
Exemple #30
0
/* load a stack of x509 certificates */
STACK_OF(X509)*
ocsp_load_certs(const char *file)
{
	BIO			*bio = NULL;
	STACK_OF(X509)		*certs = NULL;
	STACK_OF(X509_INFO)	*xis = NULL;
	X509_INFO		*xi;
	int			 i;

	if ((bio = BIO_new_file(file, "r")) == NULL) {
		log_warn("%s: BIO_new_file failed for %s",
		    __func__, file);
		return (NULL);
	}
	if ((xis = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL)) == NULL) {
		ca_sslerror(__func__);
		goto done;
	}
	if ((certs = sk_X509_new_null()) == NULL) {
		log_debug("%s: sk_X509_new_null failed for %s", __func__, file);
		goto done;
	}
	for (i = 0; i < sk_X509_INFO_num(xis); i++) {
		xi = sk_X509_INFO_value(xis, i);
		if (xi->x509) {
			if (!sk_X509_push(certs, xi->x509))
				goto done;
			xi->x509 = NULL;
		}
	}

 done:
	if (bio)
		BIO_free(bio);
	if (xis)
		sk_X509_INFO_pop_free(xis, X509_INFO_free);
	if (certs && sk_X509_num(certs) <= 0) {
		sk_X509_pop_free(certs, X509_free);
		certs = NULL;
	}
	return (certs);
}