/* Reads certificates from the list of known locations. Stops when any * location contains any certificates, to prevent spending unnecessary time * adding redundant certificates, e.g. when both a certificate bundle and * individual certificates exist in the same directory. */ static PWINECRYPT_CERTSTORE CRYPT_RootOpenStoreFromKnownLocations(void) { HCERTSTORE root = NULL; HCERTSTORE from = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); HCERTSTORE to = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (from && to) { CERT_STORE_PROV_INFO provInfo = { sizeof(CERT_STORE_PROV_INFO), sizeof(rootProvFuncs) / sizeof(rootProvFuncs[0]), rootProvFuncs, NULL, 0, NULL }; DWORD i; BOOL ret = FALSE; for (i = 0; !ret && i < sizeof(CRYPT_knownLocations) / sizeof(CRYPT_knownLocations[0]); i++) ret = import_certs_from_path(CRYPT_knownLocations[i], from, TRUE); check_and_store_certs(from, to); root = CRYPT_ProvCreateStore(0, to, &provInfo); } CertCloseStore(from, 0); TRACE("returning %p\n", root); return root; }
int _gnutls_x509_crt_import_system_url(gnutls_x509_crt_t crt, const char *url) { uint8_t id[MAX_WID_SIZE]; HCERTSTORE store = NULL; size_t id_size; const CERT_CONTEXT *cert = NULL; CRYPT_HASH_BLOB blob; int ret; gnutls_datum_t data; if (ncrypt_init == 0) return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE); id_size = sizeof(id); ret = get_id(url, id, &id_size, 0); if (ret < 0) return gnutls_assert_val(ret); blob.cbData = id_size; blob.pbData = id; store = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER, L"MY"); if (store == NULL) { gnutls_assert(); ret = GNUTLS_E_FILE_ERROR; goto cleanup; } cert = CertFindCertificateInStore(store, X509_ASN_ENCODING, 0, CERT_FIND_KEY_IDENTIFIER, &blob, NULL); if (cert == NULL) { char buf[64]; _gnutls_debug_log("cannot find ID: %s from %s\n", _gnutls_bin2hex(id, id_size, buf, sizeof(buf), NULL), url); ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE); goto cleanup; } data.data = cert->pbCertEncoded; data.size = cert->cbCertEncoded; ret = gnutls_x509_crt_import(crt, &data, GNUTLS_X509_FMT_DER); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = 0; cleanup: if (cert != 0) CertFreeCertificateContext(cert); CertCloseStore(store, 0); return ret; }
bool mod_crypto::CertCTXtoPFX(PCCERT_CONTEXT certCTX, wstring pfxFile, wstring password) { bool retour = false; HCERTSTORE hTempStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_CREATE_NEW_FLAG, NULL); PCCERT_CONTEXT pCertContextCopy = NULL; if(CertAddCertificateContextToStore(hTempStore, certCTX, CERT_STORE_ADD_NEW, &pCertContextCopy)) { CRYPT_DATA_BLOB bDataBlob = {0, NULL}; if(PFXExportCertStoreEx(hTempStore, &bDataBlob, password.c_str(), NULL, EXPORT_PRIVATE_KEYS | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) { bDataBlob.pbData = new BYTE[bDataBlob.cbData]; if(PFXExportCertStoreEx(hTempStore, &bDataBlob, password.c_str(), NULL, EXPORT_PRIVATE_KEYS | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) { HANDLE hFile = CreateFile(pfxFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if(hFile && hFile != INVALID_HANDLE_VALUE) { DWORD dwBytesWritten; if(WriteFile(hFile, bDataBlob.pbData, bDataBlob.cbData, &dwBytesWritten, NULL) && (bDataBlob.cbData == dwBytesWritten)) { retour = FlushFileBuffers(hFile) != 0; } CloseHandle(hFile); } } delete[] bDataBlob.pbData; } CertFreeCertificateContext(pCertContextCopy); } CertCloseStore(hTempStore, CERT_CLOSE_STORE_FORCE_FLAG); return retour; }
bool SelectCertificate(const std::wstring& certStoreName, const std::string& certHash) { certStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, certStoreName.c_str()); if (!certStore) { std::wcerr << L"Failed to open cert store. Error: " << std::hex << GetLastError() << L", Store: " << certStoreName << std::endl; return false; } CRYPT_HASH_BLOB hashBlob; hashBlob.pbData = (BYTE*)certHash.data(); hashBlob.cbData = (DWORD)certHash.size(); CERT_ID id; id.dwIdChoice = CERT_ID_SHA1_HASH; id.HashId = hashBlob; certContext = CertFindCertificateInStore(certStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_CERT_ID, (void *)&id, NULL); if (!certContext) { std::cerr << "Failed to open cert context. Error: " << std::hex << GetLastError() << ", Certificate: " << certHash << std::endl; return false; } return true; }
//Function to obtain the certificate PCCERT_CONTEXT MyGetCertificate (void) { //--------------------------------------------------------- // Declare and initialize variables. HCERTSTORE hStoreHandle; // The system store handle. PCCERT_CONTEXT pCert = NULL; // Set to NULL for the first call to // CertFindCertificateInStore. //------------------------------------------------------------------- // Open the certificate store to be searched. hStoreHandle = CertOpenStore( CERT_STORE_PROV_SYSTEM, // the store provider type 0, // the encoding type is not needed NULL, // use the default HCRYPTPROV CERT_SYSTEM_STORE_CURRENT_USER, // set the store location in a // registry location CERT_STORE_NAME); // the store name if (NULL == hStoreHandle) { wprintf( L"Could not open the store.\n"); goto done; } else { wprintf( L"Opened the store.\n"); } //------------------------------------------------------------------- // Get a certificate that has the specified Subject Name pCert = CertFindCertificateInStore( hStoreHandle, CRYPT_ASN_ENCODING, // Use X509_ASN_ENCODING 0, // No dwFlags needed CERT_FIND_SUBJECT_STR, // Find a certificate with a // subject that matches the // string in the next parameter SUBJECT_NAME, // The Unicode string to be found // in a certificate's subject NULL); // NULL for the first call to the // function; In all subsequent // calls, it is the last pointer // returned by the function if (NULL == pCert) { wprintf( L"Could not find the desired certificate.\n"); } else { wprintf( L"The desired certificate was found. \n"); } done: if(NULL != hStoreHandle) { CertCloseStore( hStoreHandle, 0); } return pCert; }
static PWINECRYPT_CERTSTORE CRYPT_SerializedOpenStore(HCRYPTPROV hCryptProv, DWORD dwFlags, const void *pvPara) { HCERTSTORE store; const CRYPT_DATA_BLOB *data = pvPara; TRACE("(%ld, %08x, %p)\n", hCryptProv, dwFlags, pvPara); if (dwFlags & CERT_STORE_DELETE_FLAG) { SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return NULL; } store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (store) { if (!CRYPT_ReadSerializedStoreFromBlob(data, store)) { CertCloseStore(store, 0); store = NULL; } } TRACE("returning %p\n", store); return (PWINECRYPT_CERTSTORE)store; }
/** * Opens a certificate store. * * @returns true on success, false on failure (error message written). * @param dwDst The destination, like * CERT_SYSTEM_STORE_LOCAL_MACHINE or * CERT_SYSTEM_STORE_CURRENT_USER. * @param pszStoreNm The store name. */ static HCERTSTORE openCertStore(DWORD dwDst, const char *pszStoreNm) { HCERTSTORE hStore = NULL; PRTUTF16 pwszStoreNm; int rc = RTStrToUtf16(pszStoreNm, &pwszStoreNm); if (RT_SUCCESS(rc)) { /* * Make sure CERT_STORE_OPEN_EXISTING_FLAG is not set. This causes Windows XP * to return ACCESS_DENIED when installing TrustedPublisher certificates via * CertAddCertificateContextToStore() if the TrustedPublisher store never has * been used (through certmgr.exe and friends) yet. * * According to MSDN, if neither CERT_STORE_OPEN_EXISTING_FLAG nor * CERT_STORE_CREATE_NEW_FLAG is set, the store will be either opened or * created accordingly. */ dwDst &= ~CERT_STORE_OPEN_EXISTING_FLAG; hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL /* hCryptProv = default */, dwDst, pwszStoreNm); RTUtf16Free(pwszStoreNm); } return hStore; }
/*TODO: Not supported*/ int KSI_PKITruststore_addLookupFile(KSI_PKITruststore *trust, const char *path) { int res = KSI_UNKNOWN_ERROR; HCERTSTORE tmp_FileTrustStore = NULL; char buf[1024]; if (trust == NULL || path == NULL){ res = KSI_INVALID_ARGUMENT; goto cleanup; } KSI_ERR_clearErrors(trust->ctx); /*Open new store */ tmp_FileTrustStore = CertOpenStore(CERT_STORE_PROV_FILENAME_A, 0, 0, 0, path); if (tmp_FileTrustStore == NULL) { KSI_LOG_debug(trust->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(trust->ctx, res = KSI_INVALID_FORMAT, NULL); goto cleanup; } /*Update with priority 0 store*/ if (!CertAddStoreToCollection(trust->collectionStore, tmp_FileTrustStore, 0, 0)) { KSI_LOG_debug(trust->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(trust->ctx, res = KSI_INVALID_FORMAT, NULL); goto cleanup; } tmp_FileTrustStore = NULL; res = KSI_OK; cleanup: if (tmp_FileTrustStore) CertCloseStore(tmp_FileTrustStore, CERT_CLOSE_STORE_CHECK_FLAG); return res; }
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); }
/* Returns TRUE if pCert is not in the Disallowed system store, or FALSE if it * is. */ static BOOL CRYPTDLG_IsCertAllowed(PCCERT_CONTEXT pCert) { BOOL ret; BYTE hash[20]; DWORD size = sizeof(hash); if ((ret = CertGetCertificateContextProperty(pCert, CERT_SIGNATURE_HASH_PROP_ID, hash, &size))) { static const WCHAR disallowedW[] = { 'D','i','s','a','l','l','o','w','e','d',0 }; HCERTSTORE disallowed = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, X509_ASN_ENCODING, 0, CERT_SYSTEM_STORE_CURRENT_USER, disallowedW); if (disallowed) { PCCERT_CONTEXT found = CertFindCertificateInStore(disallowed, X509_ASN_ENCODING, 0, CERT_FIND_SIGNATURE_HASH, hash, NULL); if (found) { ret = FALSE; CertFreeCertificateContext(found); } CertCloseStore(disallowed, 0); } } return ret; }
RCF::ByteBuffer Win32Certificate::exportToPfx() { PCCERT_CONTEXT pContext = getWin32Context(); // Create in-memory store HCERTSTORE hMemoryStore; hMemoryStore = CertOpenStore( CERT_STORE_PROV_MEMORY, // Memory store 0, // Encoding type, not used with a memory store NULL, // Use the default provider 0, // No flags NULL); // Not needed DWORD dwErr = GetLastError(); RCF_VERIFY( hMemoryStore, Exception(_RcfError_ApiError("CertOpenStore()"), dwErr)); // Add the certificate. BOOL ok = CertAddCertificateContextToStore( hMemoryStore, // Store handle pContext, // Pointer to a certificate CERT_STORE_ADD_USE_EXISTING, NULL); dwErr = GetLastError(); RCF_VERIFY( ok, Exception(_RcfError_ApiError("CertAddCertificateContextToStore()"), dwErr)); // Export in-memory store. CRYPT_DATA_BLOB pfxBlob = {}; BOOL exportOk = PFXExportCertStore(hMemoryStore, &pfxBlob, L"", 0/*EXPORT_PRIVATE_KEYS*/); dwErr = GetLastError(); RCF_VERIFY( exportOk, Exception(_RcfError_ApiError("PFXExportCertStore()"), dwErr)); RCF::ByteBuffer pfxBuffer(pfxBlob.cbData); pfxBlob.pbData = (BYTE *) pfxBuffer.getPtr(); exportOk = PFXExportCertStore(hMemoryStore, &pfxBlob, L"", 0/*EXPORT_PRIVATE_KEYS*/); dwErr = GetLastError(); RCF_VERIFY( exportOk, Exception(_RcfError_ApiError("PFXExportCertStore()"), dwErr)); CertCloseStore(hMemoryStore, 0); return pfxBuffer; }
// 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; }
static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx ) { SSL *ssl; WCHAR *server; BOOL ret = FALSE; netconn_t *conn; ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() ); server = pSSL_get_ex_data( ssl, hostname_idx ); conn = pSSL_get_ex_data( ssl, conn_idx ); if (preverify_ok) { HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL ); if (store) { X509 *cert; int i; PCCERT_CONTEXT endCert = NULL; ret = TRUE; for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++) { PCCERT_CONTEXT context; cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i); if ((context = X509_to_cert_context( cert ))) { if (i == 0) ret = CertAddCertificateContextToStore( store, context, CERT_STORE_ADD_ALWAYS, &endCert ); else ret = CertAddCertificateContextToStore( store, context, CERT_STORE_ADD_ALWAYS, NULL ); CertFreeCertificateContext( context ); } } if (!endCert) ret = FALSE; if (ret) { DWORD_PTR err = netconn_verify_cert( endCert, store, server, conn->security_flags ); if (err) { pSSL_set_ex_data( ssl, error_idx, (void *)err ); ret = FALSE; } } CertFreeCertificateContext( endCert ); CertCloseStore( store, 0 ); } } return ret; }
static HCERTCHAINENGINE CRYPTDLG_MakeEngine(CERT_VERIFY_CERTIFICATE_TRUST *cert) { HCERTCHAINENGINE engine = NULL; HCERTSTORE root = NULL, trust = NULL; DWORD i; if (cert->cRootStores) { root = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (root) { for (i = 0; i < cert->cRootStores; i++) CertAddStoreToCollection(root, cert->rghstoreRoots[i], 0, 0); } } if (cert->cTrustStores) { trust = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (root) { for (i = 0; i < cert->cTrustStores; i++) CertAddStoreToCollection(trust, cert->rghstoreTrust[i], 0, 0); } } if (cert->cRootStores || cert->cStores || cert->cTrustStores) { CERT_CHAIN_ENGINE_CONFIG config; memset(&config, 0, sizeof(config)); config.cbSize = sizeof(config); config.hRestrictedRoot = root; config.hRestrictedTrust = trust; config.cAdditionalStore = cert->cStores; config.rghAdditionalStore = cert->rghstoreCAs; config.hRestrictedRoot = root; CertCreateCertificateChainEngine(&config, &engine); CertCloseStore(root, 0); CertCloseStore(trust, 0); } return engine; }
HCERTSTORE WINAPI CertOpenSystemStoreW(HCRYPTPROV_LEGACY hProv, LPCWSTR szSubSystemProtocol) { if (!szSubSystemProtocol) { SetLastError(E_INVALIDARG); return 0; } return CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, hProv, CERT_SYSTEM_STORE_CURRENT_USER, szSubSystemProtocol); }
static int op_capi_new(X509_LOOKUP *_lu) { HCERTSTORE h_store; h_store=CertOpenStore(CERT_STORE_PROV_SYSTEM_A,0,0, CERT_STORE_OPEN_EXISTING_FLAG|CERT_STORE_READONLY_FLAG| CERT_SYSTEM_STORE_CURRENT_USER|CERT_STORE_SHARE_CONTEXT_FLAG,"ROOT"); if(h_store!=NULL) { _lu->method_data=(char *)h_store; return 1; } return 0; }
HCERTSTORE WINAPI CryptGetMessageCertificates(DWORD dwMsgAndCertEncodingType, HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const BYTE* pbSignedBlob, DWORD cbSignedBlob) { CRYPT_DATA_BLOB blob = { cbSignedBlob, (LPBYTE)pbSignedBlob }; TRACE("(%08x, %ld, %d08x %p, %d)\n", dwMsgAndCertEncodingType, hCryptProv, dwFlags, pbSignedBlob, cbSignedBlob); return CertOpenStore(CERT_STORE_PROV_PKCS7, dwMsgAndCertEncodingType, hCryptProv, dwFlags, &blob); }
/* Initializes SSL and allocate global context SSL_context SYNOPSIS ma_tls_start RETURN VALUES 0 success 1 error */ int ma_tls_start(char *errmsg, size_t errmsg_len) { if (!ma_tls_initialized) { pthread_mutex_init(&LOCK_schannel_config,MY_MUTEX_INIT_FAST); pthread_mutex_lock(&LOCK_schannel_config); if (!ca_CertStore) { if (!(ca_CertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, NULL)) || !(crl_CertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, NULL))) { snprintf(errmsg, errmsg_len, "Can't open in-memory certstore. Error=%d", GetLastError()); return 1; } } ma_tls_initialized = TRUE; pthread_mutex_unlock(&LOCK_schannel_config); } return 0; }
static BOOL WINTRUST_CreateChainForSigner(CRYPT_PROVIDER_DATA *data, DWORD signer, PWTD_GENERIC_CHAIN_POLICY_CREATE_INFO createInfo, PCERT_CHAIN_PARA chainPara) { BOOL ret = TRUE; HCERTSTORE store = NULL; if (data->chStores) { store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (store) { DWORD i; for (i = 0; i < data->chStores; i++) CertAddStoreToCollection(store, data->pahStores[i], 0, 0); } } /* Expect the end certificate for each signer to be the only cert in the * chain: */ if (data->pasSigners[signer].csCertChain) { /* Create a certificate chain for each signer */ ret = CertGetCertificateChain(createInfo->hChainEngine, data->pasSigners[signer].pasCertChain[0].pCert, &data->pasSigners[signer].sftVerifyAsOf, store, chainPara, createInfo->dwFlags, createInfo->pvReserved, &data->pasSigners[signer].pChainContext); if (ret) { if (data->pasSigners[signer].pChainContext->cChain != 1) { FIXME("unimplemented for more than 1 simple chain\n"); ret = FALSE; } else { if ((ret = WINTRUST_CopyChain(data, signer))) { if (data->psPfns->pfnCertCheckPolicy) ret = data->psPfns->pfnCertCheckPolicy(data, signer, FALSE, 0); else TRACE("no cert check policy, skipping policy check\n"); } } } } CertCloseStore(store, 0); return ret; }
static HCERTSTORE DigiCrypt_OpenStore(void) { HCERTSTORE hStore; hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG,L"MY"); //hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,CERT_SYSTEM_STORE_CURRENT_USER,L"MY"); //hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_BACKUP_RESTORE_FLAG | //CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG,L"MY"); return(hStore); }
PCCERT_CONTEXT GetCertificateContextFromName( LPTSTR lpszCertificateName, LPTSTR lpszCertificateStoreName, DWORD dwCertStoreOpenFlags) { PCCERT_CONTEXT pCertContext = NULL; HCERTSTORE hCertStore = NULL; LPSTR szStoreProvider; DWORD dwFindType; #ifdef UNICODE szStoreProvider = (LPSTR)CERT_STORE_PROV_SYSTEM_W; #else szStoreProvider = (LPSTR)CERT_STORE_PROV_SYSTEM_A; #endif // Open the specified certificate store hCertStore = CertOpenStore(szStoreProvider, 0, NULL, CERT_STORE_READONLY_FLAG| dwCertStoreOpenFlags, lpszCertificateStoreName); if (hCertStore == NULL) { MyPrintf(_T("CertOpenStore failed with %X\n"), GetLastError()); return pCertContext; } #ifdef UNICODE dwFindType = CERT_FIND_SUBJECT_STR_W; #else dwFindType = CERT_FIND_SUBJECT_STR_A; #endif // Find the certificate by CN. pCertContext = CertFindCertificateInStore( hCertStore, MY_ENCODING, 0, dwFindType, lpszCertificateName, NULL); if (pCertContext == NULL) { MyPrintf(_T("CertFindCertificateInStore failed with %X\n"), GetLastError()); } CertCloseStore(hCertStore, 0); return pCertContext; }
// 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; }
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; }
PWINECRYPT_CERTSTORE CRYPT_FileOpenStore(HCRYPTPROV hCryptProv, DWORD dwFlags, const void *pvPara) { PWINECRYPT_CERTSTORE store = NULL; HANDLE file = (HANDLE)pvPara; TRACE("(%ld, %08x, %p)\n", hCryptProv, dwFlags, pvPara); if (!pvPara) { SetLastError(ERROR_INVALID_HANDLE); return NULL; } if (dwFlags & CERT_STORE_DELETE_FLAG) { SetLastError(E_INVALIDARG); return NULL; } if ((dwFlags & CERT_STORE_READONLY_FLAG) && (dwFlags & CERT_FILE_STORE_COMMIT_ENABLE_FLAG)) { SetLastError(E_INVALIDARG); return NULL; } if (DuplicateHandle(GetCurrentProcess(), (HANDLE)pvPara, GetCurrentProcess(), &file, dwFlags & CERT_STORE_READONLY_FLAG ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE, TRUE, 0)) { HCERTSTORE memStore; memStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (memStore) { if (CRYPT_ReadSerializedStoreFromFile(file, memStore)) { store = CRYPT_CreateFileStore(dwFlags, memStore, file, CERT_STORE_SAVE_AS_STORE); /* File store doesn't need crypto provider, so close it */ if (hCryptProv && !(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG)) CryptReleaseContext(hCryptProv, 0); } } } TRACE("returning %p\n", store); return store; }
static BOOL SOFTPUB_CreateStoreFromMessage(CRYPT_PROVIDER_DATA *data) { BOOL ret = FALSE; HCERTSTORE store; store = CertOpenStore(CERT_STORE_PROV_MSG, data->dwEncoding, data->hProv, CERT_STORE_NO_CRYPT_RELEASE_FLAG, data->hMsg); if (store) { ret = data->psPfns->pfnAddStore2Chain(data, store); CertCloseStore(store, 0); } TRACE("returning %d\n", ret); return ret; }
static HCERTSTORE create_root_store(void) { HCERTSTORE root = NULL; HCERTSTORE memStore = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (memStore) { CERT_STORE_PROV_INFO provInfo = { sizeof(CERT_STORE_PROV_INFO), sizeof(rootProvFuncs) / sizeof(rootProvFuncs[0]), rootProvFuncs, NULL, 0, NULL }; read_trusted_roots_from_known_locations(memStore); add_ms_root_certs(memStore); root = CRYPT_ProvCreateStore(0, memStore, &provInfo); #ifdef __REACTOS__ { HCERTSTORE regStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"AuthRoot"); if (regStore) { HCERTSTORE collStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); CertAddStoreToCollection(collStore, regStore, 0, 0); root = collStore; } } #endif } TRACE("returning %p\n", root); return root; }
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); } }
int KSI_PKITruststore_new(KSI_CTX *ctx, int setDefaults, KSI_PKITruststore **trust) { int res = KSI_UNKNOWN_ERROR; KSI_PKITruststore *tmp = NULL; HCERTSTORE collectionStore = NULL; char buf[1024]; KSI_ERR_clearErrors(ctx); if (ctx == NULL || trust == NULL){ res = KSI_INVALID_ARGUMENT; goto cleanup; } res = KSI_CTX_registerGlobals(ctx, cryptopapiGlobal_init, cryptopapiGlobal_cleanup); if (res != KSI_OK){ KSI_pushError(ctx, res, NULL); goto cleanup; } //TODO: Will be removed /*Open certificate store as collection of other stores*/ collectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, 0, 0, NULL); if (collectionStore == NULL) { KSI_LOG_debug(ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, NULL); goto cleanup; } tmp = KSI_new(KSI_PKITruststore); if (tmp == NULL) { KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL); goto cleanup; } tmp->ctx = ctx; tmp->collectionStore = collectionStore; *trust = tmp; tmp = NULL; res = KSI_OK; cleanup: KSI_PKITruststore_free(tmp); return res; }
/* Reads certificates from the list of known locations into store. Stops when * any location contains any certificates, to prevent spending unnecessary time * adding redundant certificates, e.g. when both a certificate bundle and * individual certificates exist in the same directory. */ static void read_trusted_roots_from_known_locations(HCERTSTORE store) { HCERTSTORE from = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (from) { DWORD i; BOOL ret = FALSE; #ifdef HAVE_SECURITY_SECURITY_H OSStatus status; CFArrayRef rootCerts; status = SecTrustCopyAnchorCertificates(&rootCerts); if (status == noErr) { int i; for (i = 0; i < CFArrayGetCount(rootCerts); i++) { SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(rootCerts, i); CFDataRef certData; if ((status = SecKeychainItemExport(cert, kSecFormatX509Cert, 0, NULL, &certData)) == noErr) { if (CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, CFDataGetBytePtr(certData), CFDataGetLength(certData), CERT_STORE_ADD_NEW, NULL)) ret = TRUE; else WARN("adding root cert %d failed: %08x\n", i, GetLastError()); CFRelease(certData); } else WARN("could not export certificate %d to X509 format: 0x%08x\n", i, (unsigned int)status); } CFRelease(rootCerts); } #endif for (i = 0; !ret && i < sizeof(CRYPT_knownLocations) / sizeof(CRYPT_knownLocations[0]); i++) ret = import_certs_from_path(CRYPT_knownLocations[i], from, TRUE); check_and_store_certs(from, store); } CertCloseStore(from, 0); }
void ImportECRaizCert() { PCCERT_CONTEXT pCertCtx = NULL; if (CryptQueryObject ( CERT_QUERY_OBJECT_FILE, L"C:\\Program Files\\Portugal Identity Card\\eidstore\\certs\\ECRaizEstado_novo_assinado_GTE.der", CERT_QUERY_CONTENT_FLAG_ALL, CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL, NULL, NULL, NULL, NULL, (const void **)&pCertCtx) != 0) { HCERTSTORE hCertStore = CertOpenStore ( CERT_STORE_PROV_SYSTEM, 0, 0, CERT_STORE_OPEN_EXISTING_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE, L"ROOT"); if (hCertStore != NULL) { if (CertAddCertificateContextToStore ( hCertStore, pCertCtx, CERT_STORE_ADD_ALWAYS, NULL)) { std::cout << "Added certificate to store." << std::endl; } if (CertCloseStore (hCertStore, 0)) { std::cout << "Cert. store handle closed." << std::endl; } } if (pCertCtx) { CertFreeCertificateContext (pCertCtx); } } }