Exemplo n.º 1
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;
	}
Exemplo n.º 2
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;
}
Exemplo n.º 3
0
static VALUE
ossl_ocspreq_sign(int argc, VALUE *argv, VALUE self)
{
    VALUE signer_cert, signer_key, certs, flags;
    OCSP_REQUEST *req;
    X509 *signer;
    EVP_PKEY *key;
    STACK_OF(X509) *x509s;
    unsigned long flg;
    int ret;

    rb_scan_args(argc, argv, "22", &signer_cert, &signer_key, &certs, &flags);
    signer = GetX509CertPtr(signer_cert);
    key = GetPrivPKeyPtr(signer_key);
    flg = NIL_P(flags) ? 0 : NUM2INT(flags);
    if(NIL_P(certs)){
	x509s = sk_X509_new_null();
	flags |= OCSP_NOCERTS;
    }
    else x509s = ossl_x509_ary2sk(certs);
    GetOCSPReq(self, req);
    ret = OCSP_request_sign(req, signer, key, EVP_sha1(), x509s, flg);
    sk_X509_pop_free(x509s, X509_free);
    if(!ret) ossl_raise(eOCSPError, NULL);

    return self;
}
Exemplo n.º 4
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;
            }
            X509_up_ref(cch->d.certificate);
        }
    }
    return certs;

}
Exemplo n.º 5
0
static VALUE
ossl_ocspbres_sign(int argc, VALUE *argv, VALUE self)
{
    VALUE signer_cert, signer_key, certs, flags;
    OCSP_BASICRESP *bs;
    X509 *signer;
    EVP_PKEY *key;
    STACK_OF(X509) *x509s;
    unsigned long flg;
    int ret;

    rb_scan_args(argc, argv, "22", &signer_cert, &signer_key, &certs, &flags);
    signer = GetX509CertPtr(signer_cert);
    key = GetPrivPKeyPtr(signer_key);
    flg = NIL_P(flags) ? 0 : NUM2INT(flags);
    if(NIL_P(certs)){
	x509s = sk_X509_new_null();
	flg |= OCSP_NOCERTS;
    }
    else{
	x509s = ossl_x509_ary2sk(certs);
    }
    GetOCSPBasicRes(self, bs);
    ret = OCSP_basic_sign(bs, signer, key, EVP_sha1(), x509s, flg);
    sk_X509_pop_free(x509s, X509_free);
    if(!ret) ossl_raise(eOCSPError, NULL);

    return self;
}
Exemplo n.º 6
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)
        fprintf(stderr, "unable to load certificates: %s\n", file);
    sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
    BIO_free(certs);
    return othercerts;
}
Exemplo n.º 7
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);
}
Exemplo n.º 8
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();
	CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509);
	sk_X509_push(*sk,x509);
	return(1);
	}
