Beispiel #1
0
/***********************************************************************
 *		CertViewPropertiesW (CRYPTDLG.@)
 */
BOOL WINAPI CertViewPropertiesW(CERT_VIEWPROPERTIES_STRUCT_W *info)
{
    static GUID cert_action_verify = CERT_CERTIFICATE_ACTION_VERIFY;
    CERT_VERIFY_CERTIFICATE_TRUST trust;
    WINTRUST_BLOB_INFO blob;
    WINTRUST_DATA wtd;
    LONG err;
    BOOL ret;

    TRACE("(%p)\n", info);

    memset(&trust, 0, sizeof(trust));
    trust.cbSize = sizeof(trust);
    trust.pccert = info->pCertContext;
    trust.cRootStores = info->cRootStores;
    trust.rghstoreRoots = info->rghstoreRoots;
    trust.cStores = info->cStores;
    trust.rghstoreCAs = info->rghstoreCAs;
    trust.cTrustStores = info->cTrustStores;
    trust.rghstoreTrust = info->rghstoreTrust;
    memset(&blob, 0, sizeof(blob));
    blob.cbStruct = sizeof(blob);
    blob.cbMemObject = sizeof(trust);
    blob.pbMemObject = (BYTE *)&trust;
    memset(&wtd, 0, sizeof(wtd));
    wtd.cbStruct = sizeof(wtd);
    wtd.dwUIChoice = WTD_UI_NONE;
    wtd.dwUnionChoice = WTD_CHOICE_BLOB;
    wtd.u.pBlob = &blob;
    wtd.dwStateAction = WTD_STATEACTION_VERIFY;
    err = WinVerifyTrust(NULL, &cert_action_verify, &wtd);
    if (err == ERROR_SUCCESS)
    {
        CRYPTUI_VIEWCERTIFICATE_STRUCTW uiInfo;
        BOOL propsChanged = FALSE;

        memset(&uiInfo, 0, sizeof(uiInfo));
        uiInfo.dwSize = sizeof(uiInfo);
        uiInfo.hwndParent = info->hwndParent;
        uiInfo.dwFlags =
         CRYPTUI_DISABLE_ADDTOSTORE | CRYPTUI_ENABLE_EDITPROPERTIES;
        uiInfo.szTitle = info->szTitle;
        uiInfo.pCertContext = info->pCertContext;
        uiInfo.cPurposes = info->cArrayPurposes;
        uiInfo.rgszPurposes = (LPCSTR *)info->arrayPurposes;
        uiInfo.u.hWVTStateData = wtd.hWVTStateData;
        uiInfo.fpCryptProviderDataTrustedUsage = TRUE;
        uiInfo.cPropSheetPages = info->cArrayPropSheetPages;
        uiInfo.rgPropSheetPages = info->arrayPropSheetPages;
        uiInfo.nStartPage = info->nStartPage;
        ret = CryptUIDlgViewCertificateW(&uiInfo, &propsChanged);
        wtd.dwStateAction = WTD_STATEACTION_CLOSE;
        WinVerifyTrust(NULL, &cert_action_verify, &wtd);
    }
    else
        ret = FALSE;
    return ret;
}
Beispiel #2
0
bool InstallChecker::verifyPackage(std::wstring filePath,bool withUI) {
    WINTRUST_FILE_INFO FileData;
    memset(&FileData, 0, sizeof(FileData));
    FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
    FileData.pcwszFilePath = filePath.c_str();
	GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

	WINTRUST_DATA WinTrustData;
	memset(&WinTrustData, 0, sizeof(WinTrustData));
	WinTrustData.cbStruct = sizeof(WinTrustData);
	WinTrustData.dwUIChoice = withUI ? WTD_UI_ALL : WTD_UI_NONE;
    WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; 

    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
    WinTrustData.dwProvFlags = WTD_SAFER_FLAG;
    WinTrustData.pFile = &FileData;

	DWORD dwLastError;
	LONG lStatus = WinVerifyTrust(0,&WVTPolicyGUID,&WinTrustData);
	switch (lStatus) {
        case ERROR_SUCCESS: return true;
        case TRUST_E_NOSIGNATURE:
            dwLastError = GetLastError();
            if (TRUST_E_NOSIGNATURE == dwLastError ||
                    TRUST_E_SUBJECT_FORM_UNKNOWN == dwLastError ||
                    TRUST_E_PROVIDER_UNKNOWN == dwLastError) 
					return true;
		}
	return false;
	}
