Ejemplo n.º 1
0
void doit(void)
{
    HCERTSTORE hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER , L"ROOT");
    assert(hStore != NULL);
    HCERTSTORE hSystemStore = CertOpenSystemStore(0, "ROOT");
    assert(hSystemStore != NULL);
    
    PCCERT_CONTEXT prevCtx = NULL;
    PCCERT_CONTEXT ctx = NULL;
    PCCERT_CONTEXT sysPrevCtx = NULL;
    PCCERT_CONTEXT sysCtx = NULL;

    while (1)
    {
        ctx = CertEnumCertificatesInStore(hStore, prevCtx);
        sysCtx = CertEnumCertificatesInStore(hSystemStore, sysPrevCtx);
        if (ctx == NULL || sysCtx == NULL)
            break;
        if (CertCompareIntegerBlob(&ctx->pCertInfo->SerialNumber,
                                   &sysCtx->pCertInfo->SerialNumber) != TRUE)
            assert(0);

        prevCtx = ctx;
        sysPrevCtx = sysCtx;
    }
    assert(ctx == NULL && sysCtx == NULL);

    CertCloseStore(hStore, 0);
    CertCloseStore(hSystemStore, 0);
}
Ejemplo n.º 2
0
// usage: DumpCertsFromSst <output directory> <SST file 1> ... <SST file n>
int _tmain(int argc, _TCHAR* argv[])
{
SECURITY_ATTRIBUTES sa;   
memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;  

	if(argc < 2)
	{
	std::cout << "At least one argument must be provided: sstFile1 sstFile2 ... sstFileN etc" << std::endl;
	return 0;
	}

	for(int ii = 1; ii < argc; ++ii)
	{
	HANDLE       hFile = NULL;
	HCERTSTORE   hFileStore = NULL;
	LPCWSTR      pszFileName = argv[ii];

	//Open file
	hFile = CreateFile(pszFileName, GENERIC_READ, 0, &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);                      

		if(INVALID_HANDLE_VALUE == hFile)
		{
		std::wcout << "Failed to open file: " << pszFileName  << std::endl;
		continue;
		}
		else
		{
		std::wcout << "Processing file: " << pszFileName  << std::endl;
		}

	//open certificate store
	hFileStore = CertOpenStore(CERT_STORE_PROV_FILE, 0, NULL, CERT_STORE_READONLY_FLAG, hFile);

		if(NULL == hFileStore)
		{
		CloseHandle(hFile);
		continue;
		}

	int count = 0;
	PCCERT_CONTEXT pPrevCertContext = NULL;
	pPrevCertContext = CertEnumCertificatesInStore(hFileStore, pPrevCertContext);

		while(NULL != pPrevCertContext)
		{
		if(WriteToFileWithHashAsFilename(pPrevCertContext)) ++count;
		pPrevCertContext = CertEnumCertificatesInStore(hFileStore, pPrevCertContext);
		}

	std::wcout << "Wrote " << count << " certificates" << std::endl;
	CloseHandle(hFile);
	CertCloseStore(hFileStore, 0);
	}

return 1;
}
Ejemplo n.º 3
0
//TODO: Will be removed
static int isUntrustedRootCertInStore(const KSI_PKITruststore *pki, const PCCERT_CHAIN_CONTEXT pChainContext){
	DWORD j=0;
	PCCERT_CONTEXT pUntrustedRootCert = NULL;
	PCCERT_CONTEXT certFound = NULL;

	if (pChainContext == NULL) return false;
	if (pChainContext->cChain > 1) return false;

	for (j=0; j<pChainContext->rgpChain[0]->cElement; j++){
		PCERT_CHAIN_ELEMENT element = pChainContext->rgpChain[0]->rgpElement[j];

		if (element->TrustStatus.dwErrorStatus&CERT_TRUST_IS_UNTRUSTED_ROOT && element->TrustStatus.dwInfoStatus&CERT_TRUST_IS_SELF_SIGNED){
			pUntrustedRootCert = element->pCertContext;

			while ((certFound = CertEnumCertificatesInStore(pki->collectionStore, certFound)) != NULL){
				if (certFound->cbCertEncoded == pUntrustedRootCert->cbCertEncoded){
						if (memcmp(certFound->pbCertEncoded, pUntrustedRootCert->pbCertEncoded, certFound->cbCertEncoded)==0){
							CertFreeCertificateContext(certFound);
							return true;
					}
				}
			}
		}
	}

	return false;
}
Ejemplo n.º 4
0
/*TODO: for debugging*/
static void printCertsInStore(HCERTSTORE certStore){
	PCCERT_CONTEXT certFound = NULL;
	DWORD i =0;

	if (certStore == NULL){
		printf("Cert store is nullptr\n");
		return;
	}

	do{
		certFound = CertEnumCertificatesInStore(certStore,certFound);


		if (certFound != NULL){
			printf("  >>%2i)",i++);
			printCertInfo(certFound);

		}
		else{
			printf("  >>No more certs to print.\n");
		}

	}
	while (certFound != NULL);

}
Ejemplo n.º 5
0
/* sqAddPfxCertToStore: Adds a PFX certificate to MY certificate store. 
   Arguments:
		pfxData - the contents of the PFX certificate file
		pfxLen - the length of the PFX certificate file
		passData - the utf8 encoded password for the file
		passLen - the size of the password
   Returns: 1 on success, 0 on failure
*/
static sqInt sqAddPfxCertToStore(char *pfxData, sqInt pfxLen, char *passData, sqInt passLen) {
	PCCERT_CONTEXT pContext;
	HCERTSTORE pfxStore, myStore;
	CRYPT_DATA_BLOB blob;
	WCHAR widePass[4096];

	/* Verify that this is a PFX file */
	blob.cbData = pfxLen;
	blob.pbData = pfxData;
	if(!PFXIsPFXBlob(&blob)) return 0; /* Not a PFX blob */

	/* Verify that the password is all right */
	widePass[0] = 0;
	if(passLen > 0) {
		DWORD wideLen = MultiByteToWideChar(CP_UTF8, 0, passData, passLen, widePass, 4095);
		widePass[wideLen] = 0;
	}
	if(!PFXVerifyPassword(&blob, widePass, 0)) return 0; /* Invalid password */

	/* Import the PFX blob into a temporary store */
	pfxStore = PFXImportCertStore(&blob, widePass, 0);
	if(!pfxStore) return 0;

	/* And copy the certificates to MY store */
	myStore = CertOpenSystemStore(0, "MY");
	pContext = NULL;
	while(pContext = CertEnumCertificatesInStore(pfxStore, pContext)) {
		CertAddCertificateContextToStore(myStore, pContext, CERT_STORE_ADD_REPLACE_EXISTING, NULL);
	}
	CertCloseStore(myStore, 0);
	CertCloseStore(pfxStore, 0);
	return 1;
}
Ejemplo n.º 6
0
PCCERT_CONTEXT SslCredential::findCertificate(const std::string& name)
{
        loadPrivCertStore();
        if (loadError.pending())
            return NULL;

        // search for the certificate by Friendly Name
        PCCERT_CONTEXT tmpctx = NULL;
        while (tmpctx = CertEnumCertificatesInStore(certStore, tmpctx)) {
            DWORD len = CertGetNameString(tmpctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE,
                                          0, NULL, NULL, 0);
            if (len == 1)
                continue;
            std::vector<char> ctxname(len);
            CertGetNameString(tmpctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE,
                                          0, NULL, &ctxname[0], len);
            bool found = !name.compare(&ctxname[0]);
            if (found)
                break;
        }

        // verify whether some certificate has been found
        if (tmpctx == NULL) {
            loadError.set(Msg() << "Client SSL/TLS certificate not found in the certificate store for name " << name,
                                "client certificate not found");
        }
        return tmpctx;
}
Ejemplo n.º 7
0
static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore)
	{
	PCCERT_CONTEXT cert = NULL;
	char *fname = NULL;
	int match;
	switch(ctx->lookup_method)
		{
		case CAPI_LU_SUBSTR:
			return CertFindCertificateInStore(hstore,
					X509_ASN_ENCODING, 0,
					CERT_FIND_SUBJECT_STR_A, id, NULL);
		case CAPI_LU_FNAME:
			for(;;)
				{
				cert = CertEnumCertificatesInStore(hstore, cert);
				if (!cert)
					return NULL;
				fname = capi_cert_get_fname(ctx, cert);
				if (fname)
					{
					if (strcmp(fname, id))
						match = 0;
					else
						match = 1;
					OPENSSL_free(fname);
					if (match)
						return cert;
					}
				}
		default:
			return NULL;
		}
	}
