Beispiel #1
3
BOOL ClientAuthenticate(const char *name, const char *hostname)
{
	int rc, rcISC;
	SEC_WINNT_AUTH_IDENTITY nameAndPwd = {0};
	int bytesReceived = 0, bytesSent = 0;
	char myTokenSource[256];
	TimeStamp useBefore;
	DWORD ctxReq, ctxAttr;
	int dwRead,dwWritten;
	// input and output buffers
	SecBufferDesc obd, ibd;
	SecBuffer ob, ib[2];
	BOOL haveInbuffer = FALSE;
	BOOL haveContext = FALSE;
	SCHANNEL_CRED cred = {0};
	PCCERT_CONTEXT cert = NULL;

	HANDLE hMy = CertOpenSystemStore(0,"MY");
	if(!hMy)
	{
		rcISC = SEC_E_NO_CREDENTIALS;
		server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC));
		return FALSE;
    }

	if(name)
	{
		cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t *)cvs::wide(name),	NULL);
		if(!cert)
		{
			rcISC = SEC_E_NO_CREDENTIALS;
			server_error(1,"No certificate for '%s': %s\n",name,GetErrorString(rcISC));
			return FALSE;
		}
	}

	cred.dwVersion = SCHANNEL_CRED_VERSION;
	cred.dwFlags = SCH_CRED_USE_DEFAULT_CREDS;

	if(cert)
	{
		cred.cCreds     = 1;
		cred.paCred     = &cert;
	}

	rc = AcquireCredentialsHandle( NULL, "SChannel", SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &credHandle, &useBefore );

	ctxReq = ISC_REQ_MANUAL_CRED_VALIDATION | ISC_REQ_INTEGRITY | ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_STREAM | ISC_REQ_USE_SUPPLIED_CREDS;
	strncpy(myTokenSource,hostname,sizeof(myTokenSource));

	CertCloseStore(hMy,0);

	ib[0].pvBuffer = NULL;

	while ( 1 )
	{
		obd.ulVersion = SECBUFFER_VERSION;
		obd.cBuffers = 1;
		obd.pBuffers = &ob; // just one buffer
		ob.BufferType = SECBUFFER_TOKEN; // preping a token here
		ob.cbBuffer = secPackInfo->cbMaxToken;
		ob.pvBuffer = malloc(secPackInfo->cbMaxToken);

		rcISC = InitializeSecurityContext( &credHandle, haveContext? &contextHandle: NULL,
			myTokenSource, ctxReq, 0, SECURITY_NATIVE_DREP, haveInbuffer? &ibd: NULL,
			0, &contextHandle, &obd, &ctxAttr, &useBefore );

		if ( ib[0].pvBuffer != NULL )
		{
			free(ib[0].pvBuffer);
			ib[0].pvBuffer = NULL;
		}

		if ( rcISC == SEC_I_COMPLETE_AND_CONTINUE || rcISC == SEC_I_COMPLETE_NEEDED )
		{
			CompleteAuthToken( &contextHandle, &obd );
			if ( rcISC == SEC_I_COMPLETE_NEEDED )
				rcISC = SEC_E_OK;
			else if ( rcISC == SEC_I_COMPLETE_AND_CONTINUE )
				rcISC = SEC_I_CONTINUE_NEEDED;
		}

		if(rcISC<0)
		{
			server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC));
		}

		// send the output buffer off to the server
		if ( ob.cbBuffer != 0 )
		{
			if((dwWritten=tcp_write( (const char *) ob.pvBuffer, ob.cbBuffer))<=0)
				break;
			bytesSent += dwWritten;
		}
		free(ob.pvBuffer);
		ob.pvBuffer = NULL;
		ob.cbBuffer = 0;

		if ( rcISC != SEC_I_CONTINUE_NEEDED )
			break;

		// prepare to get the server's response
		ibd.ulVersion = SECBUFFER_VERSION;
		ibd.cBuffers = 2;
		ibd.pBuffers = ib; // just one buffer
		ib[0].BufferType = SECBUFFER_TOKEN; // preping a token here
		ib[0].cbBuffer = secPackInfo->cbMaxToken;
		ib[0].pvBuffer = malloc(secPackInfo->cbMaxToken);
		ib[1].cbBuffer = 0;
		ib[1].pvBuffer = NULL;
		ib[1].BufferType = SECBUFFER_EMPTY; // Spare stuff

		// receive the server's response
		if((dwRead=tcp_read(ib[0].pvBuffer,ib[0].cbBuffer))<=0)
			break;
		bytesReceived += dwRead;

		// by now we have an input buffer and a client context

		haveInbuffer = TRUE;
		haveContext = TRUE;
	}

	// we arrive here as soon as InitializeSecurityContext()
	// returns != SEC_I_CONTINUE_NEEDED.

	if ( rcISC != SEC_E_OK )
		haveContext = FALSE;
	else
		haveContext = TRUE; /* Looopback kerberos needs this */

	return haveContext;
}
Beispiel #2
0
BOOL MSCAPI_Manager::BuildCertificateChain(HCRYPTPROV provider, OpString &label, OpString &shortname, SSL_ASN1Cert_list &cert)
{
	CERT_PUBLIC_KEY_INFO *pubkey = (CERT_PUBLIC_KEY_INFO *) g_memory_manager->GetTempBuf2k();
	DWORD len;

	label.Empty();
	shortname.Empty();
	cert.Resize(0);

	if(!hMYSystemStore)
		return FALSE;

	len = g_memory_manager->GetTempBuf2kLen();
	if(!CryptExportPublicKeyInfo(provider,  /*AT_SIGNATURE*/ AT_KEYEXCHANGE, (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), pubkey, &len))
	{
		int err0 = GetLastError();
		op_memset(&pubkey, 0, sizeof(pubkey));
		len = g_memory_manager->GetTempBufLen();
		if(!CryptExportPublicKeyInfo(provider, /* AT_KEYEXCHANGE */ AT_SIGNATURE, (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), pubkey, &len))
		{
			int err = GetLastError();
			return FALSE;
		}
	}
		
	PCCERT_CONTEXT cert_item = NULL;
	
	cert_item = CertFindCertificateInStore(hMYSystemStore, (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), 0, CERT_FIND_PUBLIC_KEY, pubkey, cert_item);
	if(!cert_item && hUserDSSystemStore)
		cert_item = CertFindCertificateInStore(hUserDSSystemStore, (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), 0, CERT_FIND_PUBLIC_KEY, pubkey, cert_item);

	if(!cert_item)
		return FALSE;

	
	len = CertNameToStr((X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), 
		&cert_item->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
	

	if(len)
	{
		if(shortname.Reserve(len+1) == NULL)
			return OpStatus::ERR_NO_MEMORY;
		
		len = CertNameToStr((X509_ASN_ENCODING | PKCS_7_ASN_ENCODING), 
			&cert_item->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, shortname.DataPtr(), shortname.Capacity());
	}
	
	cert.Resize(1);
	if(cert.Error())
		return FALSE();
	
	cert[0].Set(cert_item->pbCertEncoded, cert_item->cbCertEncoded);
	
	if(cert.Error() || cert[0].GetLength() == 0)
		return FALSE;

	return TRUE;
}
Beispiel #3
0
static const CERT_CONTEXT *find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
{
    /* Find, and use, the desired certificate from the store. The
     * 'cert_prop' certificate search string can look like this:
     * SUBJ:<certificate substring to match>
     * THUMB:<certificate thumbprint hex value>, e.g.
     *     THUMB:f6 49 24 41 01 b4 fb 44 0c ce f4 36 ae d0 c4 c9 df 7a b6 28
     */
    const CERT_CONTEXT *rv = NULL;

    if (!strncmp(cert_prop, "SUBJ:", 5)) {
	/* skip the tag */
	cert_prop += 5;
	rv = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
		0, CERT_FIND_SUBJECT_STR_A, cert_prop, NULL);

    } else if (!strncmp(cert_prop, "THUMB:", 6)) {
	unsigned char hash[255];
	char *p;
	int i, x = 0;
	CRYPT_HASH_BLOB blob;

	/* skip the tag */
	cert_prop += 6;
	for (p = (char *) cert_prop, i = 0; *p && i < sizeof(hash); i++) {
	    if (*p >= '0' && *p <= '9')
		x = (*p - '0') << 4;
	    else if (*p >= 'A' && *p <= 'F')
		x = (*p - 'A' + 10) << 4;
	    else if (*p >= 'a' && *p <= 'f')
		x = (*p - 'a' + 10) << 4;
	    if (!*++p)	/* unexpected end of string */
		break;
	    if (*p >= '0' && *p <= '9')
		x += *p - '0';
	    else if (*p >= 'A' && *p <= 'F')
		x += *p - 'A' + 10;
	    else if (*p >= 'a' && *p <= 'f')
		x += *p - 'a' + 10;
	    hash[i] = x;
	    /* skip any space(s) between hex numbers */
	    for (p++; *p && *p == ' '; p++);
	}
	blob.cbData = i;
	blob.pbData = (unsigned char *) &hash;
	rv = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
		0, CERT_FIND_HASH, &blob, NULL);

    }

    return rv;
}
Beispiel #4
0
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;
}
//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;
}
Beispiel #6
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;
		}
	}