bool InstallChecker::verifyPackage( const QString &filePath, bool withUI )
{
    std::wstring path = QDir::toNativeSeparators( filePath ).toStdWString();

    BinaryCertificate c( path );
    if( c.subjectName() != "Estonian Informatics Centre" )
        return false;

    WINTRUST_FILE_INFO FileData;
    memset(&FileData, 0, sizeof(FileData));
    FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
    FileData.pcwszFilePath = path.c_str();
    GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    WINTRUST_DATA WinTrustData;
    memset(&WinTrustData, 0, sizeof(WinTrustData));
    WinTrustData.cbStruct = sizeof(WinTrustData);
    WinTrustData.dwUIChoice = withUI ? WTD_UI_ALL : WTD_UI_NONE;
    WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;

    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
    WinTrustData.dwProvFlags = WTD_SAFER_FLAG;
    WinTrustData.pFile = &FileData;

    switch( WinVerifyTrust( 0, &WVTPolicyGUID, &WinTrustData ) )
    {
    case ERROR_SUCCESS:
        return true;
    default:
        return false;
    }
}
Beispiel #4
0
/**
 * Verifies the trust of a signed file's certificate.
 *
 * @param  filePath  The file path to check.
 * @return ERROR_SUCCESS if successful, or the last error code otherwise.
 */
DWORD
VerifyCertificateTrustForFile(LPCWSTR filePath)
{
  // Setup the file to check.
  WINTRUST_FILE_INFO fileToCheck;
  ZeroMemory(&fileToCheck, sizeof(fileToCheck));
  fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
  fileToCheck.pcwszFilePath = filePath;

  // Setup what to check, we want to check it is signed and trusted.
  WINTRUST_DATA trustData;
  ZeroMemory(&trustData, sizeof(trustData));
  trustData.cbStruct = sizeof(trustData);
  trustData.pPolicyCallbackData = NULL;
  trustData.pSIPClientData = NULL;
  trustData.dwUIChoice = WTD_UI_NONE;
  trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
  trustData.dwUnionChoice = WTD_CHOICE_FILE;
  trustData.dwStateAction = 0;
  trustData.hWVTStateData = NULL;
  trustData.pwszURLReference = NULL;
  // no UI
  trustData.dwUIContext = 0;
  trustData.pFile = &fileToCheck;

  GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
  // Check if the file is signed by something that is trusted.
  LONG ret = WinVerifyTrust(NULL, &policyGUID, &trustData);
  return ret;
}
Beispiel #5
0
static void test_wintrust(void)
{
    static GUID generic_action_v2 = WINTRUST_ACTION_GENERIC_VERIFY_V2;
    WINTRUST_DATA wtd;
    WINTRUST_FILE_INFO file;
    LONG r;
    HRESULT hr;
    WCHAR notepadPathW[MAX_PATH];

    memset(&wtd, 0, sizeof(wtd));
    wtd.cbStruct = sizeof(wtd);
    wtd.dwUIChoice = WTD_UI_NONE;
    wtd.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
    wtd.dwUnionChoice = WTD_CHOICE_FILE;
    U(wtd).pFile = &file;
    wtd.dwStateAction = WTD_STATEACTION_VERIFY;
    memset(&file, 0, sizeof(file));
    file.cbStruct = sizeof(file);
    getNotepadPath(notepadPathW, MAX_PATH);
    file.pcwszFilePath = notepadPathW;
    r = WinVerifyTrust(INVALID_HANDLE_VALUE, &generic_action_v2, &wtd);
    ok(r == TRUST_E_NOSIGNATURE, "expected TRUST_E_NOSIGNATURE, got %08x\n", r);
    hr = WinVerifyTrustEx(INVALID_HANDLE_VALUE, &generic_action_v2, &wtd);
    ok(hr == TRUST_E_NOSIGNATURE, "expected TRUST_E_NOSIGNATURE, got %08x\n",
     hr);
}
Beispiel #6
0
void simVerifyTrust(const TCHAR *module, bool must_exist)
{
	TCHAR szModule[MAX_PATH];
	// For some reason VS2005 compiles this wrong, so you get a call to cvs::wide(NULL)
	// HMODULE hModule = GetModuleHandle(module?cvs::wide(module):NULL);
	HMODULE hModule;
	if(module)
		hModule = GetModuleHandle(module);
	else
		hModule = GetModuleHandle(NULL);

	if(!hModule && module)
	{
		if(!SearchPath(NULL,module,_T(".dll"),sizeof(szModule)/sizeof(szModule[0]),szModule,NULL))
		{
			if(must_exist)
			{
				printf("Unable to find %S  - aborting\n",module);
				exit(-1);
				abort();
			}
			return;
		}
	}
	else
		GetModuleFileName(hModule,szModule,sizeof(szModule));

	WINTRUST_FILE_INFO FileData = {sizeof(WINTRUST_FILE_INFO)};
	WINTRUST_DATA WinTrustData = {sizeof(WINTRUST_DATA)};
    FileData.pcwszFilePath = szModule;

    GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    WinTrustData.dwUIChoice = WTD_UI_NONE;
    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
    WinTrustData.dwProvFlags = WTD_SAFER_FLAG | WTD_REVOCATION_CHECK_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL;
    WinTrustData.pFile = &FileData;
	WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;

    DWORD dwTrustErr = WinVerifyTrust(NULL, &WVTPolicyGUID, &WinTrustData);
	if(dwTrustErr)
	{
		if(dwTrustErr==TRUST_E_NOSIGNATURE)
		{
#ifdef COMMERCIAL_RELEASE
			printf("Trust verification failed for '%S' - image not signed\n",szModule);
#else
			printf("Trust verification failed for '%S' - community image file image not signed\n",szModule);
			return;
#endif
		}
		else if(dwTrustErr==TRUST_E_SUBJECT_NOT_TRUSTED)
			printf("Trust verification failed for '%S' - invalid signature\n",szModule);
		else
			printf("Trust verification failed for '%S' - error %08x\n",szModule,GetLastError());
		exit(-1);
		abort();
	}
}
void CLibraryAccess::VerifyTrust(const char *module, bool must_exist)
{
	TCHAR szModule[MAX_PATH];
	// For some reason VS2005 compiles this wrong, so you get a call to cvs::wide(NULL)
	// HMODULE hModule = GetModuleHandle(module?cvs::wide(module):NULL);
	HMODULE hModule;
	if(module)
		hModule = GetModuleHandle(cvs::wide(module));
	else
		hModule = GetModuleHandle(NULL);

	if(!hModule && module)
	{
		if(!SearchPath(NULL,cvs::wide(module),_T(".dll"),sizeof(szModule)/sizeof(szModule[0]),szModule,NULL))
		{
			if(must_exist)
			{
				CServerIo::error("Unable to find %s - aborting",module);
				exit(-1);
				abort();
			}
			return;
		}
	}
	else
		GetModuleFileName(hModule,szModule,sizeof(szModule));

	WINTRUST_FILE_INFO FileData = {sizeof(WINTRUST_FILE_INFO)};
	WINTRUST_DATA WinTrustData = {sizeof(WINTRUST_DATA)};
    FileData.pcwszFilePath = szModule;

    GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    WinTrustData.dwUIChoice = WTD_UI_NONE;
    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
    WinTrustData.dwProvFlags = WTD_SAFER_FLAG;
    WinTrustData.pFile = &FileData;

    DWORD dwTrustErr = WinVerifyTrust(NULL, &WVTPolicyGUID, &WinTrustData);
	if(dwTrustErr)
	{
		if(dwTrustErr==TRUST_E_NOSIGNATURE)
		{
#ifdef COMMERCIAL_RELEASE
			CServerIo::error("Executable file '%s' trust verification failed - executable image not signed\n",(const char *)cvs::narrow(szModule));
#else
			CServerIo::trace(1,"Executable file '%s' trust verification failed - executable image not signed\n",(const char *)cvs::narrow(szModule));
			return;
#endif
		}
		else if(dwTrustErr==TRUST_E_SUBJECT_NOT_TRUSTED)
			CServerIo::error("Executable file '%s' trust verification failed - invalid signature\n",(const char *)cvs::narrow(szModule));
		else
			CServerIo::error("Executable file '%s' trust verification failed - error %08x\n",(const char *)cvs::narrow(szModule),GetLastError());
		exit(-1);
		abort();
	}
}
BOOL CCheckForUpdatesDlg::VerifySignature(CString fileName)
{
	WINTRUST_FILE_INFO fileInfo;
	memset(&fileInfo, 0, sizeof(fileInfo));
	fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
	fileInfo.pcwszFilePath = fileName;

	WINTRUST_DATA data;
	memset(&data, 0, sizeof(data));
	data.cbStruct = sizeof(data);

	data.dwUIChoice = WTD_UI_NONE;
	data.fdwRevocationChecks = WTD_REVOKE_NONE;
	data.dwUnionChoice = WTD_CHOICE_FILE;
	data.pFile = &fileInfo;

	GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

	return (WinVerifyTrust(NULL, &policyGUID, &data) == ERROR_SUCCESS);
}
/**
 * Verifies the trust of the specified file path.
 *
 * @param  filePath  The file path to check.
 * @return ERROR_SUCCESS if successful, or the last error code otherwise.
 */
