static BOOL RunDlg_AddItem(PCCERT_CONTEXT pCertContext, BOOL fTimeCheck) { BOOL fRes = TRUE; BOOL fAddToList = TRUE; char *psData; int iI; if (iListItems == (DLGMAXIEMS-1)) return(FALSE); if (iListItems == 0) { for (iI=0; iI < DLGMAXIEMS;++iI) { psListItems[iI] = NULL; psListItemsCert[iI] = NULL; } } if (pCertContext != NULL) { fAddToList = DigiCrypt_IsValidCert(pCertContext,fTimeCheck); if (fAddToList == TRUE) { psListItems[iListItems] = (char *)LocalAlloc(LMEM_ZEROINIT,(dSTRING_ITEM_LEN*4)); psListItemsCert[iListItems] = CertDuplicateCertificateContext(pCertContext); //Make data buffer for list psData = psListItems[iListItems]; RunDlg_FillItem(pCertContext, psData); ++iListItems; } } return(fRes); }
static BOOL CRYPT_MemAddCert(PWINECRYPT_CERTSTORE store, void *cert, void *toReplace, const void **ppStoreContext) { WINE_MEMSTORE *ms = (WINE_MEMSTORE *)store; PCERT_CONTEXT context; TRACE("(%p, %p, %p, %p)\n", store, cert, toReplace, ppStoreContext); context = ContextList_Add(ms->certs, cert, toReplace); if (context) { context->hCertStore = store; if (ppStoreContext) *ppStoreContext = CertDuplicateCertificateContext(context); } return context != 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; }
void CEstEIDCertificate::readFromCertContext() { PCCERT_CONTEXT certContext = NULL; HCERTSTORE cert_store = NULL; cert_store = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, L"MY"); if(!cert_store){ throw CryptoException(); } if(!CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, NULL)) { CertCloseStore(cert_store, CERT_CLOSE_STORE_FORCE_FLAG); throw CryptoException(); } while(certContext = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext)) { BYTE keyUsage; CertGetIntendedKeyUsage(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, certContext->pCertInfo, &keyUsage, 1); if (keyUsage & CERT_NON_REPUDIATION_KEY_USAGE) { this->certificates.push_back(CertDuplicateCertificateContext(certContext)); } } //PCCERT_CONTEXT ct = CryptUIDlgSelectCertificateFromStore(cert_store, NULL, L"TIITEL", L"Vali cert:", NULL, 0, 0); //loadCertContexts(ct); CCertificateSelectionDlg *dlg = new CCertificateSelectionDlg(); dlg->setCertificate(this->certificates); INT_PTR selectedItem = dlg->DoModal(); EstEID_log("selected item index = %i", selectedItem); if(selectedItem == -1) { throw CryptoException(ESTEID_USER_CANCEL); } loadCertContexts(this->certificates[selectedItem]); if(certContext){ CertFreeCertificateContext(certContext); } if(cert_store) { CertCloseStore(cert_store, CERT_CLOSE_STORE_FORCE_FLAG); } }
BOOL WINAPI WINTRUST_AddCert(CRYPT_PROVIDER_DATA *data, DWORD idxSigner, BOOL fCounterSigner, DWORD idxCounterSigner, PCCERT_CONTEXT pCert2Add) { BOOL ret = FALSE; TRACE("(%p, %d, %d, %d, %p)\n", data, idxSigner, fCounterSigner, idxSigner, pCert2Add); if (fCounterSigner) { FIXME("unimplemented for counter signers\n"); SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } if (data->pasSigners[idxSigner].csCertChain) data->pasSigners[idxSigner].pasCertChain = WINTRUST_ReAlloc(data->pasSigners[idxSigner].pasCertChain, (data->pasSigners[idxSigner].csCertChain + 1) * sizeof(CRYPT_PROVIDER_CERT)); else { data->pasSigners[idxSigner].pasCertChain = WINTRUST_Alloc(sizeof(CRYPT_PROVIDER_CERT)); data->pasSigners[idxSigner].csCertChain = 0; } if (data->pasSigners[idxSigner].pasCertChain) { CRYPT_PROVIDER_CERT *cert = &data->pasSigners[idxSigner].pasCertChain[ data->pasSigners[idxSigner].csCertChain]; cert->cbStruct = sizeof(CRYPT_PROVIDER_CERT); cert->pCert = CertDuplicateCertificateContext(pCert2Add); data->pasSigners[idxSigner].csCertChain++; ret = TRUE; } else SetLastError(ERROR_OUTOFMEMORY); return ret; }
bool StoreCertificateIterator::moveNext() { mpCertIterator = CertFindCertificateInStore( mhCertStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, mpCertIterator); if (mpCertIterator) { PCCERT_CONTEXT pCert = CertDuplicateCertificateContext(mpCertIterator); mCurrentCertPtr.reset( new Win32Certificate(pCert) ); return true; } else { mCurrentCertPtr.reset(); return false; } }
BOOL WINAPI CertAddCertificateContextToStore(HCERTSTORE hCertStore, PCCERT_CONTEXT pCertContext, DWORD dwAddDisposition, PCCERT_CONTEXT *ppStoreContext) { PWINECRYPT_CERTSTORE store = hCertStore; BOOL ret = TRUE; PCCERT_CONTEXT toAdd = NULL, existing = NULL; TRACE("(%p, %p, %08x, %p)\n", hCertStore, pCertContext, dwAddDisposition, ppStoreContext); switch (dwAddDisposition) { case CERT_STORE_ADD_ALWAYS: break; case CERT_STORE_ADD_NEW: case CERT_STORE_ADD_REPLACE_EXISTING: case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: case CERT_STORE_ADD_USE_EXISTING: case CERT_STORE_ADD_NEWER: case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: { BYTE hashToAdd[20]; DWORD size = sizeof(hashToAdd); ret = CertGetCertificateContextProperty(pCertContext, CERT_HASH_PROP_ID, hashToAdd, &size); if (ret) { CRYPT_HASH_BLOB blob = { sizeof(hashToAdd), hashToAdd }; existing = CertFindCertificateInStore(hCertStore, pCertContext->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH, &blob, NULL); } break; } default: FIXME("Unimplemented add disposition %d\n", dwAddDisposition); SetLastError(E_INVALIDARG); ret = FALSE; } switch (dwAddDisposition) { case CERT_STORE_ADD_ALWAYS: toAdd = CertDuplicateCertificateContext(pCertContext); break; case CERT_STORE_ADD_NEW: if (existing) { TRACE("found matching certificate, not adding\n"); SetLastError(CRYPT_E_EXISTS); ret = FALSE; } else toAdd = CertDuplicateCertificateContext(pCertContext); break; case CERT_STORE_ADD_REPLACE_EXISTING: toAdd = CertDuplicateCertificateContext(pCertContext); break; case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: toAdd = CertDuplicateCertificateContext(pCertContext); if (existing) CertContext_CopyProperties(toAdd, existing); break; case CERT_STORE_ADD_USE_EXISTING: if (existing) { CertContext_CopyProperties(existing, pCertContext); if (ppStoreContext) *ppStoreContext = CertDuplicateCertificateContext(existing); } else toAdd = CertDuplicateCertificateContext(pCertContext); break; case CERT_STORE_ADD_NEWER: if (existing) { if (CompareFileTime(&existing->pCertInfo->NotBefore, &pCertContext->pCertInfo->NotBefore) >= 0) { TRACE("existing certificate is newer, not adding\n"); SetLastError(CRYPT_E_EXISTS); ret = FALSE; } else toAdd = CertDuplicateCertificateContext(pCertContext); } else toAdd = CertDuplicateCertificateContext(pCertContext); break; case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: if (existing) { if (CompareFileTime(&existing->pCertInfo->NotBefore, &pCertContext->pCertInfo->NotBefore) >= 0) { TRACE("existing certificate is newer, not adding\n"); SetLastError(CRYPT_E_EXISTS); ret = FALSE; } else { toAdd = CertDuplicateCertificateContext(pCertContext); CertContext_CopyProperties(toAdd, existing); } } else toAdd = CertDuplicateCertificateContext(pCertContext); break; } if (toAdd) { if (store) ret = store->certs.addContext(store, (void *)toAdd, (void *)existing, (const void **)ppStoreContext); else if (ppStoreContext) *ppStoreContext = CertDuplicateCertificateContext(toAdd); CertFreeCertificateContext(toAdd); } CertFreeCertificateContext(existing); TRACE("returning %d\n", ret); return ret; }
/** * 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; }
static xmlSecKeyPtr xmlSecMSCryptoKeysStoreFindKey(xmlSecKeyStorePtr store, const xmlChar* name, xmlSecKeyInfoCtxPtr keyInfoCtx) { xmlSecKeyStorePtr* ss; xmlSecKeyPtr key = NULL; xmlSecKeyReqPtr keyReq = NULL; PCCERT_CONTEXT pCertContext = NULL; PCCERT_CONTEXT pCertContext2 = NULL; xmlSecKeyDataPtr data = NULL; xmlSecKeyDataPtr x509Data = NULL; xmlSecKeyPtr res = NULL; int ret; xmlSecAssert2(xmlSecKeyStoreCheckId(store, xmlSecMSCryptoKeysStoreId), NULL); xmlSecAssert2(keyInfoCtx != NULL, NULL); ss = xmlSecMSCryptoKeysStoreGetSS(store); xmlSecAssert2(((ss != NULL) && (*ss != NULL)), NULL); /* first try to find key in the simple keys store */ key = xmlSecKeyStoreFindKey(*ss, name, keyInfoCtx); if (key != NULL) { return (key); } /* Next try to find the key in the MS Certificate store, and construct an xmlSecKey. * we must have a name to lookup keys in the certificate store. */ if (name == NULL) { goto done; } /* what type of key are we looking for? * WK: For now, we'll look only for public/private keys using the * name as a cert nickname. Then the name is regarded as the subject * dn of the certificate to be searched for. */ keyReq = &(keyInfoCtx->keyReq); if (keyReq->keyType & (xmlSecKeyDataTypePublic | xmlSecKeyDataTypePrivate)) { pCertContext = xmlSecMSCryptoKeysStoreFindCert(store, name, keyInfoCtx); if(pCertContext == NULL) { goto done; } /* set cert in x509 data */ x509Data = xmlSecKeyDataCreate(xmlSecMSCryptoKeyDataX509Id); if(x509Data == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyDataCreate", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } pCertContext2 = CertDuplicateCertificateContext(pCertContext); if (NULL == pCertContext2) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "CertDuplicateCertificateContext", XMLSEC_ERRORS_R_CRYPTO_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } ret = xmlSecMSCryptoKeyDataX509AdoptCert(x509Data, pCertContext2); if (ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoKeyDataX509AdoptCert", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } pCertContext2 = NULL; pCertContext2 = CertDuplicateCertificateContext(pCertContext); if (NULL == pCertContext2) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "CertDuplicateCertificateContext", XMLSEC_ERRORS_R_CRYPTO_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } ret = xmlSecMSCryptoKeyDataX509AdoptKeyCert(x509Data, pCertContext2); if (ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoKeyDataX509AdoptKeyCert", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } pCertContext2 = NULL; /* set cert in key data */ data = xmlSecMSCryptoCertAdopt(pCertContext, keyReq->keyType); if(data == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoCertAdopt", XMLSEC_ERRORS_R_XMLSEC_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } pCertContext = NULL; /* create key and add key data and x509 data to it */ key = xmlSecKeyCreate(); if (key == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyCreate", XMLSEC_ERRORS_R_XMLSEC_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } ret = xmlSecKeySetValue(key, data); if (ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeySetValue", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(data))); goto done; } data = NULL; ret = xmlSecKeyAdoptData(key, x509Data); if (ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyAdoptData", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } x509Data = NULL; /* Set the name of the key to the given name */ ret = xmlSecKeySetName(key, name); if (ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)), "xmlSecKeySetName", XMLSEC_ERRORS_R_XMLSEC_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } /* now that we have a key, make sure it is valid and let the simple * store adopt it */ if (xmlSecKeyIsValid(key)) { res = key; key = NULL; } } done: if (NULL != pCertContext) { CertFreeCertificateContext(pCertContext); } if (NULL != pCertContext2) { CertFreeCertificateContext(pCertContext2); } if (data != NULL) { xmlSecKeyDataDestroy(data); } if (x509Data != NULL) { xmlSecKeyDataDestroy(x509Data); } if (key != NULL) { xmlSecKeyDestroy(key); } return (res); }
RetainPtr<CFDataRef> copyCertificateToData(PCCERT_CONTEXT certificate) { static CFAllocatorRef certDealloc = createCertContextDeallocator(); PCCERT_CONTEXT certificateCopy = CertDuplicateCertificateContext(certificate); return RetainPtr<CFDataRef>(AdoptCF, CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const UInt8*>(certificateCopy), sizeof(*certificateCopy), certDealloc)); }
/*cert obj must be freed*/ static int extractSigningCertificate(const KSI_PKISignature *signature, PCCERT_CONTEXT *cert) { int res = KSI_UNKNOWN_ERROR; KSI_CTX *ctx = NULL; HCERTSTORE certStore = NULL; DWORD signerCount = 0; PCERT_INFO pSignerCertInfo = NULL; HCRYPTMSG signaturMSG = NULL; PCCERT_CONTEXT signing_cert = NULL; BYTE *dataRecieved = NULL; char buf[1024]; DWORD dataLen = 0; if (signature == NULL || cert == NULL){ res = KSI_INVALID_ARGUMENT; goto cleanup; } ctx = signature->ctx; KSI_ERR_clearErrors(ctx); /*Get Signature certificates as a certificate store*/ certStore = CryptGetMessageCertificates(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, (HCRYPTPROV_LEGACY)NULL, 0, signature->pkcs7.pbData, signature->pkcs7.cbData); if (certStore == NULL){ KSI_LOG_debug(signature->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "Unable to get signatures PKI certificates."); goto cleanup; } /*Counting signing certificates*/ signerCount = CryptGetMessageSignerCount(PKCS_7_ASN_ENCODING, signature->pkcs7.pbData, signature->pkcs7.cbData); if (signerCount == -1){ KSI_LOG_debug(signature->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "Unable to count PKI signatures certificates."); goto cleanup; } /*Is there exactly 1 signing cert?*/ if (signerCount != 1){ KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "PKI signature certificate count is not 1."); goto cleanup; } /*Open signature for decoding*/ signaturMSG = CryptMsgOpenToDecode(PKCS_7_ASN_ENCODING, 0, 0,0, NULL, NULL); if (signaturMSG == NULL){ DWORD error = GetLastError(); const char *errmsg = getMSError(GetLastError(), buf, sizeof(buf)); KSI_LOG_debug(signature->ctx, "%s", errmsg); if (error == E_INVALIDARG) KSI_pushError(ctx, res = KSI_INVALID_FORMAT, errmsg); else if (error == E_OUTOFMEMORY) KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL); else KSI_pushError(ctx, res = KSI_UNKNOWN_ERROR, errmsg); goto cleanup; } if (!CryptMsgUpdate(signaturMSG, signature->pkcs7.pbData, signature->pkcs7.cbData, TRUE)){ DWORD error = GetLastError(); const char *errmsg = getMSError(GetLastError(), buf, sizeof(buf)); KSI_LOG_debug(signature->ctx, "%s", errmsg); if (error == E_OUTOFMEMORY) KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL); else if (error == CRYPT_E_UNEXPECTED_ENCODING) KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "The PKI signature is not encoded as PKCS7."); else if (error == CRYPT_E_MSG_ERROR) KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, errmsg); else KSI_pushError(ctx, res = KSI_UNKNOWN_ERROR, errmsg); goto cleanup; } /*Get signatures signing cert id*/ if (!CryptMsgGetParam (signaturMSG, CMSG_SIGNER_CERT_INFO_PARAM, 0, NULL, &dataLen)){ DWORD error = GetLastError(); const char *errmsg = getMSError(GetLastError(), buf, sizeof(buf)); KSI_LOG_debug(signature->ctx, "%s", errmsg); if (error == CRYPT_E_ATTRIBUTES_MISSING) KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "The PKI signature does not contain signing certificate id."); else KSI_pushError(ctx, res = KSI_INVALID_FORMAT, errmsg); goto cleanup; } dataRecieved = KSI_malloc(dataLen); if (dataRecieved == NULL){ KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL); goto cleanup; } if (!CryptMsgGetParam (signaturMSG, CMSG_SIGNER_CERT_INFO_PARAM, 0, dataRecieved, &dataLen)){ KSI_LOG_debug(signature->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(ctx, res = KSI_INVALID_FORMAT, "Unable to get PKI signatures signing certificate id."); goto cleanup; } pSignerCertInfo = (PCERT_INFO)dataRecieved; /*Get signing cert*/ signing_cert = CertGetSubjectCertificateFromStore(certStore, X509_ASN_ENCODING, pSignerCertInfo); if (signing_cert == NULL){ KSI_LOG_debug(signature->ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf))); KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, "Unable to get PKI signatures signer certificate."); goto cleanup; } /*The copy of the object is NOT created. Just its reference value is incremented*/ signing_cert = CertDuplicateCertificateContext(signing_cert); *cert = signing_cert; signing_cert = NULL; res = KSI_OK; cleanup: if (signing_cert) CertFreeCertificateContext(signing_cert); if (certStore) CertCloseStore(certStore, CERT_CLOSE_STORE_CHECK_FLAG); if (signaturMSG) CryptMsgClose(signaturMSG); KSI_free(dataRecieved); return res; }
// Select, and return a handle to a server certificate located by name // Usually used for a best guess at a certificate to be used as the SSL certificate for a server SECURITY_STATUS CertFindServerByName(PCCERT_CONTEXT & pCertContext, LPCTSTR pszSubjectName, boolean fUserStore) { HCERTSTORE hMyCertStore = NULL; TCHAR pszFriendlyNameString[128]; TCHAR pszNameString[128]; if (pszSubjectName == NULL || _tcslen(pszSubjectName) == 0) { DebugMsg("**** No subject name specified!"); return E_POINTER; } if (fUserStore) hMyCertStore = CertOpenSystemStore(NULL, _T("MY")); else { // Open the local machine certificate store. hMyCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING, NULL, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE, L"MY"); } if (!hMyCertStore) { int err = GetLastError(); if (err == ERROR_ACCESS_DENIED) DebugMsg("**** CertOpenStore failed with 'access denied'"); else DebugMsg("**** Error %d returned by CertOpenStore", err); return HRESULT_FROM_WIN32(err); } if (pCertContext) // The caller passed in a certificate context we no longer need, so free it CertFreeCertificateContext(pCertContext); pCertContext = NULL; char * serverauth = szOID_PKIX_KP_SERVER_AUTH; CERT_ENHKEY_USAGE eku; PCCERT_CONTEXT pCertContextSaved = NULL; eku.cUsageIdentifier = 1; eku.rgpszUsageIdentifier = &serverauth; // Find a server certificate. Note that this code just searches for a // certificate that has the required enhanced key usage for server authentication // it then selects the best one (ideally one that contains the server name // in the subject name). while (NULL != (pCertContext = CertFindCertificateInStore(hMyCertStore, X509_ASN_ENCODING, CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG, CERT_FIND_ENHKEY_USAGE, &eku, pCertContext))) { //ShowCertInfo(pCertContext); if (!CertGetNameString(pCertContext, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, pszFriendlyNameString, sizeof(pszFriendlyNameString))) { DebugMsg("CertGetNameString failed getting friendly name."); continue; } DebugMsg("Certificate '%S' is allowed to be used for server authentication.", ATL::CT2W(pszFriendlyNameString)); if (!CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pszNameString, sizeof(pszNameString))) DebugMsg("CertGetNameString failed getting subject name."); else if (_tcscmp(pszNameString, pszSubjectName)) DebugMsg("Certificate has wrong subject name."); else if (CertCompareCertificateName(X509_ASN_ENCODING, &pCertContext->pCertInfo->Subject, &pCertContext->pCertInfo->Issuer)) { if (!pCertContextSaved) { DebugMsg("A self-signed certificate was found and saved in case it is needed."); pCertContextSaved = CertDuplicateCertificateContext(pCertContext); } } else { DebugMsg("Certificate is acceptable."); if (pCertContextSaved) // We have a saved self signed certificate context we no longer need, so free it CertFreeCertificateContext(pCertContextSaved); pCertContextSaved = NULL; break; } } if (pCertContextSaved && !pCertContext) { // We have a saved self-signed certificate and nothing better DebugMsg("A self-signed certificate was the best we had."); pCertContext = pCertContextSaved; pCertContextSaved = NULL; } if (!pCertContext) { DWORD LastError = GetLastError(); if (LastError == CRYPT_E_NOT_FOUND) { DebugMsg("**** CertFindCertificateInStore did not find a certificate, creating one"); pCertContext = CreateCertificate(true, pszSubjectName); if (!pCertContext) { LastError = GetLastError(); DebugMsg("**** Error 0x%x returned by CreateCertificate", LastError); std::cout << "Could not create certificate, are you running as administrator?" << std::endl; return HRESULT_FROM_WIN32(LastError); } } else { DebugMsg("**** Error 0x%x returned by CertFindCertificateInStore", LastError); return HRESULT_FROM_WIN32(LastError); } } return SEC_E_OK; }
Win32CertificatePtr Win32Certificate::findRootCertificate( Win32CertificateLocation certStoreLocation, Win32CertificateStore certStore) { std::wstring storeName; switch (certStore) { case Cs_AddressBook: storeName = L"AddressBook"; break; case Cs_AuthRoot: storeName = L"AuthRoot"; break; case Cs_CertificateAuthority: storeName = L"CA"; break; case Cs_Disallowed: storeName = L"Disallowed"; break; case Cs_My: storeName = L"MY"; break; case Cs_Root: storeName = L"Root"; break; case Cs_TrustedPeople: storeName = L"TrustedPeople"; break; case Cs_TrustedPublisher: storeName = L"TrustedPublisher"; break; default: RCF_ASSERT(0 && "Invalid certificate store value."); } DWORD dwFlags = 0; switch (certStoreLocation) { case Cl_CurrentUser: dwFlags = CERT_SYSTEM_STORE_CURRENT_USER; break; case Cl_LocalMachine: dwFlags = CERT_SYSTEM_STORE_LOCAL_MACHINE; break; default: RCF_ASSERT(0 && "Invalid certificate store location value."); } Win32CertificatePtr issuerCertPtr; HCERTSTORE hCertStore = CertOpenStore( (LPCSTR) CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING, 0, dwFlags, storeName.c_str()); DWORD dwErr = GetLastError(); RCF_VERIFY( hCertStore, Exception(_RcfError_ApiError("CertOpenStore()"), dwErr)); PCCERT_CONTEXT pSubjectContext = getWin32Context(); DWORD dwCertFlags = 0; PCCERT_CONTEXT pIssuerContext = NULL; pSubjectContext = CertDuplicateCertificateContext(pSubjectContext); if (pSubjectContext) { do { dwCertFlags = CERT_STORE_REVOCATION_FLAG | CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG; pIssuerContext = CertGetIssuerCertificateFromStore( hCertStore, pSubjectContext, 0, &dwCertFlags); if (pIssuerContext) { CertFreeCertificateContext(pSubjectContext); pSubjectContext = pIssuerContext; if (dwCertFlags & CERT_STORE_NO_CRL_FLAG) { // No CRL list available. Proceed anyway. dwCertFlags &= ~(CERT_STORE_NO_CRL_FLAG | CERT_STORE_REVOCATION_FLAG); } if (dwCertFlags) { if ( dwCertFlags & CERT_STORE_TIME_VALIDITY_FLAG) { // Certificate is expired. // ... } break; } } else if (GetLastError() == CRYPT_E_SELF_SIGNED) { // Got the root certificate. issuerCertPtr.reset( new Win32Certificate(pSubjectContext) ); } } while (pIssuerContext); } CertCloseStore(hCertStore, 0); return issuerCertPtr; }
/** * xmlSecMSCryptoAppKeyLoadMemory: * @data: the key binary data. * @dataSize: the key data size. * @format: the key format. * @pwd: the key password. * @pwdCallback: the key password callback. * @pwdCallbackCtx: the user context for password callback. * * Reads key from the a file. * * Returns pointer to the key or NULL if an error occurs. */ xmlSecKeyPtr xmlSecMSCryptoAppKeyLoadMemory(const xmlSecByte* data, xmlSecSize dataSize, xmlSecKeyDataFormat format, const char *pwd, void* pwdCallback, void* pwdCallbackCtx) { PCCERT_CONTEXT pCert = NULL; PCCERT_CONTEXT tmpcert = NULL; xmlSecKeyDataPtr x509Data = NULL; xmlSecKeyDataPtr keyData = NULL; xmlSecKeyPtr key = NULL; xmlSecKeyPtr res = NULL; int ret; xmlSecAssert2(data != NULL, NULL); xmlSecAssert2(dataSize > 0, NULL); xmlSecAssert2(format == xmlSecKeyDataFormatCertDer, NULL); pCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, data, dataSize); if (NULL == pCert) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "CertCreateCertificateContext", XMLSEC_ERRORS_R_IO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } x509Data = xmlSecKeyDataCreate(xmlSecMSCryptoKeyDataX509Id); if(x509Data == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyDataCreate", XMLSEC_ERRORS_R_XMLSEC_FAILED, "transform=%s", xmlSecErrorsSafeString(xmlSecTransformKlassGetName(xmlSecMSCryptoKeyDataX509Id))); goto done; } tmpcert = CertDuplicateCertificateContext(pCert); if(tmpcert == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "CertDuplicateCertificateContext", XMLSEC_ERRORS_R_CRYPTO_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } ret = xmlSecMSCryptoKeyDataX509AdoptKeyCert(x509Data, tmpcert); if(ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoKeyDataX509AdoptKeyCert", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); CertFreeCertificateContext(tmpcert); goto done; } tmpcert = NULL; keyData = xmlSecMSCryptoCertAdopt(pCert, xmlSecKeyDataTypePublic); if(keyData == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoCertAdopt", XMLSEC_ERRORS_R_XMLSEC_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } pCert = NULL; key = xmlSecKeyCreate(); if(key == NULL) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyCreate", XMLSEC_ERRORS_R_XMLSEC_FAILED, XMLSEC_ERRORS_NO_MESSAGE); goto done; } ret = xmlSecKeySetValue(key, keyData); if(ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeySetValue", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } keyData = NULL; ret = xmlSecKeyAdoptData(key, x509Data); if(ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecKeyAdoptData", XMLSEC_ERRORS_R_XMLSEC_FAILED, "data=%s", xmlSecErrorsSafeString(xmlSecKeyDataGetName(x509Data))); goto done; } x509Data = NULL; /* success */ res = key; key = NULL; done: if(pCert != NULL) { CertFreeCertificateContext(pCert); } if(tmpcert != NULL) { CertFreeCertificateContext(tmpcert); } if(x509Data != NULL) { xmlSecKeyDataDestroy(x509Data); } if(keyData != NULL) { xmlSecKeyDataDestroy(keyData); } if(key != NULL) { xmlSecKeyDestroy(key); } return(res); }