CertificateCollection qca_get_systemstore(const QString &provider)
{
    CertificateCollection col;
    HCERTSTORE hSystemStore;
    hSystemStore = CertOpenSystemStoreA(0, "ROOT");
    if(!hSystemStore)
        return col;
    PCCERT_CONTEXT pc = NULL;
    while(1)
    {
        pc = CertFindCertificateInStore(
                 hSystemStore,
                 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                 0,
                 CERT_FIND_ANY,
                 NULL,
                 pc);
        if(!pc)
            break;
        int size = pc->cbCertEncoded;
        QByteArray der(size, 0);
        memcpy(der.data(), pc->pbCertEncoded, size);

        Certificate cert = Certificate::fromDER(der, 0, provider);
        if(!cert.isNull())
            col.addCertificate(cert);
    }
    CertCloseStore(hSystemStore, 0);
    return col;
}
Beispiel #8
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;
}
Beispiel #9
0
		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;
		}
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);
	}
}
Beispiel #11
0
DWORD StoreAuthorityCert(PCCERT_CONTEXT pCertContext, unsigned char KeyUsageBits)
{
	DWORD dwRet = 0;
	HCERTSTORE hMemoryStore = NULL;
	PCCERT_CONTEXT pDesiredCert = NULL;

	if ( 0 == memcmp ( pCertContext->pCertInfo->Issuer.pbData, pCertContext->pCertInfo->Subject.pbData, pCertContext->pCertInfo->Subject.cbData	)	)
	{
		hMemoryStore = CertOpenSystemStore ((HCRYPTPROV_LEGACY)NULL, TEXT("ROOT"));
	}
	else
	{
		hMemoryStore = CertOpenSystemStore ((HCRYPTPROV_LEGACY)NULL, TEXT("CA"));
	}

	if (hMemoryStore == NULL)
	{
		dwRet = GetLastError();
		printf("StoreAuthorityCerts: Unable to open the system certificate store. Error code: %d.\n",dwRet);
		return dwRet;
	}

	pDesiredCert = CertFindCertificateInStore( hMemoryStore
		, X509_ASN_ENCODING
		, 0
		, CERT_FIND_EXISTING
		, pCertContext
		, NULL
		);
	if( pDesiredCert )
	{
		CertFreeCertificateContext(pDesiredCert);
	}
	else if (GetLastError())
	{
		CertAddEnhancedKeyUsageIdentifier (pCertContext, szOID_PKIX_KP_EMAIL_PROTECTION);
		CertAddEnhancedKeyUsageIdentifier (pCertContext, szOID_PKIX_KP_SERVER_AUTH);
		if(CertAddCertificateContextToStore(hMemoryStore, pCertContext, CERT_STORE_ADD_NEWER, NULL))
		{
			printf("StoreUserCerts: Certificate context added to store.\n");
			dwRet = 0;
		}
		else
		{
			dwRet = GetLastError();
			printf("StoreAuthorityCerts: Unable to add certificate context to store. Error code: %d.\n",dwRet);
		}
	}
	CertCloseStore (hMemoryStore, CERT_CLOSE_STORE_FORCE_FLAG);

	return dwRet;

}
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;
}
Beispiel #13
0
bool CertStore::find( const QSslCertificate &cert ) const
{
	if( !d->s )
		return false;

	PCCERT_CONTEXT context = d->certContext( cert );
	if( !context )
		return false;
	PCCERT_CONTEXT result = CertFindCertificateInStore( d->s, X509_ASN_ENCODING,
		0, CERT_FIND_SUBJECT_CERT, context->pCertInfo, 0 );
	CertFreeCertificateContext( context );
	return result;
}
Beispiel #14
0
std::auto_ptr<Certificate> Store::findCertificate(CERT_INFO* ci)
{
    PCCERT_CONTEXT cert = CertFindCertificateInStore(m_hCertStore,
                          X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                          0,
                          CERT_FIND_SUBJECT_CERT,
                          ci,
                          NULL);

    std::auto_ptr<Certificate> certificate = new Certificate(cert);

    return certificate;
}
Certificado* AlmacenCertificadoCAPI::loadCertificado(ClaveBusqueda claveBusqueda, void *data)
{
	Certificado		*ret;
	PCCERT_CONTEXT	cert;
	DWORD tipoBusqueda;
	void *parametros;
	bool ok;

	// Obtener el certificado.
	//
	// Para firmar, no vale un certificado cualquiera, sino uno que contenga una clave
	// privada. Si lo que queremos es validar una firma, con que tenga clave pública
	// (todos la tienen) es suficiente.
	//
	// La búsqueda del certificado se puede hacer por varios campos de los que aparecen
	// en la pestaña "Detalles" del certificado.
	//

	if (handle == NULL)
		return (NULL);

	ret = NULL;

	parametros = calcularParametrosBusqueda(claveBusqueda, data, tipoBusqueda);

	if (tipoBusqueda != 0xFFFFFFFF)
	{
		cert = CertFindCertificateInStore(handle, TIPO_CODIFICACION, 0,
								tipoBusqueda, parametros, NULL);

		// una vez terminada la búsqueda, podemos liberar sus parámetros, que desde
		// aquí no sabemos de qué tipo son y cuando ocupan
		liberarParametrosBusqueda(claveBusqueda, parametros);

		if (cert != NULL)
		{
			// comprobar si el certificado realmente corresponde al CSP (en caso de haber CSP)
			if (csp != 0)
				ok = CorrespondeCertificadoConCSP(cert);
			else
				ok = true;

			if (ok)
				ret = crearCertificado(cert);
		}
	}

	return (ret);
}
PCCERT_CONTEXT findCertificateInStore (HCERTSTORE certStoreHandle, const std::string &certName) {
	if (!boost::iequals(certName.substr(0, 5), "sha1:")) {

		// Find client certificate. Note that this sample just searches for a
		// certificate that contains the user name somewhere in the subject name.
		return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /*dwFindFlags*/ 0, CERT_FIND_SUBJECT_STR_A, /* *pvFindPara*/certName.c_str(), /*pPrevCertContext*/ NULL);
	}


	std::string hexstring = certName.substr(5);
	ByteArray byteArray = Hexify::unhexify(hexstring);
	CRYPT_HASH_BLOB HashBlob;

	if (byteArray.size() != SHA1_HASH_LEN) {
		return NULL;
	}
	HashBlob.cbData = SHA1_HASH_LEN;
	HashBlob.pbData = static_cast<BYTE *>(vecptr(byteArray));

	// Find client certificate. Note that this sample just searches for a
	// certificate that contains the user name somewhere in the subject name.
	return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /* dwFindFlags */ 0, CERT_FIND_HASH, &HashBlob, /* pPrevCertContext */ NULL);

}
Beispiel #17
0
PCCERT_CONTEXT FindCertificateByHash(HCERTSTORE hSystemStore, unsigned char *hash)
{
    PCCERT_CONTEXT pCertContext = NULL;
    CRYPT_HASH_BLOB toFindData;

    toFindData.cbData = SK_HASH_LEN;
    toFindData.pbData = hash;

    pCertContext = CertFindCertificateInStore(hSystemStore,
        X509_ASN_ENCODING |
        PKCS_7_ASN_ENCODING, 0,
        CERT_FIND_HASH, &toFindData,
        NULL);
    return pCertContext;
}
Beispiel #18
0
std::auto_ptr<Certificate> Store::getIssuerOf(Certificate* cert)
{
    PCCERT_CONTEXT c = CertFindCertificateInStore(m_hCertStore,
                       X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                       0,
                       CERT_FIND_SUBJECT_NAME,
                       &(cert->getContext()->pCertInfo->Issuer),
                       0);

    if(!c)
    {
        return std::auto_ptr<Certificate>(0);
    }
    return std::auto_ptr<Certificate>(new Certificate(c));
}
Beispiel #19
0
std::auto_ptr<Certificate> Store::getNextCertificate()
{
    PCCERT_CONTEXT cert = CertFindCertificateInStore(m_hCertStore,
                          X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                          0,
                          CERT_FIND_ANY,
                          0,
                          m_prevCert);

    m_prevCert = cert;

    if(!cert)
    {
        return std::auto_ptr<Certificate>(0);
    }
    return std::auto_ptr<Certificate>(new Certificate(cert));
}
Beispiel #20
0
static BOOL find_and_delete_cert_in_store(HCERTSTORE store, PCCERT_CONTEXT cert)
{
    CERT_ID id;
    PCCERT_CONTEXT found;

    id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
    memcpy(&id.u.IssuerSerialNumber.Issuer,
     &cert->pCertInfo->Issuer, sizeof(CERT_NAME_BLOB));
    memcpy(&id.u.IssuerSerialNumber.SerialNumber,
     &cert->pCertInfo->SerialNumber, sizeof(CRYPT_INTEGER_BLOB));
    found = CertFindCertificateInStore(store, X509_ASN_ENCODING, 0,
     CERT_FIND_CERT_ID, &id, NULL);
    if (!found)
        return FALSE;

    CertDeleteCertificateFromStore(found);

    return TRUE;
}
Beispiel #21
0
    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;
        }
    }