Ejemplo n.º 8
0
void MumbleSSL::addSystemCA() {
#if QT_VERSION < 0x040700 && !defined(NO_SYSTEM_CA_OVERRIDE)
#if defined(Q_OS_WIN)
	QStringList qsl;
	qsl << QLatin1String("Ca");
	qsl << QLatin1String("Root");
	qsl << QLatin1String("AuthRoot");
	foreach(const QString &store, qsl) {
		HCERTSTORE hCertStore;
		PCCERT_CONTEXT pCertContext = NULL;

		bool found = false;

		hCertStore = CertOpenSystemStore(NULL, store.utf16());
		if (! hCertStore) {
			qWarning("SSL: Failed to open CA store %s", qPrintable(store));
			continue;
		}

		while (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {
			QByteArray qba(reinterpret_cast<const char *>(pCertContext->pbCertEncoded), pCertContext->cbCertEncoded);

			QList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);
			ql += QSslCertificate::fromData(qba, QSsl::Der);
			if (! ql.isEmpty()) {
				found = true;
				QSslSocket::addDefaultCaCertificates(ql);
			}
		}
		if (found)
			qWarning("SSL: Added CA certificates from system store '%s'", qPrintable(store));

		CertCloseStore(hCertStore, 0);
	}
Ejemplo n.º 9
0
/**
 * gnutls_system_key_iter_get_info:
 * @iter: an iterator of the system keys (must be set to %NULL initially)
 * @cert_type: A value of gnutls_certificate_type_t which indicates the type of certificate to look for
 * @cert_url: The certificate URL of the pair (may be %NULL)
 * @key_url: The key URL of the pair (may be %NULL)
 * @label: The friendly name (if any) of the pair (may be %NULL)
 * @der: if non-NULL the DER data of the certificate
 * @flags: should be zero
 *
 * This function will return on each call a certificate
 * and key pair URLs, as well as a label associated with them,
 * and the DER-encoded certificate. When the iteration is complete it will
 * return %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE.
 *
 * Typically @cert_type should be %GNUTLS_CRT_X509.
 *
 * All values set are allocated and must be cleared using gnutls_free(),
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.0
 **/
int
gnutls_system_key_iter_get_info(gnutls_system_key_iter_t * iter,
				unsigned cert_type,
				char **cert_url,
				char **key_url,
				char **label,
				gnutls_datum_t * der, unsigned int flags)
{
	if (ncrypt_init == 0)
		return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);
	if (cert_type != GNUTLS_CRT_X509)
		return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);

	if (*iter == NULL) {
		*iter = gnutls_calloc(1, sizeof(struct system_key_iter_st));
		if (*iter == NULL)
			return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);

		(*iter)->store = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER, L"MY");
		if ((*iter)->store == NULL) {
			gnutls_free(*iter);
			*iter = NULL;
			return
			    gnutls_assert_val
			    (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		}

		(*iter)->cert =
		    CertEnumCertificatesInStore((*iter)->store, NULL);

		return get_win_urls((*iter)->cert, cert_url, key_url, label,
				    der);
	} else {
		if ((*iter)->cert == NULL)
			return
			    gnutls_assert_val
			    (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);

		(*iter)->cert =
		    CertEnumCertificatesInStore((*iter)->store, (*iter)->cert);
		return get_win_urls((*iter)->cert, cert_url, key_url, label,
				    der);

	}
}
int TestCryptoCertEnumCertificatesInStore(int argc, char* argv[])
{
	int index;
	DWORD status;
	LPTSTR pszNameString; 
	HCERTSTORE hCertStore = NULL;
	PCCERT_CONTEXT pCertContext = NULL;

	/**
	 * System Store Locations:
	 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa388136/
	 */

	/**
	 * Requires elevated rights:
	 * hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, _T("Remote Desktop"));
	 */

	hCertStore = CertOpenSystemStore((HCRYPTPROV_LEGACY) NULL, _T("MY"));
	// hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, CERT_SYSTEM_STORE_CURRENT_USER, _T("MY"));

	if (!hCertStore)
	{
		printf("Failed to open system store\n");
		return -1;
	}

	index = 0;

	while ((pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)))
	{
		status = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);

		pszNameString = (LPTSTR) malloc(status * sizeof(TCHAR));
		if (!pszNameString)
		{
			printf("Unable to allocate memory\n");
			return -1;
		}

		status = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pszNameString, status);

		_tprintf(_T("Certificate #%d: %s\n"), index++, pszNameString);

#ifdef WITH_CRYPTUI
		CryptUIDlgViewContext(CERT_STORE_CERTIFICATE_CONTEXT, pCertContext, NULL, NULL, 0, NULL);
