CryptAcquireCertificatePrivateKey accepting CAPI despite using CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG
0
I am currently testing some code which is supposed to fail all CAPI keys so that only up to date CNG certs can be used. One of my functions I'm using, CryptAcquireCertificatePrivateKey, is specifically set to only take CNG keys.
However when I create a CAPI key, it is able to have it's key obtained by CryptAcquireCertificatePrivateKey as a CNG key. This is unexpected and unacceptable behavior because those CAPI keys need to be detected and removed.
LPCWSTR pszX500 = L"CN=dummy.primary.cert";
CERT_NAME_BLOB SubjectIssuerBlob;
if (!CertStrToName(CRYPT_ASN_ENCODING, pszX500, 0, NULL, NULL, &SubjectIssuerBlob.cbData, NULL))
{
throw;
}
SubjectIssuerBlob.pbData = (BYTE*)malloc(SubjectIssuerBlob.cbData);
if (!SubjectIssuerBlob.pbData)
{
throw;
}
if (!CertStrToName(CRYPT_ASN_ENCODING, pszX500, 0, NULL, SubjectIssuerBlob.pbData, &SubjectIssuerBlob.cbData, NULL))
{
free(SubjectIssuerBlob.pbData);
throw;
}
HCRYPTPROV hCryptProv;
CryptAcquireContextA(&hCryptProv, NULL, NULL, PROV_DSS_DH,CRYPT_NEWKEYSET);
PCCERT_CONTEXT pCertContext = CertCreateSelfSignCertificate(hCryptProv, &SubjectIssuerBlob, 0, NULL, NULL, NULL, NULL, NULL);
if (!pCertContext)
{
throw;
}
DWORD dwKeySpec;
BOOL fCallerFreeProvOrNCryptKey = FALSE;
NCRYPT_KEY_HANDLE hkeyz = NULL;
if (!CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG, NULL, &hkeyz, &dwKeySpec, &fCallerFreeProvOrNCryptKey))
{
INFO("This is not expected to succeed since CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG is set while a CAPI Key is used");
}
if (hkeyz)
{
CryptReleaseContext(hkeyz, 0);
}
if (pCertContext)
{
INFO("removing cert");
CertFreeCertificateContext(pCertContext);
}
My expectation is that the following code is called but it isn't.
INFO("This is not expected to succeed since CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG is set while a CAPI Key is used");