Beispiel #22
0
int main()
{
	test();

	HCERTSTORE myCertStoreHandle = CertOpenSystemStore(NULL, TEXT("MY"));
	
	const CERT_CONTEXT* pCertificateContext = CertFindCertificateInStore(
		myCertStoreHandle,
		X509_ASN_ENCODING, 
		0,
		CERT_FIND_SUBJECT_STR,
		TEXT("localhost"),
		NULL);

	SchannelCredentialData schannelCredentialData(&pCertificateContext);

	SchannelCredential schannelCredential(SECPKG_CRED_INBOUND, &schannelCredentialData);

	SecBufferArray<2> inputBufferArray;
	initializeSecBuffer(inputBufferArray[0], SECBUFFER_TOKEN, tokenBuffer, 78);
	initializeSecBuffer(inputBufferArray[1], SECBUFFER_EMPTY, NULL, 0);

	SecBufferArray<1> outputBufferArray;
	initializeSecBuffer(outputBufferArray[0], SECBUFFER_TOKEN, NULL, 0);

	SecurityContext securityContext;
	
	SECURITY_STATUS result = securityContext.accept(
		schannelCredential,
		inputBufferArray,
		ASC_REQ_ALLOCATE_MEMORY,
		outputBufferArray);

	outputBufferArray.dump();

	ShowError(result);
}
    BinaryCertificate( const std::wstring &path )
        : store( 0 )
        , msg( 0 )
        , signerInfo( 0 )
        , certContext( 0 )
    {
        if( !CryptQueryObject( CERT_QUERY_OBJECT_FILE, path.c_str(),
                               CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY,
                               0, 0, 0, 0, &store, &msg, NULL ) )
            return;

        DWORD signerInfoSize;
        if( !CryptMsgGetParam( msg, CMSG_SIGNER_INFO_PARAM, 0, 0, &signerInfoSize ) )
            return;
        signerInfo = (PCMSG_SIGNER_INFO)LocalAlloc( LPTR, signerInfoSize );
        if( !CryptMsgGetParam( msg, CMSG_SIGNER_INFO_PARAM, 0, signerInfo, &signerInfoSize ) )
            return;

        CERT_INFO certInfo;
        certInfo.Issuer = signerInfo->Issuer;
        certInfo.SerialNumber = signerInfo->SerialNumber;
        certContext = CertFindCertificateInStore( store,
                      X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, &certInfo, 0 );
    }