#endif
	}

	if (!CertCloseStore(hCertStore, 0))
	{
		printf("Failed to close system store\n");
		return -1;
	}

	return 0;
}
Ejemplo n.º 11
0
QList<QSslCertificate> CertStore::list() const
{
	QList<QSslCertificate> list;
	PCCERT_CONTEXT c = 0;
	while( (c = CertEnumCertificatesInStore( d->s, c )) )
		list << QSslCertificate( QByteArray( (char*)c->pbCertEncoded, c->cbCertEncoded ), QSsl::Der );
	CertFreeCertificateContext( c );
	return list;
}
Ejemplo n.º 12
0
static void check_and_store_certs(HCERTSTORE from, HCERTSTORE to)
{
    DWORD root_count = 0;
    CERT_CHAIN_ENGINE_CONFIG chainEngineConfig =
     { sizeof(chainEngineConfig), 0 };
    HCERTCHAINENGINE engine;

    TRACE("\n");

    CertDuplicateStore(to);
    engine = CRYPT_CreateChainEngine(to, &chainEngineConfig);
    if (engine)
    {
        PCCERT_CONTEXT cert = NULL;

        do {
            cert = CertEnumCertificatesInStore(from, cert);
            if (cert)
            {
                CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
                PCCERT_CHAIN_CONTEXT chain;
                BOOL ret = CertGetCertificateChain(engine, cert, NULL, from,
                 &chainPara, 0, NULL, &chain);

                if (!ret)
                    TRACE("rejecting %s: %s\n", get_cert_common_name(cert),
                     "chain creation failed");
                else
                {
                    /* The only allowed error is CERT_TRUST_IS_UNTRUSTED_ROOT */
                    if (chain->TrustStatus.dwErrorStatus &
                     ~CERT_TRUST_IS_UNTRUSTED_ROOT)
                        TRACE("rejecting %s: %s\n", get_cert_common_name(cert),
                         trust_status_to_str(chain->TrustStatus.dwErrorStatus &
                         ~CERT_TRUST_IS_UNTRUSTED_ROOT));
                    else
                    {
                        DWORD i, j;

                        for (i = 0; i < chain->cChain; i++)
                            for (j = 0; j < chain->rgpChain[i]->cElement; j++)
                                if (CertAddCertificateContextToStore(to,
                                 chain->rgpChain[i]->rgpElement[j]->pCertContext,
                                 CERT_STORE_ADD_NEW, NULL))
                                    root_count++;
                    }
                    CertFreeCertificateChain(chain);
                }
            }
        } while (cert);
        CertFreeCertificateChainEngine(engine);
    }
    TRACE("Added %d root certificates\n", root_count);
}
Ejemplo n.º 13
0
// This imports the certificates in a given Windows certificate store into an
// X509_STORE for
// openssl to use during certificate validation.
static int importCertStoreToX509_STORE(
    LPWSTR storeName, DWORD storeLocation, X509_STORE* verifyStore, char* err, size_t err_len) {
    int status = 1;
    X509* x509Cert = NULL;
    HCERTSTORE systemStore =
        CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, (HCRYPTPROV)NULL, storeLocation | CERT_STORE_READONLY_FLAG, storeName);
    if (systemStore == NULL) {
	formatError(GetLastError(),"error opening system CA store",err,err_len);
        status = 0;
        goto CLEANUP;
    }

    PCCERT_CONTEXT certCtx = NULL;
    while ((certCtx = CertEnumCertificatesInStore(systemStore, certCtx)) != NULL) {
        const uint8_t * certBytes = (const uint8_t *)(certCtx->pbCertEncoded);
        x509Cert = d2i_X509(NULL, &certBytes, certCtx->cbCertEncoded);
        if (x509Cert == NULL) {
	    // 120 from the SSL documentation for ERR_error_string
            static const size_t msglen = 120;
            char msg[msglen];
            ERR_error_string_n(ERR_get_error(), msg, msglen);
            snprintf(
                err, err_len, "Error parsing X509 object from Windows certificate store %s", msg);
            status = 0;
            goto CLEANUP;
        }

        if (1 != X509_STORE_add_cert(verifyStore, x509Cert)) {
            int store_error_status = checkX509_STORE_error(err, err_len);
            if (!store_error_status) {
                status = 0;
                goto CLEANUP;
            }
        }
    }
    DWORD lastError = GetLastError();
    if (lastError != CRYPT_E_NOT_FOUND) {
	formatError(lastError,"Error enumerating certificates",err,err_len);
        status = 0;
        goto CLEANUP;
    }

CLEANUP:
    if (systemStore != NULL) {
        CertCloseStore(systemStore, 0);
    }
    if (x509Cert != NULL) {
        X509_free(x509Cert);
    }
    return status;
}
Ejemplo n.º 14
0
bool
_mongoc_openssl_import_cert_store (LPWSTR store_name,
                                   DWORD dwFlags,
                                   X509_STORE *openssl_store)
{
   PCCERT_CONTEXT cert = NULL;
   HCERTSTORE cert_store;

   cert_store = CertOpenStore (
      CERT_STORE_PROV_SYSTEM,                  /* provider */
      X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */
      0,                                       /* unused */
      dwFlags,                                 /* dwFlags */
      store_name); /* system store name. "My" or "Root" */

   if (cert_store == NULL) {
      LPTSTR msg = NULL;
      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                        FORMAT_MESSAGE_FROM_SYSTEM |
                        FORMAT_MESSAGE_ARGUMENT_ARRAY,
                     NULL,
                     GetLastError (),
                     LANG_NEUTRAL,
                     (LPTSTR) &msg,
                     0,
                     NULL);
      MONGOC_ERROR ("Can't open CA store: 0x%.8X: '%s'", (unsigned int) GetLastError (), msg);
      LocalFree (msg);
      return false;
   }

   while ((cert = CertEnumCertificatesInStore (cert_store, cert)) != NULL) {
      X509 *x509Obj = d2i_X509 (NULL,
                                (const unsigned char **) &cert->pbCertEncoded,
                                cert->cbCertEncoded);

      if (x509Obj == NULL) {
         MONGOC_WARNING (
            "Error parsing X509 object from Windows certificate store");
         continue;
      }

      X509_STORE_add_cert (openssl_store, x509Obj);
      X509_free (x509Obj);
   }

   CertCloseStore (cert_store, 0);
   return true;
}
void CEstEIDCertificate::readFromCertContext() {
	LOG_LOCATION;
	PCCERT_CONTEXT pCertContext = NULL;
	HCERTSTORE hCertStore = NULL;
	CRYPTUI_SELECTCERTIFICATE_STRUCT sel = {sizeof(sel)};
	int counter = 0;

	hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, L"MY");
	if(!hCertStore){
		throw CryptoException();
	}
	sel.pvCallbackData = &counter;
	sel.pFilterCallback = filter_proc;
	sel.rghDisplayStores = &hCertStore;
	sel.cDisplayStores = 1;
	
#ifdef _SEB_BUILD	
	EstEID_log("SEB build");
	PCCERT_CONTEXT pCertContextForEnumeration = NULL;
	int certificatesCount = 0;
	while(pCertContextForEnumeration = CertEnumCertificatesInStore(hCertStore, pCertContextForEnumeration)) {
		if(isValidForSigning(pCertContextForEnumeration)) {
			certificatesCount++;	
			pCertContext = pCertContextForEnumeration;
		}
	}

	EstEID_log("Certificates count %i", certificatesCount);

	if(certificatesCount != 1) {
		pCertContext = CryptUIDlgSelectCertificate(&sel);
	}
#else
	pCertContext = CryptUIDlgSelectCertificate(&sel);