Exemplo n.º 9
0
pki_pkcs12::pki_pkcs12(const QString fname, pem_password_cb *cb)
	:pki_base(fname)
{
	FILE *fp;
	char pass[MAX_PASS_LENGTH];
	EVP_PKEY *mykey = NULL;
	X509 *mycert = NULL;
	key=NULL; cert=NULL;
	passcb = cb;
	class_name="pki_pkcs12";
	certstack = sk_X509_new_null();
	pass_info p(XCA_TITLE, tr("Please enter the password to decrypt the PKCS#12 file.")
		+ "\n'" + fname + "'");
	fp = fopen(QString2filename(fname), "rb");
	if (fp) {
		PKCS12 *pkcs12 = d2i_PKCS12_fp(fp, NULL);
		fclose(fp);
		if (ign_openssl_error()) {
			if (pkcs12)
				PKCS12_free(pkcs12);
			throw errorEx(tr("Unable to load the PKCS#12 (pfx) file %1.").arg(fname));
		}
		if (PKCS12_verify_mac(pkcs12, "", 0) || PKCS12_verify_mac(pkcs12, NULL, 0))
			pass[0] = '\0';
		else if (passcb(pass, MAX_PASS_LENGTH, 0, &p) < 0) {
			/* cancel pressed */
			PKCS12_free(pkcs12);
			throw errorEx("","");
		}
		PKCS12_parse(pkcs12, pass, &mykey, &mycert, &certstack);
		int error = ERR_peek_error();
		if (ERR_GET_REASON(error) == PKCS12_R_MAC_VERIFY_FAILURE) {
			ign_openssl_error();
			PKCS12_free(pkcs12);
			throw errorEx(getClassName(), tr("The supplied password was wrong (%1)").arg(ERR_reason_error_string(error)));
		}
		ign_openssl_error();
		if (mycert) {
			if (mycert->aux && mycert->aux->alias) {
				alias = asn1ToQString(mycert->aux->alias);
				alias = QString::fromUtf8(alias.toAscii());
			}
			cert = new pki_x509(mycert);
			if (alias.isEmpty()) {
				cert->autoIntName();
			} else {
				cert->setIntName(alias);
			}
			alias = cert->getIntName();
		}
		if (mykey) {
			key = new pki_evp(mykey);
			key->setIntName(alias + "_key");
			key->bogusEncryptKey();
		}
		PKCS12_free(pkcs12);
	} else
		fopen_error(fname);
}
Exemplo n.º 10
0
ZCertificateChain *
z_certificate_chain_new(void)
{
  ZCertificateChain *self = Z_NEW_COMPAT(Z_CLASS(ZCertificateChain), ZCertificateChain);

  self->chain = sk_X509_new_null();

  return self;
}
Exemplo n.º 11
0
pki_pkcs12::pki_pkcs12(const QString d, pki_x509 *acert, pki_evp *akey)
	:pki_base(d)
{
	class_name="pki_pkcs12";
	key = new pki_evp(akey);
	cert = new pki_x509(acert);
	certstack = sk_X509_new_null();
	openssl_error();
}
Exemplo n.º 12
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;
	}
Exemplo n.º 13
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;
}
Exemplo n.º 14
0
static int
lka_X509_verify(struct ca_vrfy_req_msg *vrfy,
                const char *CAfile, const char *CRLfile)
{
    X509			*x509;
    X509			*x509_tmp;
    X509			*x509_tmp2;
    STACK_OF(X509)		*x509_chain;
    const unsigned char    	*d2i;
    size_t			i;
    int			ret = 0;
    const char		*errstr;

    x509 = NULL;
    x509_tmp = NULL;
    x509_chain = NULL;

    d2i = vrfy->cert;
    if (d2i_X509(&x509, &d2i, vrfy->cert_len) == NULL) {
        x509 = NULL;
        goto end;
    }

    if (vrfy->n_chain) {
        x509_chain = sk_X509_new_null();
        for (i = 0; i < vrfy->n_chain; ++i) {
            d2i = vrfy->chain_cert[i];
            if (d2i_X509(&x509_tmp, &d2i, vrfy->chain_cert_len[i]) == NULL) {
                x509_tmp = NULL;
                goto end;
            }

            if ((x509_tmp2 = X509_dup(x509_tmp)) == NULL)
                goto end;
            sk_X509_insert(x509_chain, x509_tmp2, i);
            x509_tmp = x509_tmp2 = NULL;
        }
    }
    if (! ca_X509_verify(x509, x509_chain, CAfile, NULL, &errstr))
        log_debug("debug: lka: X509 verify: %s", errstr);
    else
        ret = 1;

end:
    if (x509)
        X509_free(x509);
    if (x509_tmp)
        X509_free(x509_tmp);
    if (x509_chain)
        sk_X509_pop_free(x509_chain, X509_free);

    return ret;
}
Exemplo n.º 15
0
MonoBtlsX509Chain *
mono_btls_x509_chain_new (void)
{
	MonoBtlsX509Chain *chain = (MonoBtlsX509Chain *)OPENSSL_malloc (sizeof (MonoBtlsX509Chain));
	if (chain == NULL)
		return NULL;

	memset(chain, 0, sizeof(MonoBtlsX509Chain));
	chain->certs = sk_X509_new_null ();
	chain->references = 1;
	return chain;
}
Exemplo n.º 16
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;
}
Exemplo n.º 17
0
// 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;
}
Exemplo n.º 18
0
opts_t *
opts_new(void)
{
	opts_t *opts;

	opts = malloc(sizeof(opts_t));
	memset(opts, 0, sizeof(opts_t));

	opts->sslcomp = 1;
	opts->chain = sk_X509_new_null();

	return opts;
}
Exemplo n.º 19
0
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;
}
/**
 * This function initializes a globus_gsi_callback_data_t.
 * @ingroup globus_gsi_callback_data
 *
 * @param callback_data
 *        Reference to the structure to be initialized
 *
 * @return
 *        GLOBUS_SUCCESS unless an error occurred, in which case, 
 *        a globus error object ID is returned
 */