Beispiel #24
0
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;
}
Beispiel #25
0
BOOL ServerAuthenticate(const char *hostname)
{
	int rc, rcISC, rcl;
	BOOL haveToken;
	int bytesReceived = 0, bytesSent = 0;
	TimeStamp useBefore;
	// input and output buffers
	SecBufferDesc obd, ibd;
	SecBuffer ob, ib[2];
	BOOL haveContext = FALSE;
	DWORD ctxReq,ctxAttr;
	int n;
	short len;
	SCHANNEL_CRED cred = {0};
	char host[256];
	struct addrinfo *ai=NULL, hints = {0};
	PCCERT_CONTEXT cert;

	HANDLE hMy = CertOpenSystemStore(0,"MY");
	if(!hMy)
	{
		rcISC = SEC_E_NO_CREDENTIALS;
		server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC));
		return FALSE;
	}

	if(!hostname)
	{
		gethostname (host, sizeof host);
		hints.ai_flags=AI_CANONNAME;
		if(getaddrinfo(cvs::idn(host),NULL,&hints,&ai))
			server_error (1, "can't get canonical hostname");
		hostname = ai->ai_canonname;
		cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t*)cvs::wide(cvs::decode_idn(hostname)),	NULL);
	}
	else
		cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t*)cvs::wide(hostname),	NULL);

	if(!cert)
	{
		rcISC = SEC_E_NO_CREDENTIALS;
		server_error(1,"No certificate for '%s': %s\n",hostname,GetErrorString(rcISC));
		return FALSE;
	}

	cred.cCreds     = 1;
	cred.paCred     = &cert;

	if(ai)
		freeaddrinfo(ai);

	cred.dwVersion = SCHANNEL_CRED_VERSION;
	cred.dwFlags = SCH_CRED_USE_DEFAULT_CREDS;

	rc = AcquireCredentialsHandle( NULL, "SChannel", SECPKG_CRED_INBOUND, NULL, &cred, NULL, NULL, &credHandle, &useBefore );
	if ( rc == SEC_E_OK )
		haveToken = TRUE;
	else
		haveToken = FALSE;

	CertCloseStore(hMy,0);

	while ( 1 )
	{
		// prepare to get the server's response
		ibd.ulVersion = SECBUFFER_VERSION;
		ibd.cBuffers = 2;
		ibd.pBuffers = ib; // just one buffer
		ib[0].BufferType = SECBUFFER_TOKEN; // preping a token here
		ib[0].cbBuffer = secPackInfo->cbMaxToken;
		ib[0].pvBuffer = malloc(ib[0].cbBuffer);
		ib[1].cbBuffer = 0;
		ib[1].pvBuffer = NULL;
		ib[1].BufferType = SECBUFFER_EMPTY; // Spare stuff

		// receive the client's POD

		rcl = read( current_server()->in_fd, ib[0].pvBuffer, ib[0].cbBuffer);
		if(rcl<=0)
		{
			rc = SEC_E_INTERNAL_ERROR;
			break;
		}

		// by now we have an input buffer

		obd.ulVersion = SECBUFFER_VERSION;
		obd.cBuffers = 1;
		obd.pBuffers = &ob; // just one buffer
		ob.BufferType = SECBUFFER_TOKEN; // preping a token here
		ob.cbBuffer = secPackInfo->cbMaxToken;
		ob.pvBuffer = malloc(secPackInfo->cbMaxToken);

		if(rc<0)
		{
			len=0;
			if((n=write(current_server()->out_fd,&len,sizeof(len)))<=0)
				break;
			break;
		}

		ctxReq = ASC_REQ_INTEGRITY | ASC_REQ_CONFIDENTIALITY | ASC_REQ_REPLAY_DETECT | ASC_REQ_SEQUENCE_DETECT | ASC_REQ_STREAM;

		rc = AcceptSecurityContext( &credHandle, haveContext? &contextHandle: NULL,
				&ibd, ctxReq, SECURITY_NATIVE_DREP, &contextHandle, &obd, &ctxAttr,
				&useBefore );

		if ( ib[0].pvBuffer != NULL )
		{
			free( ib[0].pvBuffer );
			ib[0].pvBuffer = NULL;
		}

		if ( rc == SEC_I_COMPLETE_AND_CONTINUE || rc == SEC_I_COMPLETE_NEEDED )
		{
			CompleteAuthToken( &contextHandle, &obd );
			if ( rc == SEC_I_COMPLETE_NEEDED )
				rc = SEC_E_OK;
			else if ( rc == SEC_I_COMPLETE_AND_CONTINUE )
				rc = SEC_I_CONTINUE_NEEDED;
		}

		// send the output buffer off to the server
		// warning -- this is machine-dependent! FIX IT!
		if ( rc == SEC_E_OK || rc == SEC_I_CONTINUE_NEEDED )
		{
			if ( ob.cbBuffer != 0 )
			{
				if((n=write(current_server()->out_fd,ob.pvBuffer, ob.cbBuffer))<=0)
					break;
				bytesSent += n;
			}
			free(ob.pvBuffer);
			ob.pvBuffer = NULL;
			ob.cbBuffer = 0;
		}
		else
		{
			break;
		}

		if ( rc != SEC_I_CONTINUE_NEEDED )
			break;

		haveContext = TRUE;
	}

	// we arrive here as soon as InitializeSecurityContext()
	// returns != SEC_I_CONTINUE_NEEDED.

	if ( rc != SEC_E_OK )
	{
		haveToken = FALSE;
	}

	if(rc<0)
		server_error(0,"[%08x] %s\n",rc, GetErrorString(rc));

	return haveToken?TRUE:FALSE;
}
Beispiel #26
0
/**
 * Checks to see if a file stored at filePath matches the specified info. This
 * only supports the name and issuer attributes currently.
 *
 * @param  filePath    The PE file path to check
 * @param  infoToMatch The acceptable information to match
 * @return ERROR_SUCCESS if successful, ERROR_NOT_FOUND if the info
 *         does not match, or the last error otherwise.
 */