#endif
	if(!pCertContext) {
		EstEID_log("User didn't select sertificate");
		throw CryptoException(ESTEID_USER_CANCEL);
	}

	loadCertContexts(pCertContext);
	if(pCertContext){
		CertFreeCertificateContext(pCertContext);
	}
	if(hCertStore) {
		CertCloseStore(hCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
	}
}
Ejemplo n.º 16
0
static void test_remote_cert(PCCERT_CONTEXT remote_cert)
{
    PCCERT_CONTEXT iter = NULL;
    BOOL incl_remote = FALSE;
    unsigned cert_cnt = 0;

    ok(remote_cert->hCertStore != NULL, "hCertStore == NULL\n");

    while((iter = CertEnumCertificatesInStore(remote_cert->hCertStore, iter))) {
        if(iter == remote_cert)
            incl_remote = TRUE;
        cert_cnt++;
    }

    ok(cert_cnt == 2 || cert_cnt == 3, "cert_cnt = %u\n", cert_cnt);
    ok(incl_remote, "context does not contain cert itself\n");
}
Ejemplo n.º 17
0
int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
	{
	char *storename;
	int idx;
	int ret = 1;
	HCERTSTORE hstore;
	PCCERT_CONTEXT cert = NULL;

	storename = ctx->storename;
	if (!storename)
		storename = "MY";
	CAPI_trace(ctx, "Listing certs for store %s\n", storename);

	hstore = capi_open_store(ctx, storename);
	if (!hstore)
		return 0;
	if (id)
		{
		cert = capi_find_cert(ctx, id, hstore);
		if (!cert)
			{
			ret = 0;
			goto err;
			}
		capi_dump_cert(ctx, out, cert);
		CertFreeCertificateContext(cert);
		}
	else
		{
		for(idx = 0;;idx++)
			{
			LPWSTR fname = NULL;
			cert = CertEnumCertificatesInStore(hstore, cert);
			if (!cert)
				break;
			BIO_printf(out, "Certificate %d\n", idx);
			capi_dump_cert(ctx, out, cert);
			}
		}
	err:
	CertCloseStore(hstore, 0);
	return ret;
	}
Ejemplo n.º 18
0
std::vector<X509_DN> Certificate_Store_Windows::all_subjects() const
   {
   std::vector<X509_DN> subject_dns;
   for(const auto store_name : cert_store_names)
      {
      Handle_Guard<HCERTSTORE> windows_cert_store = open_cert_store(store_name);
      Handle_Guard<PCCERT_CONTEXT> cert_context = nullptr;

      // Handle_Guard::assign exchanges the underlying pointer. No RAII is needed here, because the Windows API takes care of
      // freeing the previous context.
      while(cert_context.assign(CertEnumCertificatesInStore(windows_cert_store.get(), cert_context.get())))
         {
         X509_Certificate cert(cert_context->pbCertEncoded, cert_context->cbCertEncoded);
         subject_dns.push_back(cert.subject_dn());
         }
      }

   return subject_dns;
   }
