Silent accept .pfx certificates - c++

Such a problem: I need to import .pfx certificates in my installation (WiX 3.5). I need to accept importing them without any(!) user interaction, even acception (need to be so for testion on building servers and testing makets)
Tried standard WiX solution, using WiXIISExtension, but there is no option for quiet(silent) import.
Tried such solutions on C++ (deferred custom actions from dll in wix):
Chain PfxImportCertStore - CertEnumCertificatesStore - CertAddCertificateContextToStore:
Certificate manager asked for acception...
CryptUIWizImport with flag CRYPTUI_WIZ_NO_UI: CryptoAPI tried to access to a private key, and manager asked for acception...
Is there any way of solving this? or I really need to write a custom service for acception?

Well, I solved my problem. In my case it was just the flag of user protected certificate. Just my dummy. but, in these two days I realised:
Be carefully with the methods of importing certificate. You should know different situations, when you need to use import from file or from context.
Pay attention to the flags, you used (the more if you use some examples)
Be sure your certificate has approvals.
P.S. Comment me if somebody needs good examples of working codes of importing different certificates.

I got the same problem when trying to add a self signed certificate in Root trust location. It was prompting me the security warning.
Security Warning
With the following code I am now able to add the self signed certificate silently in the Root trust location.
HCERTSTORE hUIRootCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"Root");
CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc;
memset(&importSrc, 0, sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO));
importSrc.dwSize = sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO);
importSrc.dwSubjectChoice = CRYPTUI_WIZ_IMPORT_SUBJECT_FILE;
importSrc.pwszFileName = L"<certificate file>";
importSrc.pwszPassword = L"<your password>";
importSrc.dwFlags = CRYPT_EXPORTABLE;
bRet = CryptUIWizImport(CRYPTUI_WIZ_NO_UI | CRYPTUI_WIZ_IMPORT_TO_LOCALMACHINE, NULL, NULL, &importSrc, hUIRootCertStore);
If there is any other method please tell me.

Related

Differences in reading private key with libp11 and pkcs11-engine

I'm trying to implement SSL client authentication in C++ using credentials stored on a smartcard.
In essence, this means using the openssl library to initialize an SSL context using a certificate and a private key, then using this context for all future https connections.
The libraries i've come across to help me with this are libp11 and its pkcs11-engine module, found here: https://github.com/OpenSC/libp11 .
A scenario in which my code actually works as intended with our webserver is where the certificate is listed and retrieved via libp11 and the private key is retrieved by id using the pkcs11 engine:
PKCS11_enumerate_certs(slot->token, &certs, &ncerts);
X509 *cert = certs[0].x509;
EVP_PKEY *pkey = ENGINE_load_private_key(pkcs11_eng, "pkey_id", NULL, NULL);
if (!SSL_CTX_use_certificate(context->ctx, cert )) {
throw SSLError::getLastError();
}
if (!SSL_CTX_use_PrivateKey(context->ctx, pkey )) {
throw SSLError::getLastError();
}
if (!SSL_CTX_check_private_key(context->ctx)) {
throw SSLError::getLastError();
}
However, for consistency and to keep things simple, it is preferred to use libp11 for both of these retrievals as this would also eliminate the use of a whole other component (the pkcs11-engine).
The issue i'm having is that when retrieving pkey with:
PKCS11_KEY *key = PKCS11_find_key(&certs[0]);
EVP_PKEY pkey = PKCS11_get_private_key(key)
And initializing ssl, the checks pass, but the following error is thrown by the SSL_connect() function:
error:80009005:Vendor defined:PKCS11_rsa_encrypt:General Error
Basically the private key works when it's retrieved via engine but an error is thrown when using libp11, which is strange because looking through the code on github for the engine, i noticed the same p11 calls being made that i was using.
If anyone has any experience with this topic and might know what's going on here, it would help me enormously.
This was my bad. I was initializing the pkcs11 engine with our own dll implementing pkcs11 but using the opensc dll when initializing p11. I guess the lesson learned here is always look carefully before copy/pasting code

WinVerifyTrust error code handling