DWORD
CheckCertificateForPEFile(LPCWSTR filePath,
                          CertificateCheckInfo &infoToMatch)
{
  HCERTSTORE certStore = NULL;
  HCRYPTMSG cryptMsg = NULL;
  PCCERT_CONTEXT certContext = NULL;
  PCMSG_SIGNER_INFO signerInfo = NULL;
  DWORD lastError = ERROR_SUCCESS;

  // Get the HCERTSTORE and HCRYPTMSG from the signed file.
  DWORD encoding, contentType, formatType;
  BOOL result = CryptQueryObject(CERT_QUERY_OBJECT_FILE,
                                 filePath,
                                 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
                                 CERT_QUERY_CONTENT_FLAG_ALL,
                                 0, &encoding, &contentType,
                                 &formatType, &certStore, &cryptMsg, NULL);
  if (!result) {
    lastError = GetLastError();
    goto cleanup;
  }

  // Pass in NULL to get the needed signer information size.
  DWORD signerInfoSize;
  result = CryptMsgGetParam(cryptMsg, CMSG_SIGNER_INFO_PARAM, 0,
                            NULL, &signerInfoSize);
  if (!result) {
    lastError = GetLastError();
    goto cleanup;
  }

  // Allocate the needed size for the signer information.
  signerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, signerInfoSize);
  if (!signerInfo) {
    lastError = GetLastError();
    goto cleanup;
  }

  // Get the signer information (PCMSG_SIGNER_INFO).
  // In particular we want the issuer and serial number.
  result = CryptMsgGetParam(cryptMsg, CMSG_SIGNER_INFO_PARAM, 0,
                            (PVOID)signerInfo, &signerInfoSize);
  if (!result) {
    lastError = GetLastError();
    goto cleanup;
  }

  // Search for the signer certificate in the certificate store.
  CERT_INFO certInfo;
  certInfo.Issuer = signerInfo->Issuer;
  certInfo.SerialNumber = signerInfo->SerialNumber;
  certContext = CertFindCertificateInStore(certStore, ENCODING, 0,
                                           CERT_FIND_SUBJECT_CERT,
                                           (PVOID)&certInfo, NULL);
  if (!certContext) {
    lastError = GetLastError();
    goto cleanup;
  }

  if (!DoCertificateAttributesMatch(certContext, infoToMatch)) {
    lastError = ERROR_NOT_FOUND;
    goto cleanup;
  }