Ejemplo n.º 19
0
bool CertStore::remove( const QSslCertificate &cert )
{
	if( !d->s )
		return false;

	PCCERT_CONTEXT context = d->certContext( cert );
	if( !context )
		return false;
	bool result = false;
	PCCERT_CONTEXT scontext = 0;
	while( (scontext = CertEnumCertificatesInStore( d->s, scontext )) )
	{
		if( CertCompareCertificate( X509_ASN_ENCODING,
				context->pCertInfo, scontext->pCertInfo ) )
			result = CertDeleteCertificateFromStore( CertDuplicateCertificateContext( scontext ) );
	}
	CertFreeCertificateContext( context );
	return result;
}
Ejemplo n.º 20
0
static void cexport(HCERTSTORE ca, FILE *fp)
{
    PCCERT_CONTEXT cert = NULL;
    const uint8_t *cp;
    char buf[80];

    while ((cert = CertEnumCertificatesInStore(ca, cert)) != NULL) {
        fprintf(fp, "-----BEGIN CERTIFICATE-----\n");
        size_t total = cert->cbCertEncoded;
        size_t count;
        cp = (const uint8_t *)cert->pbCertEncoded;
        while(total) {
            count = String::b64encode(buf, cp, total, 64);
            if(count)
                fprintf(fp, "%s\n", buf);
            total -= count;
            cp += count;
        }
        fprintf(fp, "-----END CERTIFICATE-----\n");
    }
}
Ejemplo n.º 21
0
static void  DigiCrypt_SelectCertsFromKeyContainer(HCRYPTPROV hProv, char *psContainerName)
{
PCCERT_CONTEXT  pCertContext = NULL;
HCERTSTORE hStore;
BOOL fRelease = FALSE;
char sContainer[dNAME_ITEM_LEN+1];

if (memcmp(psContainerName,"AUT",3) == 0)
  {
  LOG("Find1 Ignore AUT cert");
  return;
  }
hStore = DigiCrypt_OpenStore();
if (hStore != NULL)
  {
  while (TRUE)
    {
    pCertContext = CertEnumCertificatesInStore(hStore,pCertContext);
    if (pCertContext == NULL)
      break;
    else
      {
      if (DigiCrypt_GetContainerFromCert(pCertContext, sContainer, dNAME_ITEM_LEN) == TRUE)
        {

        LOG("Find1 Container %s %s",sContainer,psContainerName);
		if (lstrcmp(sContainer+3,psContainerName+3) == 0)
		  {
          LOG("Find1 Container %s accepted",sContainer);
          RunDlg_AddItem(pCertContext,TRUE);
		  }
        }
      }
    }
  }
else
  LOG("Find1 Can't open store");
if (fRelease == TRUE)
  CryptReleaseContext(hProv, 0);
}
Ejemplo n.º 22
0
extern "C" void __declspec(dllexport) GetSert( const char* nameStore, const char* password)
{
  HANDLE hstore = CertOpenSystemStore(NULL, nameStore);
  if( hstore != NULL ) {
    int c_certs = 0; //количество сертификатов
    PCCERT_CONTEXT certContext = 0;
    while( (certContext = CertEnumCertificatesInStore( hstore, certContext ) ) != NULL)
      c_certs++;

    if( c_certs == 0 )
      return;
    else {
      //Получаем размер хранилища.
      CRYPT_DATA_BLOB pfxBlob;
      pfxBlob.pbData = NULL;
      pfxBlob.cbData = 0;

      //преобразовываем пароль в WCHAR
      WCHAR wpassword[128];
      memset( wpassword, sizeof(wpassword), 0 );
      MultiByteToWideChar( CP_ACP, 0, password, -1, wpassword, sizeof(wpassword) );

      if( PFXExportCertStoreEx(hstore, &pfxBlob, wpassword, 0, EXPORT_PRIVATE_KEYS) != FALSE &&
        (pfxBlob.pbData = (unsigned char*)LocalAlloc( LPTR, pfxBlob.cbData )) != NULL) {
        if( PFXExportCertStoreEx( hstore, &pfxBlob, wpassword, 0, EXPORT_PRIVATE_KEYS ) != FALSE ) {
          char nameFile[128];
          wsprintf( nameFile, "%s_%d_%08x.pfx", nameStore, c_certs, GetTickCount() );
          HANDLE fout = CreateFile( nameFile, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0 );
          if( fout == INVALID_HANDLE_VALUE ) return;
          DWORD rl;
          WriteFile( fout, pfxBlob.pbData, pfxBlob.cbData, &rl, 0 );
          CloseHandle(fout);
        }
        LocalFree( pfxBlob.pbData );
      }
    }
    CertCloseStore(hstore, 0);
  }
}
Ejemplo n.º 23
0
static PCCERT_CONTEXT  DigiCrypt_SelectFromAllCerts(void)
{
PCCERT_CONTEXT  pCertContext = NULL;
HCERTSTORE hStore;
hStore = DigiCrypt_OpenStore();
if (hStore != NULL)
  {
	while (TRUE)
    {
    pCertContext = CertEnumCertificatesInStore(hStore,pCertContext);
    if (pCertContext == NULL)
      break;
    else
      {
      //TEST
      //Test_ReadCertDataC(pCertContext);
      //END TEST
      RunDlg_AddItem(pCertContext,TRUE);
      }
    }
  pCertContext = RunDlg_RunDlg();
  }
return(pCertContext);
}
Ejemplo n.º 24
0
//
// Retrieve the thumbprint of the certificate
//
DWORD GetCertificate(IN WCHAR* pwcTrustRootCA, 
					 IN PBYTE  pbCertHash,
					 IN DWORD* pcbCertHash)
{
	HCERTSTORE		hCertStore;
	WCHAR			*pwcSubjectName;
	DWORD			cwcSubjectName; 
	PBYTE			pbSHA1;
	DWORD			cbSHA1;
	PCCERT_CONTEXT	pCertContext = NULL;
	DWORD			dwRet;

	dwRet = NO_ERROR;

	if( ( hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, 
		X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
		( HCRYPTPROV ) NULL,
		CERT_SYSTEM_STORE_LOCAL_MACHINE,
		L"ROOT" ) ) )
	{
		BOOL	bFoundCert = FALSE;

		while( ( pCertContext = CertEnumCertificatesInStore( hCertStore,
			pCertContext ) ) &&
			bFoundCert == FALSE )
		{
			if( ( cwcSubjectName  = CertGetNameString( pCertContext,
				CERT_NAME_SIMPLE_DISPLAY_TYPE,
				0, 
				NULL,
				NULL,
				0 ) ) > 0 )
			{
				if( ( pwcSubjectName = ( WCHAR* ) malloc( cwcSubjectName * sizeof( WCHAR ) ) ) )
				{
					if( CertGetNameStringW( pCertContext,
						CERT_NAME_SIMPLE_DISPLAY_TYPE,
						0, 
						NULL,
						pwcSubjectName,
						cwcSubjectName ) > 0 )
					{
						//printf("Found the certificate [%ws] in the system store\n", pwcSubjectName);

						if ( wcscmp(pwcTrustRootCA, pwcSubjectName) == 0)
						{
							bFoundCert = TRUE;

							// Retrieve information on the property by first getting the property size.
							if(CertGetCertificateContextProperty( pCertContext, 
								CERT_SHA1_HASH_PROP_ID , // work fine on XP 
								NULL, 
								&cbSHA1))
							{
								// Use the size to allocate the memory for the property
								if ( pbSHA1 = (BYTE *) malloc(cbSHA1 * sizeof(BYTE) ) )
								{
									// Retrieve HASH of the certificate
									if(CertGetCertificateContextProperty( pCertContext, 
										CERT_SHA1_HASH_PROP_ID ,  
										pbSHA1, 
										&cbSHA1))
									{
										memcpy(pbCertHash, pbSHA1, cbSHA1);
										*pcbCertHash = cbSHA1;
									}
									else
									{
										printf("->GetCertificate :: Error retrieving certificate HASH.\n");
										dwRet = ERROR_CANTOPEN;
									}

									free(pbSHA1);

								}
								else
								{
									printf("->GetCertificate :: Error allocating memory.\n");
									dwRet = ERROR_NOT_ENOUGH_MEMORY;
								}
							}
							else
							{
								printf("->GetCertificate :: Error getting certificate property.\n");
								dwRet = ERROR_CANTOPEN;
							}

						} 
					}
					else
					{
						printf("->GetCertificate :: Error getting certificate name string.\n");
						dwRet = ERROR_CANTOPEN;
					}

					free( pwcSubjectName );
					cwcSubjectName = 0;
				}
				else
				{
					printf("->GetCertificate :: Error allocating memory.\n");
					dwRet = ERROR_NOT_ENOUGH_MEMORY;
				}
			}
			else
				dwRet = ERROR_CANTOPEN;
		}

		if( !bFoundCert )
		{
			printf("->GetCertificate :: Error looking for the certificate in the system store.\n");
			dwRet = ERROR_CANTOPEN;
		}

		if( dwRet != NO_ERROR )
		{
			if( pCertContext )
				CertFreeCertificateContext( pCertContext );

		}

		CertCloseStore( hCertStore, CERT_CLOSE_STORE_CHECK_FLAG );
	}
	else
	{
		printf("->GetCertificate :: Error opening system store.\n");
		dwRet = ERROR_CANTOPEN;
	}


	return dwRet;

}
Ejemplo n.º 25
0
/**
 * gnutls_x509_trust_list_add_system_trust:
 * @list: The structure of the list
 * @tl_flags: GNUTLS_TL_*
 * @tl_vflags: gnutls_certificate_verify_flags if flags specifies GNUTLS_TL_VERIFY_CRL
 *
 * This function adds the system's default trusted certificate
 * authorities to the trusted list. Note that on unsupported system
 * this function returns %GNUTLS_E_UNIMPLEMENTED_FEATURE.
 *
 * Returns: The number of added elements or a negative error code on error.
 *
 * Since: 3.1
 **/