globus_result_t
globus_gsi_callback_data_init(
    globus_gsi_callback_data_t *        callback_data)
{
    globus_result_t                     result = GLOBUS_SUCCESS;
    static char *                       _function_name_ =
        "globus_gsi_callback_data_init";

    GLOBUS_I_GSI_CALLBACK_DEBUG_ENTER;

    if(callback_data == NULL)
    {
        GLOBUS_GSI_CALLBACK_ERROR_RESULT(
            result,
            GLOBUS_GSI_CALLBACK_ERROR_CALLBACK_DATA,
            (_CLS("NULL pointer to callback_data passed to function: %s"),
             _function_name_));
        goto exit;
    }

    *callback_data = malloc(sizeof(globus_i_gsi_callback_data_t));
    if(*callback_data == NULL)
    {
        result = globus_error_put(
            globus_error_wrap_errno_error(
                GLOBUS_GSI_CALLBACK_MODULE,
                errno,
                GLOBUS_GSI_CALLBACK_ERROR_ERRNO,
                __FILE__,
                _function_name_,
                __LINE__,
                "Error allocating space (malloc) for callback data"));
        goto exit;
    }

    memset(*callback_data, 0, sizeof(globus_i_gsi_callback_data_t));

    (*callback_data)->max_proxy_depth = -1;
    
    (*callback_data)->cert_type = GLOBUS_GSI_CERT_UTILS_TYPE_EEC;

    (*callback_data)->cert_chain = sk_X509_new_null();

    (*callback_data)->error = GLOBUS_SUCCESS;

    (*callback_data)->check_self_signed_policy = GLOBUS_FALSE;

 exit:
    GLOBUS_I_GSI_CALLBACK_DEBUG_EXIT;
    return result;
}
Exemplo n.º 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;
}
Exemplo n.º 22
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);
}
Exemplo n.º 23
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;
	}
Exemplo n.º 24
0
int s2n_x509_validator_init(struct s2n_x509_validator *validator, struct s2n_x509_trust_store *trust_store, uint8_t check_ocsp) {
    notnull_check(trust_store);
    validator->trust_store = trust_store;

    validator->skip_cert_validation = 0;
    validator->check_stapled_ocsp = check_ocsp;
    validator->max_chain_depth = DEFAULT_MAX_CHAIN_DEPTH;

    validator->cert_chain = NULL;
    if (validator->trust_store->trust_store) {
        validator->cert_chain = sk_X509_new_null();
    }

    return 0;
}
Exemplo n.º 25
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;
}
Exemplo n.º 26
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;
}
Exemplo n.º 27
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;
}
Exemplo n.º 28
0
int
myproxy_ocsp_set_responder_cert(const char *path) {
    BIO *    in = NULL;
    X509 *   x  = NULL;
    int      count;
    int      rval = -1;

	sk_X509_pop_free(responder_cert, X509_free);
    responder_cert = NULL;

    in = BIO_new(BIO_s_file_internal());
    if (in == NULL || BIO_read_filename(in, path) <= 0) {
        verror_put_string("error reading %s", path);
        goto exit;
    }
    responder_cert = sk_X509_new_null();
    if (!responder_cert) {
        verror_put_string("sk_X509_new_null() failed in "
                          "myproxy_ocsp_set_responder_cert()");
        goto exit;
    }
    for (count = 0; ; count++) {
        x = PEM_read_bio_X509(in, NULL, NULL, NULL);
        if (x == NULL) {
            if ((ERR_GET_REASON(ERR_peek_error()) ==
                 PEM_R_NO_START_LINE) && (count > 0)) {
                ERR_clear_error();
                break;
            } else {
                verror_put_string("error reading %s", path);
                goto exit;
            }
        }
        sk_X509_insert(responder_cert,x,sk_X509_num(responder_cert));
        x = NULL;
    }

    rval = 0;                   /* success */

 exit:
    if (in) BIO_free_all(in);
    if (x)  X509_free(x);

    return rval;
}
Exemplo n.º 29
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;
}
Exemplo n.º 30
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;  
}