cleanup:
  if (signerInfo) {
    LocalFree(signerInfo);
  }
  if (certContext) {
    CertFreeCertificateContext(certContext);
  }
  if (certStore) {
    CertCloseStore(certStore, 0);
  }
  if (cryptMsg) {
    CryptMsgClose(cryptMsg);
  }
  return lastError;
}
/*****************************************************************************
 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;
}
Beispiel #28
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);
}
Beispiel #29
0
void 
get_cert_time_left(
	char				*realm,
	CTimeSpan			*ptimeLeft
)
{
	HCERTSTORE			hStoreHandle		= NULL;
	PCCERT_CONTEXT		pCertContext		= NULL;      
	PCCERT_CONTEXT		prev_pCertContext	= NULL;      
	DWORD				dwCertEncodingType	= X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
	DWORD				dwAddDisposition	= CERT_STORE_ADD_REPLACE_EXISTING;
	DWORD				dwFindFlags			= 0;
# define				OID_KCA_AUTHREALM	"1.3.6.1.4.1.250.42.1"
	DWORD				dwFindType			= CERT_FIND_ANY;
	CERT_INFO			*pCertInfo			= NULL;
	PCERT_EXTENSION		pCertExt			= NULL;
	CRYPT_OBJID_BLOB	*p					= NULL;
	int					i					= 0;
	char				tmpRealm[250]		= { 0 };
	CTime				startTime			= 0;
	CTime				endTime				= 0;



	memset(ptimeLeft, 0, sizeof(*ptimeLeft));

	if (!realm || !strlen(realm))
		return;

	//--------------------------------------------------------------------
	// Open a store as the source of the certificates to be deleted and added

	if(!(hStoreHandle = CertOpenSystemStore(
			0,
			MY_STORE)))
	{
		HandleError("get_cert_time_left: Strange.  Unable to access your place in the Registry for certificates");
		goto EXIT_RTN;
	}


	// Find first MY store cert issued by our Certificate Authority

	while ((pCertContext = CertFindCertificateInStore(
						hStoreHandle,					// in
						dwCertEncodingType,				// in
						dwFindFlags,					// in
						dwFindType,						// in
						NULL,							// in
						prev_pCertContext				// in
						)))
	{
		if (pCertInfo = pCertContext->pCertInfo)
			for (i = pCertInfo->cExtension; i; i--)
			{
				pCertExt = &pCertInfo->rgExtension[i-1];
				if (!strcmp(pCertExt->pszObjId, OID_KCA_AUTHREALM))
				{
					log_printf("get_cert_time_left: Found KCA_AUTHREALM Extension\n");

					p = &pCertExt->Value;
					memcpy(tmpRealm, &p->pbData[2], p->cbData-2);
					tmpRealm[p->cbData-2] ='\0';
					log_printf("get_cert_time_left:    value is: '%s'\n", tmpRealm);

					/* only match if realm of current TGT matches AuthRealm of this cert */
					if (realm && !strcmp(realm, tmpRealm))
					{
						// It matches, determine remaining certificate's remaining minutes
						startTime	= CTime::GetCurrentTime();
						endTime		= pCertContext->pCertInfo->NotAfter;
						*ptimeLeft	= endTime - startTime;

						goto EXIT_RTN;
					}
				}
			}

		prev_pCertContext = pCertContext;
	}