DWORD
VerifyCertificateTrustForFile(LPCWSTR filePath)
{
  // Setup the file to check.
  WINTRUST_FILE_INFO fileToCheck;
  ZeroMemory(&fileToCheck, sizeof(fileToCheck));
  fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
  fileToCheck.pcwszFilePath = filePath;

  // Setup what to check, we want to check it is signed and trusted.
  WINTRUST_DATA trustData;
  ZeroMemory(&trustData, sizeof(trustData));
  trustData.cbStruct = sizeof(trustData);
  trustData.pPolicyCallbackData = NULL;
  trustData.pSIPClientData = NULL;
  trustData.dwUIChoice = WTD_UI_NONE;
  trustData.fdwRevocationChecks = WTD_REVOKE_NONE; 
  trustData.dwUnionChoice = WTD_CHOICE_FILE;
  trustData.dwStateAction = 0;
  trustData.hWVTStateData = NULL;
  trustData.pwszURLReference = NULL;
  // no UI
  trustData.dwUIContext = 0;
  trustData.pFile = &fileToCheck;

  GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
  // Check if the file is signed by something that is trusted.
  LONG ret = WinVerifyTrust(NULL, &policyGUID, &trustData);
  if (ERROR_SUCCESS == ret) {
    // The hash that represents the subject is trusted and there were no
    // verification errors.  No publisher nor time stamp chain errors.
    LOG(("The file \"%ls\" is signed and the signature was verified.\n",
        filePath));
      return ERROR_SUCCESS;
  }

  DWORD lastError = GetLastError();
  LOG(("There was an error validating trust of the certificate for file"
       " \"%ls\". Returned: %d, Last error: %d\n", filePath, ret, lastError));
  return ret;
}
/* This function takes a full path and returns FALSE if the file is correctly signed (digital certificate) */
long is_signed(LPCWSTR wPath) {

	/* Building various data structures used as part of the query */
	LONG lStatus;
	WINTRUST_FILE_INFO FileData;
	memset(&FileData, 0, sizeof(FileData));
	FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
	FileData.pcwszFilePath = wPath;
	FileData.hFile = NULL;
	FileData.pgKnownSubject = NULL;


	GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
	WINTRUST_DATA WinTrustData;

	memset(&WinTrustData, 0, sizeof(WinTrustData));

	WinTrustData.cbStruct = sizeof(WinTrustData);
	WinTrustData.pPolicyCallbackData = NULL;
	WinTrustData.pSIPClientData = NULL;
	WinTrustData.dwUIChoice = WTD_UI_NONE;
	WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
	WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
	WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
	WinTrustData.hWVTStateData = NULL;
	WinTrustData.pwszURLReference = NULL;
	WinTrustData.dwUIContext = 0;

	WinTrustData.pFile = &FileData;

	/* API call which identifies whether a file has been correctly signed */
	lStatus = WinVerifyTrust(NULL, &WVTPolicyGUID, &WinTrustData);

	/* This function returns 0 if the file is correctly signed */
	return lStatus;
}
Beispiel #11
0
uint32 ValidateCert(const wchar_t* pwszSourceFile, char* message, size_t size)
{
	LONG lStatus;
	DWORD dwLastError;

	// Initialize the WINTRUST_FILE_INFO structurer
	WINTRUST_FILE_INFO FileData;
	memset(&FileData, 0, sizeof(FileData));
	FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
	FileData.pcwszFilePath = pwszSourceFile;
	FileData.hFile = nullptr;
	FileData.pgKnownSubject = nullptr;

	/*
	WVTPolicyGUID specifies the policy to apply on the file
	WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks:

	1) The certificate used to sign the file chains up to a root
	certificate located in the trusted root certificate store. This
	implies that the identity of the publisher has been verified by
	a certification authority.

	2) In cases where user interface is displayed (which this example
	does not do), WinVerifyTrust will check for whether the
	end entity certificate is stored in the trusted publisher store,
	implying that the user trusts content from this publisher.

	3) The end entity certificate has sufficient permission to sign
	code, as indicated by the presence of a code signing EKU or no
	EKU.
	*/

	GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
	WINTRUST_DATA WinTrustData;

	// Initialize the WinVerifyTrust input data structure.

	// Default all fields to 0.
	memset(&WinTrustData, 0, sizeof(WinTrustData));

	WinTrustData.cbStruct = sizeof(WinTrustData);

	// Use default code signing EKU.
	WinTrustData.pPolicyCallbackData = nullptr;

	// No data to pass to SIP.
	WinTrustData.pSIPClientData = nullptr;

	// Disable WVT UI.
	WinTrustData.dwUIChoice = WTD_UI_NONE;

	// No revocation checking.
	WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;

	// Verify an embedded signature on a file.
	WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;

	// Default verification.
	WinTrustData.dwStateAction = 0;

	// Not applicable for default verification of embedded signature.
	WinTrustData.hWVTStateData = nullptr;

	// Not used.
	WinTrustData.pwszURLReference = nullptr;

	// Default.
	WinTrustData.dwProvFlags = WTD_SAFER_FLAG;

	// This is not applicable if there is no UI because it changes
	// the UI to accommodate running applications instead of
	// installing applications.
	WinTrustData.dwUIContext = 0;

	// Set pFile.
	WinTrustData.pFile = &FileData;

	// WinVerifyTrust verifies signatures as specified by the GUID
	// and Wintrust_Data.
	lStatus = WinVerifyTrust(nullptr, &WVTPolicyGUID, &WinTrustData);

	if (!message)
		return lStatus;

	switch (lStatus)
	{
		case ERROR_SUCCESS:
			Safe::snprintf(message, size, "The file is signed and the signature was verified.");
			break;

		case TRUST_E_NOSIGNATURE:
			// The file was not signed or had a signature
			// that was not valid.

			// Get the reason for no signature.
			dwLastError = GetLastError();
			if (TRUST_E_NOSIGNATURE == dwLastError ||TRUST_E_SUBJECT_FORM_UNKNOWN == dwLastError || TRUST_E_PROVIDER_UNKNOWN == dwLastError)
			{
				Safe::snprintf(message, size, "The file is not signed.");
			}
			else
			{
				Safe::snprintf(message, size, "An unknown error occurred trying to verify the signature [%d].", dwLastError);
			}
			break;

		case TRUST_E_EXPLICIT_DISTRUST:
			Safe::snprintf(message, size, "The signature is present, but specifically disallowed.");
			break;

		case TRUST_E_SUBJECT_NOT_TRUSTED:
			Safe::snprintf(message, size, "The signature is present, but not trusted.");
			break;

		case CRYPT_E_SECURITY_SETTINGS:
			 Safe::snprintf(message, size, "CRYPT_E_SECURITY_SETTINGS - The hash "
				"representing the subject or the publisher wasn't "
				"explicitly trusted by the admin and admin policy "
				"has disabled user trust. No signature, publisher "
				"or timestamp errors.");
			break;

		default:
			Safe::snprintf(message, size, "Error is: 0x%x.\n", lStatus);
			break;
	}

	return lStatus;
}
nsresult
BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath)
{
  MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread");

  nsNSSShutDownPreventionLock nssLock;
  if (isAlreadyShutDown()) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  {
    MutexAutoLock lock(mLock);
    if (!mSignatureInfoEnabled) {
      return NS_OK;
    }
  }
  nsresult rv;
  nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
#ifdef XP_WIN
  // Setup the file to check.
  WINTRUST_FILE_INFO fileToCheck = {0};
  fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
  fileToCheck.pcwszFilePath = filePath.Data();
  fileToCheck.hFile = nullptr;
  fileToCheck.pgKnownSubject = nullptr;

  // We want to check it is signed and trusted.
  WINTRUST_DATA trustData = {0};
  trustData.cbStruct = sizeof(trustData);
  trustData.pPolicyCallbackData = nullptr;
  trustData.pSIPClientData = nullptr;
  trustData.dwUIChoice = WTD_UI_NONE;
  trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
  trustData.dwUnionChoice = WTD_CHOICE_FILE;
  trustData.dwStateAction = WTD_STATEACTION_VERIFY;
  trustData.hWVTStateData = nullptr;
  trustData.pwszURLReference = nullptr;
  // Disallow revocation checks over the network
  trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
  // no UI
  trustData.dwUIContext = 0;
  trustData.pFile = &fileToCheck;

  // The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate
  // chains up to a trusted root CA and has appropriate permissions to sign
  // code.
  GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
  // Check if the file is signed by something that is trusted. If the file is
  // not signed, this is a no-op.
  LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData);
  CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr;
  // According to the Windows documentation, we should check against 0 instead
  // of ERROR_SUCCESS, which is an HRESULT.
  if (ret == 0) {
    cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData);
  }
  if (cryptoProviderData) {
    // Lock because signature information is read on the main thread.
    MutexAutoLock lock(mLock);
    LOG(("Downloaded trusted and signed file [this = %p].", this));
    // A binary may have multiple signers. Each signer may have multiple certs
    // in the chain.
    for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) {
      const CERT_CHAIN_CONTEXT* certChainContext =
        cryptoProviderData->pasSigners[i].pChainContext;
      if (!certChainContext) {
        break;
      }
      for (DWORD j = 0; j < certChainContext->cChain; ++j) {
        const CERT_SIMPLE_CHAIN* certSimpleChain =
          certChainContext->rgpChain[j];
        if (!certSimpleChain) {
          break;
        }
        nsCOMPtr<nsIX509CertList> nssCertList =
          do_CreateInstance(NS_X509CERTLIST_CONTRACTID);
        if (!nssCertList) {
          break;
        }
        bool extractionSuccess = true;
        for (DWORD k = 0; k < certSimpleChain->cElement; ++k) {
          CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k];
          if (certChainElement->pCertContext->dwCertEncodingType !=
            X509_ASN_ENCODING) {
              continue;
          }
          nsCOMPtr<nsIX509Cert> nssCert = nullptr;
          rv = certDB->ConstructX509(
            reinterpret_cast<char *>(
              certChainElement->pCertContext->pbCertEncoded),
            certChainElement->pCertContext->cbCertEncoded,
            getter_AddRefs(nssCert));
          if (!nssCert) {
            extractionSuccess = false;
            LOG(("Couldn't create NSS cert [this = %p]", this));
            break;
          }
          nssCertList->AddCert(nssCert);
          nsString subjectName;
          nssCert->GetSubjectName(subjectName);
          LOG(("Adding cert %s [this = %p]",
               NS_ConvertUTF16toUTF8(subjectName).get(), this));
        }
        if (extractionSuccess) {
          mSignatureInfo.AppendObject(nssCertList);
        }
      }
    }
    // Free the provider data if cryptoProviderData is not null.
    trustData.dwStateAction = WTD_STATEACTION_CLOSE;
    WinVerifyTrust(nullptr, &policyGUID, &trustData);
  } else {
    LOG(("Downloaded unsigned or untrusted file [this = %p].", this));
  }