I've been tasked with determining whether a particular DLL from a third party company has been tampered with, after installation on a user's system. I've never done anything related to digital signing before. I'm trying to set up a test on my own system using WinVerifyTrust.
{
WINTRUST_FILE_INFO wtfi;
wtfi.cbStruct = sizeof(WINTRUST_FILE_INFO);
wtfi.pcwszFilePath = TEXT("*****.dll");
//wtfi.hFile = DllHandle;
wtfi.pgKnownSubject = NULL;
GUID wtvPolicyGUID = DRIVER_ACTION_VERIFY;
WINTRUST_DATA wtd;
wtd.cbStruct = sizeof(WINTRUST_DATA);
wtd.pPolicyCallbackData = NULL;
wtd.pSIPClientData = NULL;
wtd.dwUIChoice = WTD_UI_NONE;
wtd.fdwRevocationChecks = WTD_REVOKE_NONE;
wtd.dwUnionChoice = WTD_CHOICE_FILE;
wtd.pFile = &wtfi;
wtd.dwStateAction = WTD_STATEACTION_IGNORE;
wtd.pwszURLReference = NULL;
wtd.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
//wtd.pSignatureSettings = NULL; // Win8 and Server2012 only?
LONG result = WinVerifyTrust( NULL, &wtvPolicyGUID, &wtd);
debugf(TEXT("Validation result: 0x%08x"), result);
}
This is returning 0x57. From what I've gathered from MSDN, errors come from a supplied trust provider. I don't really know what the trust provider is or what error messages it can return.
I've linked in WinTrust.dll and WinTrust.lib, so I presume that means I'm using Microsoft's "Software Publisher Trust Provider". Is this recommended, or are there better ones out there? Should you be using one specific to / provided by the software publisher whose product you're analyzing?
SoftPub.h contains the GUID input value, but does not seem to provide output error codes. Any help in tracking down their response code list is appreciated.
Thanks in advance.
EDIT: I have since figured out that this library uses error codes provided by winerror.h. 0x57 is "ERROR_INVALID_PARAMETER", so I'm reviewing what it could be complaining about. I also tried switching the Policy GUID to WINTRUST_ACTION_GENERIC_VERIFY_V2, which returned error TRUST_E_SUBJECT_FORM_UNKNOWN. Neither error code is particularly illuminating about what the ultimate issue is.
EDIT 2: I also ran Microsoft's SignTool.exe on the dll in question, and got the following output:
SignTool Error: A certificate chain processed, but terminated in a root
certificate which is not trusted by the trust provider.
Number of errors: 1
So it seems like I need to change the trust provider I'm using. After discussing with the software manufacturer, the task is being dropped in favor of another approach.
According to MSDN it seems that you should set
dwStateAction = WTD_STATEACTION_VERIFY;
Also I would try setting
wtfi.hFile = NULL;
or when giving the file handle setting
wtfi.pcwszFilePath = NULL;
(It's not quite clear to me if you are providing hFile or not. And I would not set both hFile and pcwszFilePath to valid values.)
Another point to check: if you are compiling for Windows 8 or Windows Server 2012 you will have the struct member pSignatureSettings and will need to initialize it. Take care to set cbStruct so that pSignatureSettings is not included or to properly initialize pSignatureSettings.

SSL certificate verify failure using django and Mozilla Persona

I'm trying to build a simple web app using Django. I'd like a minimal user model with verification using Mozilla Persona. Using Persona happens without a hitch, until the SSL certificate fails when tossing the authentication (success or failure) back to the Django app.
I know there is a lot on Stack Overflow already about SSL errors, but I haven't turned up anything that works in this case. For example, trying to use verify = False when using the requests package still produces the error.
I was able to replicate the error in a minimal example app using the default settings for a new Django project and following the boilerplate installation for django_browserid. Even if this can be hacked, it might be worth noting in either the django_browserid docs or the Persona documentation if someone knows how to remedy this annoying bug.
I've put this minimal example with instructions on GitHub.com at:
https://github.com/pedmiston/ssl_error
The actual error is, with [blob] substituted in place of the assertion.
Error while verifying assertion [blob] with audience http://localhost:8000.
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
I'm on OSX Mavericks.
Update: I was able to get the minimal example to pass using sigmavirus24's answer, by adding the following to my virtualenv's src/django_browserid/base.py
class RemoteVerifier(object):
"""
Verifies BrowserID assertions using a remote verification service.
By default, this uses the Mozilla Persona service for remote verification.
"""
verification_service_url = 'https://verifier.login.persona.org/verify'
requests_parameters = {
'timeout': 5,
'verify': False,
}
# ...
This is great, and it gets the minimal example to pass (and assures me that this isn't really a django_browserid or Persona error?).
However, it does just kind of by-pass the merits of the verification procedure. Now that the error has been localized, any suggestions for how to fix it?
I've been reading that there were some changes in OS X when Mavericks came around, in a switch from open_ssl to Apple's own Secure Transport engine. If this is the cause of the problem I'm having, then it might be worth knowing for others who run into a similar problem when using Mavericks.
Looking at your example app and it's sole dependency it seems your trouble is coming from this line in django_browserid. I'm not familiar with your app or django_browserid but if you can pass verify=False to https://github.com/mozilla/django-browserid/blob/66641335751b869562ba7a554e61ca56bc880257/django_browserid/base.py#L167 this should solve your problems. In other words, if you specify which Verifier you use, then it should do something like
verifier = RemoteVerifier()
verifier.requests_parameters['verify'] = False
# or
verifier.verify(verify=False)
Of course you didn't show any code where you were doing that so that could be what you meant when you said:
For example, trying to use verify = False when using the requests package still produces the error.
But I can't tell that from the code you have posted.

Getting certificate chain to a private root

I'm trying to verify that the certificate from a signature chains back to a particular root certificate, which is not trusted by Windows (it's a private certificate for the app).
My current attempt to do this involves creating a chaining engine which only trusts the specific certificate I want as the root, so that no other chains can be generated.
HCERTSTORE hPrivateRootStore = CertOpenStore(CERT_STORE_PROV_FILENAME, dwEncoding,
NULL, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG,
_T("C:\\Test\\PrivateRoot.cer"));
CERT_CHAIN_ENGINE_CONFIG config;
memset(&config, 0, sizeof(config));
config.cbSize = sizeof(config);
config.hRestrictedTrust = hPrivateRootStore;
config.dwFlags = CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL | CERT_CHAIN_ENABLE_SHARE_STORE;
HCERTCHAINENGINE hEngine;
CertCreateCertificateChainEngine(&config, &hEngine);
CERT_CHAIN_PARA params;
memset(&params, 0, sizeof(params));
params.cbSize = sizeof(params);
PCCERT_CHAIN_CONTEXT chains = NULL;
if (CertGetCertificateChain(hEngine, pCertContext, NULL, hStore, &params,
0, NULL, &chains))
...
(error checking omitted for clarity; pCertContext and hStore came from CryptQueryObject extracting the signature and related certificates from a signed binary file.)
Unfortunately, this doesn't seem to work; despite using a custom chaining engine it still seems to be searching the OS store, and either doesn't find a chain or finds one to a different root (which is trusted by the OS). I can only get the chain I want by adding my private root certificate to the OS trusted store.
I've also tried setting config.hRestrictedOther to an empty memory store, since the docs suggest that having hRestrictedTrust non-NULL will bring in the system stores again, but that doesn't make any difference.
Is there something I'm missing, or a better way to do this?
Edit: just to give a bit more context, I'm trying to do something similar to the driver signing certificates, where the signing certificate chains back to two different roots: one standard CA root trusted by the OS and one internal root (which in drivers is also trusted by the OS but in my case will only be trusted by my app). The cross occurs somewhere mid-way up the "main" chain; there could potentially be a number of different files all signed with different "real" CAs but still chained back to my internal certificate.
I've found a half-baked workaround now; it's a little ugly but it does kinda work. I got the basic idea from Chromium's test suite; it involves installing a hook into Crypt32 such that when it tries to open the system stores to build the chain it gets my custom store instead, containing only my desired certificate.
The good is that this seems to force CertGetCertificateChain to go "past" the real CA certificate and chain all the way to my custom certificate, instead of stopping at the CA certificate (which is what it usually does when that is trusted).
The bad is that it doesn't seem to stop it from building chains to and trusting any other CA certificate. I can work around that by explicitly verifying that the root of the chain is the certificate I wanted, but it's less than ideal, and I'm not sure if there are situations which will trip it up.
Still looking for any better solutions; I'm definitely getting the impression that I'm taking the wrong path somewhere.
Ok, new plan. I'm now just walking the chain manually (since I know that all of the certificates I care about will be in the hStore extracted from the signed .exe), with basic structure like this:
Use WinVerifyTrust to do basic "is it not tampered" authentication.
Use CryptQueryObject to obtain certificate store hStore from the .exe
Use CryptMsgGetParam and CertFindCertificateInStore to find the signing certificate from hStore.
Starting from the signing certificate, use CertFindCertificateInStore with CERT_FIND_SUBJECT_NAME in a loop to find the potential issuer certificates; keep walking back until I hit a self-signed certificate or find my desired root (checking for a match via CertComparePublicKeyInfo).
Abandon a particular branch if CertVerifySubjectCertificateContext says that the signatures don't match.
Seems cleaner than the previous approaches I was trying. Thoughts/comments/alternatives?
(Something which in some ways does seem to make more sense would be to add an additional custom countersignature [similar to the timestamping] instead of trying to chain certificates like this, but I can't find any information on doing that, or what the pros/cons are.)

What's the correct way to verify an SSL certificate in Win32?

I want to verify an SSL certificate in Win32 using C++. I think I want to use the Cert* API so that I can get the benefit of the Windows certificate store. This is what I've come up with.
Is it correct?
Is there a better way to do this?
Am I doing anything wrong?
bool IsValidSSLCertificate( PCCERT_CONTEXT certificate, LPWSTR serverName )
{
LPTSTR usages[] = { szOID_PKIX_KP_SERVER_AUTH };
CERT_CHAIN_PARA params = { sizeof( params ) };
params.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
params.RequestedUsage.Usage.cUsageIdentifier = _countof( usages );
params.RequestedUsage.Usage.rgpszUsageIdentifier = usages;
PCCERT_CHAIN_CONTEXT chainContext = 0;
if ( !CertGetCertificateChain( NULL,
certificate,
NULL,
NULL,
&params,
CERT_CHAIN_REVOCATION_CHECK_CHAIN,
NULL,
&chainContext ) )
{
return false;
}
SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslPolicy = { sizeof( sslPolicy ) };
sslPolicy.dwAuthType = AUTHTYPE_SERVER;
sslPolicy.pwszServerName = serverName;
CERT_CHAIN_POLICY_PARA policy = { sizeof( policy ) };
policy.pvExtraPolicyPara = &sslPolicy;
CERT_CHAIN_POLICY_STATUS status = { sizeof( status ) };
BOOL verified = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
chainContext,
&policy,
&status );
CertFreeCertificateChain( chainContext );
return verified && status.dwError == 0;
}
You should be aware of RFC3280 section 6.1 and RFC5280 section 6.1. Both describe algorithms for validating certificate paths. Even though Win32 API takes care of some things for you, it could still be valuable to know about the process in general.
Also, here’s a (in my opinion) pretty trustworthy reference: Chromium certificate verification code.
Overall, I think your code isn't incorrect. But here’s a few things I’d look into/change, if I were you:
1. Separate Common Name Validation
Chromium validates certificate common name separately from the chain. Apparently they've noticed some problems with it. See the comments for their rationale:
cert_verify_proc.win.cc:731 // Certificate name validation happens separately, later, using an internal
cert_verify_proc.win.cc:732 // routine that has better support for RFC 6125 name matching.
2. Use CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT
Chromium also uses the CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT flag instead of CERT_CHAIN_REVOCATION_CHECK_CHAIN. I actually started to looking into this before I found their code, and it reinforced my belief that you should use CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT.
Even though both aforementioned RFCs specify that a self-signed trust anchor is not considered part of a chain, the documentation for CertGetCertificateChain (http://msdn.microsoft.com/en-us/library/windows/desktop/aa376078(v=vs.85).aspx) says it builds a chain up to, if possible, a trusted root certificate. A trusted root certificate is defined (on the same page) as a trusted self-signed certificate.
This eliminates the possibility that *EXCLUDE_ROOT might skip revocation checking for a non-root trust anchor (Win32 actually requires trust-anchors to be self-signed, even though it is not required by any RFCs. Though this is not officially documented).
Now, since a root CA certificate can not revoke itself (the CRL could not be signed/verified), it seems to me that these two flags are identical.
I did some googling and stumbled across this forum post: http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/9f95882a-1a68-477a-80ee-0a7e3c7ae5cf/x509revocationflag-question?forum=windowssecurity. A member of .NET Product Group (supposedly) claims that the flags in practice act the same, if the root is self-signed (in theory, the ENTIRE_CHAIN flag would check the root certificate for revocation if it included a CDP extension, but that can’t happen).
He also recommends to use the *EXCLUDE_ROOT flag, because the other flag could cause an unnecessary network request, if the self-signed root CA includes the CDP extension.
Unfortunately:
I can’t find any officially documented explanation on the differences between the two flags.
Even though it is likely that the linked discussion applies to the same Win32 API flags under the hood of .NET, it is not guaranteed.
To be completely sure that it’s ok to use CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, I googled a bit more and found the Chromium SSL certificate verification code I linked to at the top of my reply.
As an added bonus, the Chromium cert_verify_proc_win.cc file contains the following hints about IE verification code:
618: // IE passes a non-NULL pTime argument that specifies the current system
619: // time. IE passes CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT as the
620: // chain_flags argument.
Not sure how they’d know this, but at this point I’d feel comfortable using CERT_CHAIN_REVOCATION_CHECK_EXCLUDE_ROOT.
3. Different Accepted Certificate Usages
I noticed Chromium also specifies 3 certificate usages instead of 1:
szOID_PKIX_KP_SERVER_AUTH,
szOID_SERVER_GATED_CRYPTO,
szOID_SGC_NETSCAPE
From what I can gather through Google, the other usages can be required by older web browsers, otherwise they can fail to establish a secure connection.
If Chromium deems fit to include these usages, I'd follow suit.
Note that if you change your code, you should also set params.RequestedUsage.dwType to USAGE_MATCH_TYPE_OR instead of USAGE_MATCH_TYPE_AND.
—
I can’t think of any other comments at the moment. But if I were you, I’d check out Chromium source myself (and maybe Firefox too) - just to be sure I haven’t missed anything.
I think the best answer depends on what exactly you are attempting to do.
I will caution you that SSL is based on the assumption that Both endpoints want a secure connection. If either endpoint isn't interested in maintaining security then there is none.
Its a trivial effort to put byte codes in your distributed code that simply returns true for this function. That's why windows moved a lot of validation into the kernel. But they didn't anticipate people running windows on virtual hardware, which makes circumventing the OS just about as trivial.
Now consider that you expect to be provided a cert from some source, but pretending that that source couldn't be provided the same information from a reliable source. And then hand it to you. So You cannot rely on certificates to "prove" anyone is anyone in particular.
The only protection gained from certificates are in preventing outsiders, not endpoints, from breaching the confidentiality of the message being transported.
Any other use is doomed to fail, and it will fail eventually with potentially catastrophic results.
Sorry for the big post. The comment section has a word limit.
The functions CertGetCertificateChain and CertVerifyCertificatePolicy go together. This part is correct.
For CertGetCertificateChain the flag can be set to any of the following three if you want to check for revocation:
CERT_CHAIN_REVOCATION_CHECK_END_CERT
CERT_CHAIN_REVOCATION_CHECK_CHAIN
CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT.
Only one of them can be used, these three options cannot be ORed. Beside one of these flags you can consider how the chain should be created; using local cache or just CRL or OCSP. For these considerations read this link.
Error in executing the function or more simply if the return value is 0, it does not mean the certificate is invalid, rather you were unable to perform the operation. For error information use GetLastError(). So your logic of returning false is wrong, it is more of a case of throwing the error and let the client code decide whether to try again or go on to do other stuff.
In this link there is a section called "classify the error", please read that. Basically you should check certChainContext->TrustStatus.dwErrorStatus. Here a list of error statuses will be ORed. Please check CERT_TRUST_STATUS msdn reference. So here you can have your business logic. For example, if you find the error status of the value (CERT_TRUST_REVOCATION_STATUS_UNKNOWN | CERT_TRUST_IS_OFFLINE_REVOCATION) that certificate revocation check could not be performed, you have the option to decide what you want (let the cert go or still mark it as invalid).
So, before going to call CertVerifyCertificatePolicy you have the option to discard or already flag a validation error.
If you choose to come to CertVerifyCertificatePolicy, the chromium code is a wonderful reference regarding how to map policy_status.dwError to your error class/enum.