EXIT_RTN:
	if ((prev_pCertContext != pCertContext) && pCertContext)
	{
		CertFreeCertificateContext(pCertContext);
		pCertContext = NULL;
	}

	if (pCertContext)
		CertFreeCertificateContext(pCertContext);

	if(hStoreHandle &&!CertCloseStore(
							hStoreHandle,
#ifdef DEBUG
							CERT_CLOSE_STORE_CHECK_FLAG
#else // !DEBUG
							CERT_CLOSE_STORE_FORCE_FLAG
#endif // ! DEBUG
			))
	{
		log_printf("get_cert_time_left: The store was closed, but certificates still in use.\n");
	}
} // get_cert_time_left
static PCCERT_CONTEXT
xmlSecMSCryptoKeysStoreFindCert(xmlSecKeyStorePtr store, const xmlChar* name,
                                xmlSecKeyInfoCtxPtr keyInfoCtx) {
    LPCTSTR storeName;
    HCERTSTORE hStoreHandle = NULL;
    PCCERT_CONTEXT pCertContext = NULL;
    LPTSTR wcName = 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) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "CertOpenSystemStore",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    "storeName=%s",
                    xmlSecErrorsSafeString(storeName));
        return(NULL);
    }

    /* convert name to unicode */
    wcName = xmlSecMSCryptoConvertUtf8ToTstr(name);
    if(wcName == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                        xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)),
                        "xmlSecMSCryptoConvertUtf8ToUnicode",
                        XMLSEC_ERRORS_R_XMLSEC_FAILED,
                        "wcName");
        CertCloseStore(hStoreHandle, 0);
        return(NULL);
    }

    /* first attempt: try to find the cert with a full blown subject dn */
    if(NULL == pCertContext) {
        pCertContext = xmlSecMSCryptoX509FindCertBySubject(
            hStoreHandle,
            wcName,
            X509_ASN_ENCODING | PKCS_7_ASN_ENCODING);
    }

    /*
     * Try ro find certificate with name="Friendly Name"
     */
    if (NULL == pCertContext) {
        DWORD dwPropSize;
        PBYTE pbFriendlyName;
        PCCERT_CONTEXT pCertCtxIter = NULL;


        while (pCertCtxIter = CertEnumCertificatesInStore(hStoreHandle, pCertCtxIter)) {
            if (TRUE != CertGetCertificateContextProperty(pCertCtxIter,
                                                      CERT_FRIENDLY_NAME_PROP_ID,
                                                      NULL,
                                                      &dwPropSize)) {
                continue;
            }

            pbFriendlyName = xmlMalloc(dwPropSize);
            if(pbFriendlyName == NULL) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            xmlSecErrorsSafeString(xmlSecKeyStoreGetName(store)),
                            NULL,
                            XMLSEC_ERRORS_R_MALLOC_FAILED,
                            XMLSEC_ERRORS_NO_MESSAGE);
                xmlFree(wcName);
                CertCloseStore(hStoreHandle, 0);
                return(NULL);
            }

            if (TRUE != CertGetCertificateContextProperty(pCertCtxIter,
                                                      CERT_FRIENDLY_NAME_PROP_ID,
                                                      pbFriendlyName,
                                                      &dwPropSize)) {
                xmlFree(pbFriendlyName);
                continue;
            }

            /* Compare FriendlyName to name */
            if (!lstrcmp(wcName, (LPCTSTR)pbFriendlyName)) {
              pCertContext = pCertCtxIter;
              xmlFree(pbFriendlyName);
              break;
            }
            xmlFree(pbFriendlyName);
        }
    }

    /* We don't give up easily, now try to find cert with part of the name
     */
    if (NULL == pCertContext) {
        pCertContext = CertFindCertificateInStore(
            hStoreHandle,
            X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
            0,
            CERT_FIND_SUBJECT_STR,
            wcName,
            NULL);
    }


    /* 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? */
    xmlFree(wcName);
    CertCloseStore(hStoreHandle, 0);
    return(pCertContext);
}