#endif
  return NS_OK;
}
BOOL
IsFilePublisherTrusted(
    LPCWSTR pwszFileName
)
{
    BOOL trusted = FALSE;
    DWORD lastError;
    GUID wvtProvGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    //
    // Initialize structure for WinVerifyTrust call
    //

    WINTRUST_DATA wtd = { 0 };
    WINTRUST_FILE_INFO wtfi = { 0 };

    wtd.cbStruct = sizeof(WINTRUST_DATA);
    wtd.pPolicyCallbackData = NULL;
    wtd.pSIPClientData = NULL;
    wtd.dwUIChoice = WTD_UI_NONE;
    wtd.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
    wtd.dwUnionChoice = WTD_CHOICE_FILE;
    wtd.pFile = &wtfi;
    wtd.dwStateAction = WTD_STATEACTION_VERIFY;
    wtd.hWVTStateData = NULL;
    wtd.pwszURLReference = NULL;
    wtd.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;

    wtfi.cbStruct = sizeof(WINTRUST_FILE_INFO);
    wtfi.pcwszFilePath = pwszFileName;
    wtfi.hFile = NULL;
    wtfi.pgKnownSubject = NULL;

    //
    // Check the file's Authenticode signature
    //

    if (S_OK != WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &wvtProvGuid, &wtd))
    {
        lastError = GetLastError();
        goto Cleanup;
    }

    //
    // Get provider data
    //

    CRYPT_PROVIDER_DATA* pProvData = WTHelperProvDataFromStateData(wtd.hWVTStateData);
    if (NULL == pProvData)
    {
        lastError = GetLastError();
        goto Cleanup;
    }

    //
    // Get the signer
    //

    CRYPT_PROVIDER_SGNR* pProvSigner = WTHelperGetProvSignerFromChain(pProvData, 0, FALSE, 0);
    if (NULL == pProvSigner)
    {
        lastError = GetLastError();
        goto Cleanup;
    }

    if (!IsTrustedRootKey(pProvSigner->pChainContext))
    {
        goto Cleanup;
    }

    if (!IsTrustedPublisherName(pProvSigner->pChainContext))
    {
        goto Cleanup;
    }

    //
    // If we made it this far, we can trust the file
    //

    trusted = TRUE;