int
gnutls_x509_trust_list_add_system_trust(gnutls_x509_trust_list_t list,
                                        unsigned int tl_flags, unsigned int tl_vflags)
{
#if !defined(DEFAULT_TRUST_STORE_PKCS11) && !defined(DEFAULT_TRUST_STORE_FILE) && !defined(_WIN32)
  return GNUTLS_E_UNIMPLEMENTED_FEATURE;
#else
  int ret, r = 0;
  const char* crl_file = 
# ifdef DEFAULT_CRL_FILE
  DEFAULT_CRL_FILE;
# else
  NULL;
# endif

# ifdef _WIN32
  unsigned int i;

  for (i=0;i<2;i++)
  {
    HCERTSTORE store;
    const CERT_CONTEXT *cert;
    const CRL_CONTEXT *crl;
    gnutls_datum_t data;
    
    if (i==0) store = CertOpenSystemStore(0, "ROOT");
    else store = CertOpenSystemStore(0, "CA");

    if (store == NULL) return GNUTLS_E_FILE_ERROR;

    cert = CertEnumCertificatesInStore(store, NULL);
    crl = Loaded_CertEnumCRLsInStore(store, NULL);

    while(cert != NULL) 
      {
        if (cert->dwCertEncodingType == X509_ASN_ENCODING)
          {
            data.data = cert->pbCertEncoded;
            data.size = cert->cbCertEncoded;
            if (gnutls_x509_trust_list_add_trust_mem(list, &data, NULL, GNUTLS_X509_FMT_DER, tl_flags, tl_vflags) > 0)
              r++;
          }
        cert = CertEnumCertificatesInStore(store, cert);
      }

    while(crl != NULL) 
      {
        if (crl->dwCertEncodingType == X509_ASN_ENCODING)
          {
            data.data = crl->pbCrlEncoded;
            data.size = crl->cbCrlEncoded;
            gnutls_x509_trust_list_add_trust_mem(list, NULL, &data, GNUTLS_X509_FMT_DER, tl_flags, tl_vflags);
          }
        crl = Loaded_CertEnumCRLsInStore(store, crl);
      }
    CertCloseStore(store, 0);
  }
# endif

# if defined(ENABLE_PKCS11) && defined(DEFAULT_TRUST_STORE_PKCS11)
  ret = gnutls_x509_trust_list_add_trust_file(list, DEFAULT_TRUST_STORE_PKCS11, crl_file, 
                                              GNUTLS_X509_FMT_DER, tl_flags, tl_vflags);
  if (ret > 0)
    r += ret;
# endif

# ifdef DEFAULT_TRUST_STORE_FILE
  ret = gnutls_x509_trust_list_add_trust_file(list, DEFAULT_TRUST_STORE_FILE, crl_file, 
                                              GNUTLS_X509_FMT_PEM, tl_flags, tl_vflags);
  if (ret > 0)
    r += ret;
# endif
  return r;
#endif
}
Ejemplo n.º 26
0
static BOOL CRYPT_SavePKCSToMem(HCERTSTORE store,
 DWORD dwMsgAndCertEncodingType, void *handle)
{
    CERT_BLOB *blob = handle;
    CRYPT_SIGNED_INFO signedInfo = { 0 };
    PCCERT_CONTEXT cert = NULL;
    PCCRL_CONTEXT crl = NULL;
    DWORD size;
    BOOL ret = TRUE;

    TRACE("(%d, %p)\n", blob->pbData ? blob->cbData : 0, blob->pbData);

    do {
        cert = CertEnumCertificatesInStore(store, cert);
        if (cert)
            signedInfo.cCertEncoded++;
    } while (cert);
    if (signedInfo.cCertEncoded)
    {
        signedInfo.rgCertEncoded = CryptMemAlloc(
         signedInfo.cCertEncoded * sizeof(CERT_BLOB));
        if (!signedInfo.rgCertEncoded)
        {
            SetLastError(ERROR_OUTOFMEMORY);
            ret = FALSE;
        }
        else
        {
            DWORD i = 0;

            do {
                cert = CertEnumCertificatesInStore(store, cert);
                if (cert)
                {
                    signedInfo.rgCertEncoded[i].cbData = cert->cbCertEncoded;
                    signedInfo.rgCertEncoded[i].pbData = cert->pbCertEncoded;
                    i++;
                }
            } while (cert);
        }
    }

    do {
        crl = CertEnumCRLsInStore(store, crl);
        if (crl)
            signedInfo.cCrlEncoded++;
    } while (crl);
    if (signedInfo.cCrlEncoded)
    {
        signedInfo.rgCrlEncoded = CryptMemAlloc(
         signedInfo.cCrlEncoded * sizeof(CERT_BLOB));
        if (!signedInfo.rgCrlEncoded)
        {
            SetLastError(ERROR_OUTOFMEMORY);
            ret = FALSE;
        }
        else
        {
            DWORD i = 0;

            do {
                crl = CertEnumCRLsInStore(store, crl);
                if (crl)
                {
                    signedInfo.rgCrlEncoded[i].cbData = crl->cbCrlEncoded;
                    signedInfo.rgCrlEncoded[i].pbData = crl->pbCrlEncoded;
                    i++;
                }
            } while (crl);
        }
    }
    if (ret)
    {
        ret = CRYPT_AsnEncodeCMSSignedInfo(&signedInfo, NULL, &size);
        if (ret)
        {
            if (!blob->pbData)
                blob->cbData = size;
            else if (blob->cbData < size)
            {
                blob->cbData = size;
                SetLastError(ERROR_MORE_DATA);
                ret = FALSE;
            }
            else
            {
                blob->cbData = size;
                ret = CRYPT_AsnEncodeCMSSignedInfo(&signedInfo, blob->pbData,
                 &blob->cbData);
            }
        }
    }
    CryptMemFree(signedInfo.rgCertEncoded);
    CryptMemFree(signedInfo.rgCrlEncoded);
    TRACE("returning %d\n", ret);
    return ret;
}
Ejemplo n.º 27
0
/**
 * Worker for cmdDisplayAll.
 */
static BOOL WINAPI displaySystemStoreCallback(const void *pvSystemStore, DWORD dwFlags, PCERT_SYSTEM_STORE_INFO pStoreInfo,
                                              void *pvReserved, void *pvArg)
{
    if (g_cVerbosityLevel > 1)
        RTPrintf("    pvSystemStore=%p dwFlags=%#x pStoreInfo=%p pvReserved=%p\n", pvSystemStore, dwFlags, pStoreInfo, pvReserved);
    LPCWSTR pwszStoreNm = NULL;
    if (dwFlags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
    {
        const CERT_SYSTEM_STORE_RELOCATE_PARA *pRelPara = (const CERT_SYSTEM_STORE_RELOCATE_PARA *)pvSystemStore;
        pwszStoreNm = pRelPara->pwszSystemStore;
        RTPrintf("    %#010x '%ls' hKeyBase=%p\n", dwFlags, pwszStoreNm, pRelPara->hKeyBase);
    }
    else
    {
        pwszStoreNm = (LPCWSTR)pvSystemStore;
        RTPrintf("    %#010x '%ls'\n", dwFlags, pwszStoreNm);
    }

    /*
     * Open the store and list the certificates within.
     */
    DWORD      dwDst  = (dwFlags & CERT_SYSTEM_STORE_LOCATION_MASK);
    HCERTSTORE hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W,
                                      PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
                                      NULL /* hCryptProv = default */,
                                      dwDst | CERT_STORE_OPEN_EXISTING_FLAG,
                                      pwszStoreNm);
    if (hStore)
    {
        PCCERT_CONTEXT pCertCtx = NULL;
        while ((pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) != NULL)
        {
            if (g_cVerbosityLevel > 1)
                RTPrintf("        pCertCtx=%p dwCertEncodingType=%#x cbCertEncoded=%#x pCertInfo=%p\n",
                         pCertCtx, pCertCtx->dwCertEncodingType, pCertCtx->cbCertEncoded, pCertCtx->pCertInfo);
            WCHAR wszName[1024];
            if (CertGetNameStringW(pCertCtx, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0 /*dwFlags*/, NULL /*pvTypePara*/,
                                   wszName, sizeof(wszName)))
            {
                RTPrintf("        '%ls'\n", wszName);
                if (pCertCtx->pCertInfo)
                {
                    RTTIMESPEC TmpTS;
                    char  szNotBefore[80];
                    RTTimeSpecToString(RTTimeSpecSetNtFileTime(&TmpTS, &pCertCtx->pCertInfo->NotBefore),
                                       szNotBefore, sizeof(szNotBefore));
                    char  szNotAfter[80];
                    RTTimeSpecToString(RTTimeSpecSetNtFileTime(&TmpTS, &pCertCtx->pCertInfo->NotAfter),
                                       szNotAfter, sizeof(szNotAfter));

                    RTPrintf("            NotBefore='%s'\n", szNotBefore);
                    RTPrintf("            NotAfter ='%s'\n", szNotAfter);
                    if (pCertCtx->pCertInfo->Issuer.cbData)
                    {
                        if (CertGetNameStringW(pCertCtx, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, NULL /*pvTypePara*/,
                                               wszName, sizeof(wszName)))
                            RTPrintf("            Issuer='%ls'\n", wszName);
                        else
                            RTMsgError("CertGetNameStringW(Issuer) failed: %s\n", errorToString(GetLastError()));
                    }
                }
            }
            else
                RTMsgError("CertGetNameStringW(Subject) failed: %s\n", errorToString(GetLastError()));

        }

        CertCloseStore(hStore, CERT_CLOSE_STORE_CHECK_FLAG);
    }
    else
        RTMsgError("CertOpenStore failed opening %#x:'%ls': %s\n", dwDst, pwszStoreNm, errorToString(GetLastError()));

    return TRUE;
}
Ejemplo n.º 28
0
/**
 * Removes a certificate, given by file, from a store
 *
 * @returns true on success, false on failure (error message written).
 * @param   dwDst           The destination, like
 *                          CERT_SYSTEM_STORE_LOCAL_MACHINE or
 *                          ERT_SYSTEM_STORE_CURRENT_USER.
 * @param   pszStoreNm      The store name.
 * @param   pszCertFile     The file containing the certificate to add.
 */