Cleanup:
    //
    // Close the previously-opened state data handle
    //

    wtd.dwStateAction = WTD_STATEACTION_CLOSE;
    WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &wvtProvGuid, &wtd);

    return trusted;
}
Beispiel #14
0
bool Bootstrap_UpdateEXE(int exeSize)
{
	const char* fn = _tempnam(NULL, "cup");
	CL_QueueDownload(va(CONTENT_URL "/%s/bootstrap/CitizenFX.exe.xz", GetUpdateChannel()), fn, exeSize, true);

	UI_DoCreation();

	if (!DL_RunLoop())
	{
		UI_DoDestruction();
		return false;
	}

	UI_DoDestruction();

	// verify the signature on the EXE
	wchar_t wfn[512];
	MultiByteToWideChar(CP_ACP, 0, fn, -1, wfn, 512);

	WINTRUST_FILE_INFO info;
	memset(&info, 0, sizeof(info));

	info.cbStruct = sizeof(info);
	info.pcwszFilePath = wfn;
	info.hFile = NULL;
	info.pgKnownSubject = NULL;

	GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

	WINTRUST_DATA data;
	memset(&data, 0, sizeof(data));

	data.cbStruct = sizeof(data);
	data.pPolicyCallbackData = NULL;
	data.pSIPClientData = NULL;
	data.dwUIChoice = WTD_UI_NONE;
	data.fdwRevocationChecks = WTD_REVOKE_NONE;
	data.dwUnionChoice = WTD_CHOICE_FILE;
	data.dwStateAction = 0;
	data.hWVTStateData = NULL;
	data.pwszURLReference = NULL;
	data.dwUIContext = 0;
	data.pFile = &info;

	LONG status = WinVerifyTrust(NULL, &WVTPolicyGUID, &data);

	if (status != ERROR_SUCCESS)
	{
		//MessageBox(NULL, va(L"A trust chain error occurred in the downloaded rtcg.exe. The specific error code is 0x%08x.", status), L"O\x448\x438\x431\x43A\x430", MB_OK | MB_ICONSTOP);
		//return false;
	}

	wchar_t exePath[512];
	GetModuleFileName(GetModuleHandle(NULL), exePath, sizeof(exePath) / 2);

	STARTUPINFO startupInfo;
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	startupInfo.wShowWindow = SW_HIDE;
	startupInfo.dwFlags |= STARTF_USESHOWWINDOW;

	PROCESS_INFORMATION processInfo;

	CreateProcess(wfn, (LPWSTR)va(L"%s -bootstrap \"%s\"", wfn, exePath), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);

	return false;
}
Beispiel #15
0
/***********************************************************************
 *		WinVerifyTrustEx (WINTRUST.@)
 */