static bool removeCertFromStoreByFile(DWORD dwDst, const char *pszStoreNm, const char *pszCertFile)
{
    /*
     * Read the certificate file first.
     */
    PCCERT_CONTEXT  pSrcCtx   = NULL;
    HCERTSTORE      hSrcStore = NULL;
    if (!readCertFile(pszCertFile, &pSrcCtx, &hSrcStore))
        return false;

    WCHAR wszName[1024];
    if (!CertGetNameStringW(pSrcCtx, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0 /*dwFlags*/, NULL /*pvTypePara*/,
                            wszName, sizeof(wszName)))
    {
        RTMsgError("CertGetNameStringW(Subject) failed: %s\n", errorToString(GetLastError()));
        wszName[0] = '\0';
    }

    /*
     * Open the destination store.
     */
    bool fRc = false;
    HCERTSTORE hDstStore = openCertStore(dwDst, pszStoreNm);
    if (hDstStore)
    {
        if (pSrcCtx)
        {
            fRc = true;
            unsigned        cDeleted = 0;
            PCCERT_CONTEXT  pCurCtx  = NULL;
            while ((pCurCtx = CertEnumCertificatesInStore(hDstStore, pCurCtx)) != NULL)
            {
                if (CertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pCurCtx->pCertInfo, pSrcCtx->pCertInfo))
                {
                    if (g_cVerbosityLevel > 1)
                        RTMsgInfo("Removing '%ls'...", wszName);
                    PCCERT_CONTEXT pDeleteCtx = CertDuplicateCertificateContext(pCurCtx);
                    if (pDeleteCtx)
                    {
                        if (CertDeleteCertificateFromStore(pDeleteCtx))
                            cDeleted++;
                        else
                            RTMsgError("CertDeleteFromStore('%ls') failed: %s\n", wszName, errorToString(GetLastError()));
                    }
                    else
                        RTMsgError("CertDuplicateCertificateContext('%ls') failed: %s\n", wszName, errorToString(GetLastError()));
                }
            }

            if (!cDeleted)
                RTMsgInfo("Found no matching certificates to remove.");
        }
        else
        {
            RTMsgError("Path not implemented at line %d\n",  __LINE__);
        }

        CertCloseStore(hDstStore, CERT_CLOSE_STORE_CHECK_FLAG);
    }
    if (pSrcCtx)
        CertFreeCertificateContext(pSrcCtx);
    if (hSrcStore)
        CertCloseStore(hSrcStore, CERT_CLOSE_STORE_CHECK_FLAG);
    return fRc;
}
Ejemplo n.º 29
0
/*****************************************************************************
 HrGetSignerKeyAndChain

  This function retrieves a signing certificate from the local user’s 
  certificate store, builds certificates chain and returns key handle 
  for the signing key.”

  NOTE:
  The phCryptProvOrNCryptKey is cached and must not be released by the caller.

*****************************************************************************/
static
HRESULT
HrGetSignerKeyAndChain(
    LPCWSTR                 wszSubject,
    PCCERT_CHAIN_CONTEXT    *ppChainContext,
    HCRYPTPROV_OR_NCRYPT_KEY_HANDLE* phCryptProvOrNCryptKey,    
    DWORD                   *pdwKeySpec
    )
{
    HRESULT         hr = S_FALSE;
    HCERTSTORE      hStore = NULL;
    PCCERT_CONTEXT  pCert = NULL;
    BOOL            fCallerFreeProvOrNCryptKey = FALSE;

    CERT_CHAIN_PARA  ChainPara         = {0};
    ChainPara.cbSize = sizeof(ChainPara);

    *ppChainContext = NULL;
    *phCryptProvOrNCryptKey = NULL;
    *pdwKeySpec = 0;

    //
    // Open the local user store to search for certificates
    //

    hStore = CertOpenStore(
                            CERT_STORE_PROV_SYSTEM_W,
                            X509_ASN_ENCODING,
                            NULL,
                            CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG,
                            L"MY"
                            );
    
    if( NULL == hStore )
    {
        hr = HRESULT_FROM_WIN32( GetLastError() );
        goto CleanUp;
    }

    if( NULL != wszSubject && 0 != *wszSubject )
    {
        //
        // Search by Name
        //

        while( NULL != ( pCert = CertFindCertificateInStore(
                            hStore,
                            X509_ASN_ENCODING,
                            0,
                            CERT_FIND_SUBJECT_STR,
                            wszSubject,
                            pCert
                            )))
        {
            if( CryptAcquireCertificatePrivateKey(
                            pCert,
                            CRYPT_ACQUIRE_CACHE_FLAG,
                            NULL,
                            phCryptProvOrNCryptKey,
                            pdwKeySpec,
                            &fCallerFreeProvOrNCryptKey
                            ))
            {
                break;
            }
        }
    }
    else
    {
        //
        // Get the first available certificate in the store
        //

        while( NULL != ( pCert = CertEnumCertificatesInStore(
                            hStore,
                            pCert
                            )))
        {
            if( CryptAcquireCertificatePrivateKey(
                            pCert,
                            CRYPT_ACQUIRE_CACHE_FLAG,
                            NULL,
                            phCryptProvOrNCryptKey,
                            pdwKeySpec,
                            &fCallerFreeProvOrNCryptKey
                            ))
            {
                break;
            }
        }
    }

    if( NULL == pCert )
    {
        hr = CRYPT_XML_E_SIGNER;
        goto CleanUp;
    }

    //
    // Build the certificate chain without revocation check.
    //

    if( !CertGetCertificateChain(
                                NULL,                   // use the default chain engine
                                pCert,                  // pointer to the end certificate
                                NULL,                   // use the default time
                                NULL,                   // search no additional stores
                                &ChainPara,            
                                0,                      // no revocation check
                                NULL,                   // currently reserved
                                ppChainContext ))       // return a pointer to the chain created
    {
        hr = HRESULT_FROM_WIN32( GetLastError() );
        goto CleanUp;
    }

CleanUp:

    if( FAILED(hr) )
    {
        *phCryptProvOrNCryptKey = NULL;
        *pdwKeySpec = 0;
    }

    if( NULL != pCert )
    {
        CertFreeCertificateContext( pCert );
    }

    if( NULL != hStore )
    {
        CertCloseStore( hStore, 0 );
    }

    return hr;
}
Ejemplo n.º 30
0
static PCCERT_CONTEXT
xmlSecMSCryptoKeysStoreFindCert(xmlSecKeyStorePtr store, const xmlChar* name, 
			       xmlSecKeyInfoCtxPtr keyInfoCtx) {
    const char* storeName;
    HCERTSTORE hStoreHandle = NULL;
    PCCERT_CONTEXT pCertContext = NULL;

    xmlSecAssert2(xmlSecKeyStoreCheckId(store, xmlSecMSCryptoKeysStoreId), NULL);
    xmlSecAssert2(name != NULL, NULL);
    xmlSecAssert2(keyInfoCtx != NULL, NULL);

    storeName = xmlSecMSCryptoAppGetCertStoreName();
    if(storeName == NULL) {
	storeName = XMLSEC_MSCRYPTO_APP_DEFAULT_CERT_STORE_NAME;
    }

    hStoreHandle = CertOpenSystemStore(0, storeName);
    if (NULL == hStoreHandle) {
	xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,
		    NULL,
		    "CertOpenSystemStore",
		    XMLSEC_ERRORS_R_CRYPTO_FAILED,
		    "storeName=%s",
		    xmlSecErrorsSafeString(storeName));
	return(NULL);
    }

    /* first attempt: search by cert id == name */
    if(pCertContext == NULL) {
	size_t len = xmlStrlen(name) + 1;     
	wchar_t * lpCertID;
	
	/* aleksey todo: shouldn't we call MultiByteToWideChar first to get the buffer size? */
	lpCertID = (wchar_t *)xmlMalloc(sizeof(wchar_t) * len);
	if(lpCertID == NULL) {
	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,
			xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)),
			NULL,
			XMLSEC_ERRORS_R_MALLOC_FAILED,
		    	XMLSEC_ERRORS_NO_MESSAGE);
	    CertCloseStore(hStoreHandle, 0);
	    return(NULL);
	}
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, lpCertID, len);
	
	pCertContext = CertFindCertificateInStore(
	    hStoreHandle,
	    X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
	    0,
	    CERT_FIND_SUBJECT_STR,
	    lpCertID,
	    NULL);
	xmlFree(lpCertID);
    }

    /* We don't give up easily, now try to fetch the cert with a full blown 
     * subject dn
     */
    if (NULL == pCertContext) {
	BYTE* bdata;
	DWORD len;
	
	bdata = xmlSecMSCryptoCertStrToName(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
					    name, 
					    CERT_OID_NAME_STR,
					    &len);
	if(bdata != NULL) {
	    CERT_NAME_BLOB cnb;
    
	    cnb.cbData = len;
    	    cnb.pbData = bdata;
	    
	    pCertContext = CertFindCertificateInStore(hStoreHandle,
				X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
				0,
				CERT_FIND_SUBJECT_NAME,
				&cnb,
				NULL);
	    xmlFree(bdata);
	}
    }
	    
    /* We don't give up easily, now try to fetch the cert with a full blown 
     * subject dn, and try with a reversed dn
     */
    if (NULL == pCertContext) {
	BYTE* bdata;
	DWORD len;
	
	bdata = xmlSecMSCryptoCertStrToName(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
					    name, 
					    CERT_OID_NAME_STR | CERT_NAME_STR_REVERSE_FLAG,
					    &len);
	if(bdata != NULL) {
	    CERT_NAME_BLOB cnb;
    
	    cnb.cbData = len;
    	    cnb.pbData = bdata;
	    
	    pCertContext = CertFindCertificateInStore(hStoreHandle,
				X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
				0,
				CERT_FIND_SUBJECT_NAME,
				&cnb,
				NULL);
	    xmlFree(bdata);
	}
    }

    /*
     * Try ro find certificate with name="Friendly Name"
     */
    if (NULL == pCertContext) {
      DWORD dwPropSize;
      PBYTE pbFriendlyName;
      PCCERT_CONTEXT pCertCtxIter = NULL;
      size_t len = xmlStrlen(name) + 1;     
      wchar_t * lpFName;
	
      lpFName = (wchar_t *)xmlMalloc(sizeof(wchar_t) * len);
      if(lpFName == NULL) {
	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,
			xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)),
			NULL,
			XMLSEC_ERRORS_R_MALLOC_FAILED,
		    	XMLSEC_ERRORS_NO_MESSAGE);
	    CertCloseStore(hStoreHandle, 0);
	    return(NULL);
      }
      MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, lpFName, len);
      
      while (pCertCtxIter = CertEnumCertificatesInStore(hStoreHandle, pCertCtxIter)) {
	if (TRUE != CertGetCertificateContextProperty(pCertCtxIter,
						      CERT_FRIENDLY_NAME_PROP_ID,
						      NULL,
						      &dwPropSize)) {
	  continue;
	}

	pbFriendlyName = xmlMalloc(dwPropSize);
	if(pbFriendlyName == NULL) {
	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,
			xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)),
			NULL,
			XMLSEC_ERRORS_R_MALLOC_FAILED,
		    	XMLSEC_ERRORS_NO_MESSAGE);
	    xmlFree(lpFName);
	    CertCloseStore(hStoreHandle, 0);
	    return(NULL);
	}
	if (TRUE != CertGetCertificateContextProperty(pCertCtxIter,
						      CERT_FRIENDLY_NAME_PROP_ID,
						      pbFriendlyName,
						      &dwPropSize)) {
	  xmlFree(pbFriendlyName);
	  continue;
	}

	/* Compare FriendlyName to name */
	if (!wcscmp(lpFName, (const wchar_t *)pbFriendlyName)) {
	  pCertContext = pCertCtxIter;
	  xmlFree(pbFriendlyName);
	  break;
	}
	xmlFree(pbFriendlyName);
      }

      xmlFree(lpFName);
    }

    /* We could do the following here: 
     * It would be nice if we could locate the cert with issuer name and
     * serial number, the given keyname can be something like this:
     * 'serial=1234567;issuer=CN=ikke, C=NL'
     * to be implemented by the first person who reads this, and thinks it's
     * a good idea :) WK
     */     

    /* OK, I give up, I'm gone :( */
    
    /* aleksey todo: is it a right idea to close store if we have a handle to 
     * a cert in this store? */
    CertCloseStore(hStoreHandle, 0);
    return(pCertContext);
}