HRESULT WINAPI WinVerifyTrustEx( HWND hwnd, GUID *ActionID,
 WINTRUST_DATA* ActionData )
{
    return WinVerifyTrust(hwnd, ActionID, ActionData);
}
bool ExtDLL_CheckSafety()
{
	// check #1: NP validity
	NPAsync<NPGetPublisherFileResult>* async = NP_GetPublisherFile("hello_world.txt", (uint8_t*)helloWorld, sizeof(helloWorld));
	NPGetPublisherFileResult* result = async->Wait();

	if (result->result != GetFileResultOK)
	{
		MessageBoxA(NULL, "The IW4M extension DLL failed to load due to the master server lacking support for the functionality provided by this DLL.", "IW4M", MB_OK);
		return false;
	}

	// check #2: DLL signature
	if (!GAME_FLAG(GAME_FLAG_DEDICATED))
	{
		HMODULE iw4m = GetModuleHandleA("iw4m.dll");

		if (!iw4m)
		{
			return false;
		}

		wchar_t filename[MAX_PATH];
		GetModuleFileNameW(iw4m, filename, sizeof(filename) / 2);

		WINTRUST_FILE_INFO info;
		memset(&info, 0, sizeof(info));

		info.cbStruct = sizeof(info);
		info.pcwszFilePath = filename;
		info.hFile = NULL;
		info.pgKnownSubject = NULL;

		GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

		WINTRUST_DATA data;
		memset(&data, 0, sizeof(data));

		data.cbStruct = sizeof(data);
		data.pPolicyCallbackData = NULL;
		data.pSIPClientData = NULL;
		data.dwUIChoice = WTD_UI_NONE;
		data.fdwRevocationChecks = WTD_REVOKE_NONE;
		data.dwUnionChoice = WTD_CHOICE_FILE;
		data.dwStateAction = 0;
		data.hWVTStateData = NULL;
		data.pwszURLReference = NULL;
		data.dwUIContext = 0;
		data.pFile = &info;

		LONG status = WinVerifyTrust(NULL, &WVTPolicyGUID, &data);

		if (status != ERROR_SUCCESS)
		{
			MessageBoxA(NULL, va("The IW4M extension DLL failed to load due to a trust chain error. The specific error was 0x%x.", status), "IW4M", MB_OK);
			return false;
		}
	}

	return true;
}
Beispiel #17
0
BOOL VerifyEmbeddedSignature( LPCWSTR lpFileName )
{
	BOOL bRet = FALSE;
	WINTRUST_DATA wd = { 0 };
	WINTRUST_FILE_INFO wfi = { 0 };
	WINTRUST_CATALOG_INFO wci = { 0 };
	CATALOG_INFO ci = { 0 };

	HCATADMIN hCatAdmin = NULL;
	if ( !CryptCATAdminAcquireContext( &hCatAdmin, NULL, 0 ) )
	{
		return FALSE;
	}

	HANDLE hFile = CreateFileW( lpFileName, GENERIC_READ, FILE_SHARE_READ,
		NULL, OPEN_EXISTING, 0, NULL );
	if ( INVALID_HANDLE_VALUE == hFile )
	{
		CryptCATAdminReleaseContext( hCatAdmin, 0 );
		return FALSE;
	}

	DWORD dwCnt = 100;
	BYTE byHash[100];
	CryptCATAdminCalcHashFromFileHandle( hFile, &dwCnt, byHash, 0 );
	CloseHandle( hFile );

	//LPWSTR pszMemberTag = new WCHAR[dwCnt * 2 + 1];
	//LPWSTR pszMemberTag = (WCHAR *)VirtualAlloc(0, dwCnt * 2 + 1,MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

	//用静态内存~!
	WCHAR pszMemberTag[260] = {0};
	for ( DWORD dw = 0; dw < dwCnt; ++dw )
	{
		wsprintfW( &pszMemberTag[dw * 2], L"%02X", byHash[dw] );
	}

	HCATINFO hCatInfo = CryptCATAdminEnumCatalogFromHash( hCatAdmin,
		byHash, dwCnt, 0, NULL );
	if ( NULL == hCatInfo )
	{
		wfi.cbStruct       = sizeof( WINTRUST_FILE_INFO );
		wfi.pcwszFilePath  = lpFileName;
		wfi.hFile          = NULL;
		wfi.pgKnownSubject = NULL;

		wd.cbStruct            = sizeof( WINTRUST_DATA );
		wd.dwUnionChoice       = WTD_CHOICE_FILE;
		wd.pFile               = &wfi;
		wd.dwUIChoice          = WTD_UI_NONE;
		wd.fdwRevocationChecks = WTD_REVOKE_NONE;
		wd.dwStateAction       = WTD_STATEACTION_IGNORE;
		wd.dwProvFlags         = WTD_SAFER_FLAG;
		wd.hWVTStateData       = NULL;
		wd.pwszURLReference    = NULL;
	}
	else
	{
		CryptCATCatalogInfoFromContext( hCatInfo, &ci, 0 );
		wci.cbStruct             = sizeof( WINTRUST_CATALOG_INFO );
		wci.pcwszCatalogFilePath = ci.wszCatalogFile;
		wci.pcwszMemberFilePath  = lpFileName;
		wci.pcwszMemberTag       = pszMemberTag;

		wd.cbStruct            = sizeof( WINTRUST_DATA );
		wd.dwUnionChoice       = WTD_CHOICE_CATALOG;
		wd.pCatalog            = &wci;
		wd.dwUIChoice          = WTD_UI_NONE;
		wd.fdwRevocationChecks = WTD_STATEACTION_VERIFY;
		wd.dwProvFlags         = 0;
		wd.hWVTStateData       = NULL;
		wd.pwszURLReference    = NULL;
	}
	GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2;
	HRESULT hr  = WinVerifyTrust( NULL, &action, &wd );
	bRet        = SUCCEEDED( hr );

	//记得要释放啊,尼玛的不然内存飚的老高了~!!!!
	if (hCatAdmin && hCatInfo)
		 CryptCATAdminReleaseCatalogContext(hCatAdmin,hCatInfo,0);

	if (hCatAdmin)
		CryptCATAdminReleaseContext( hCatAdmin, 0 );

	//delete[] pszMemberTag;
	//VirtualFree(pszMemberTag,dwCnt * 2 + 1,MEM_RESERVE | MEM_COMMIT);

	return bRet;
}
Beispiel #18
0
int verify_trust(const char source[], int warn_unsigned=0) {

	int nchars = MultiByteToWideChar(CP_ACP, 0, source, -1, NULL, 0);

	wchar_t* wsource = new wchar_t[nchars];
	if (wsource == NULL) {
		fprintf(stderr, "SECURITY FAILURE: out-of-memory allocating wsource\n");
		return -2;
		}

	MultiByteToWideChar(CP_ACP, 0, source, -1, wsource, nchars);

	/* code adapted from 
	 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa382384%28v=vs.85%29.aspx
	 */

    /* Initialize the WINTRUST_FILE_INFO structure. */

    WINTRUST_FILE_INFO FileData;
    memset(&FileData, 0, sizeof(FileData));
    FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
    FileData.pcwszFilePath = wsource;
    FileData.hFile = NULL;
    FileData.pgKnownSubject = NULL;

    GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
    WINTRUST_DATA WinTrustData;

    /* Initialize the WinVerifyTrust input data structure. */

    memset(&WinTrustData, 0, sizeof(WinTrustData));
    WinTrustData.cbStruct = sizeof(WinTrustData);
    WinTrustData.pPolicyCallbackData = NULL;
    WinTrustData.pSIPClientData = NULL;
    WinTrustData.dwUIChoice = WTD_UI_NONE;
    WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; 
    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
    WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
    WinTrustData.hWVTStateData = NULL;
    WinTrustData.pwszURLReference = NULL;
    WinTrustData.dwUIContext = 0;
    WinTrustData.pFile = &FileData;

	int trusted = 0;

    LONG status = WinVerifyTrust( NULL, &WVTPolicyGUID, &WinTrustData);
	DWORD err;

    switch (status) {

        case ERROR_SUCCESS:
			trusted = 1;
            break;
        
        case TRUST_E_NOSIGNATURE:
            /* check the error details */
            err = GetLastError();
            if (TRUST_E_NOSIGNATURE == err ||
				TRUST_E_SUBJECT_FORM_UNKNOWN == err ||
				TRUST_E_PROVIDER_UNKNOWN == err) {
				if (warn_unsigned)
					fprintf(stderr, "SECURITY WARNING: '%s' not signed\n", source);
				trusted = -1;
            	} 
            else{
				/* unknown error verifying signature */
				fprintf(stderr, "SECURITY FAILURE: trying to verify '%s' "
						"status=0x%lx, error=0x$lx\n", source, status, err);
				trusted = -2;
				}
            break;

        case TRUST_E_EXPLICIT_DISTRUST:
        case CRYPT_E_SECURITY_SETTINGS:
			/* subject or publisher was invalidated by machine admin */
			fprintf(stderr, "SECURITY VIOLATION: '%s' is blocked by local policy\n", source);
			trusted = 0;
            break;

        case TRUST_E_SUBJECT_NOT_TRUSTED:
            /* user clicked "No" when asked to install/run. */
			fprintf(stderr, "SECURTIY VIOLATION: '%s' has untrusted signature\n", source);
			trusted = 0;
            break;

		case TRUST_E_BAD_DIGEST:
			/* tampered binary */
			fprintf(stderr, "SECURITY VIOLATION: '%s' tampered binary\n", source);
			break;

        default:
			fprintf(stderr, "SECURITY FAILURE: verifying '%s' status=0x%lx\n", source, status);
            break;
    	}

	/* cleanup */

    WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
    WinVerifyTrust( NULL, &WVTPolicyGUID, &WinTrustData);

	delete [] wsource;

    return trusted;
	}