导航

How to verify a file's signature

Posted on 2013-12-10 23:15  littledot  阅读(623)  评论(0编辑  收藏  举报

http://msdn.microsoft.com/en-us/library/aa382384.aspx

//-------------------------------------------------------------------
// Copyright (C) Microsoft.  All rights reserved.
// Example of verifying the embedded signature of a PE file by using 
// the WinVerifyTrust function.

#define _UNICODE 1
#define UNICODE 1

#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>

// Link with the Wintrust.lib file.
#pragma comment (lib, "wintrust")

BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
    LONG lStatus;
    DWORD dwLastError;

    // Initialize the WINTRUST_FILE_INFO structure.

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

    /*
    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 = NULL;

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

    // 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;

    // Verify action.
    WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;

    // Verification sets this value.
    WinTrustData.hWVTStateData = NULL;

    // Not used.
    WinTrustData.pwszURLReference = NULL;

    // 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(
        NULL,
        &WVTPolicyGUID,
        &WinTrustData);

    switch (lStatus) 
    {
        case ERROR_SUCCESS:
            /*
            Signed file:
                - Hash that represents the subject is trusted.

                - Trusted publisher without any verification errors.

                - UI was disabled in dwUIChoice. No publisher or 
                    time stamp chain errors.

                - UI was enabled in dwUIChoice and the user clicked 
                    "Yes" when asked to install and run the signed 
                    subject.
            */
            wprintf_s(L"The file \"%s\" is signed and the signature "
                L"was verified.\n",
                pwszSourceFile);
            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) 
            {
                // The file was not signed.
                wprintf_s(L"The file \"%s\" is not signed.\n",
                    pwszSourceFile);
            } 
            else 
            {
                // The signature was not valid or there was an error 
                // opening the file.
                wprintf_s(L"An unknown error occurred trying to "
                    L"verify the signature of the \"%s\" file.\n",
                    pwszSourceFile);
            }

            break;

        case TRUST_E_EXPLICIT_DISTRUST:
            // The hash that represents the subject or the publisher 
            // is not allowed by the admin or user.
            wprintf_s(L"The signature is present, but specifically "
                L"disallowed.\n");
            break;

        case TRUST_E_SUBJECT_NOT_TRUSTED:
            // The user clicked "No" when asked to install and run.
            wprintf_s(L"The signature is present, but not "
                L"trusted.\n");
            break;

        case CRYPT_E_SECURITY_SETTINGS:
            /*
            The hash that represents the subject or the publisher 
            was not explicitly trusted by the admin and the 
            admin policy has disabled user trust. No signature, 
            publisher or time stamp errors.
            */
            wprintf_s(L"CRYPT_E_SECURITY_SETTINGS - The hash "
                L"representing the subject or the publisher wasn't "
                L"explicitly trusted by the admin and admin policy "
                L"has disabled user trust. No signature, publisher "
                L"or timestamp errors.\n");
            break;

        default:
            // The UI was disabled in dwUIChoice or the admin policy 
            // has disabled user trust. lStatus contains the 
            // publisher or time stamp chain error.
            wprintf_s(L"Error is: 0x%x.\n",
                lStatus);
            break;
    }

    // Any hWVTStateData must be released by a call with close.
    WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;

    lStatus = WinVerifyTrust(
        NULL,
        &WVTPolicyGUID,
        &WinTrustData);

    return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
    if(argc > 1)
    {
        VerifyEmbeddedSignature(argv[1]);
    }

    return 0;
}


BOOLEAN IsFileDigitallySigned(PWCHAR FilePath)
{
    //Author: AD, 2009
    PVOID Context;
    HANDLE FileHandle;
    DWORD HashSize = 0;
    PBYTE Buffer;
    PVOID CatalogContext;
    CATALOG_INFO InfoStruct;
    WINTRUST_DATA WintrustStructure;
    WINTRUST_CATALOG_INFO WintrustCatalogStructure;
    WINTRUST_FILE_INFO WintrustFileStructure;
    PWCHAR MemberTag;
    BOOLEAN ReturnFlag = FALSE;
    ULONG ReturnVal;
    GUID ActionGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    //Zero our structures.
    memset(&InfoStruct, 0, sizeof(CATALOG_INFO));
    InfoStruct.cbStruct = sizeof(CATALOG_INFO);
    memset(&WintrustCatalogStructure, 0, sizeof(WINTRUST_CATALOG_INFO));
    WintrustCatalogStructure.cbStruct = sizeof(WINTRUST_CATALOG_INFO);
    memset(&WintrustFileStructure, 0, sizeof(WINTRUST_FILE_INFO));
    WintrustFileStructure.cbStruct = sizeof(WINTRUST_FILE_INFO);

    //Get a context for signature verification.
    if( !CryptCATAdminAcquireContext(&Context, NULL, 0) )
    {
        return FALSE;
    }

    //Open file.
    FileHandle = CreateFileW(FilePath, GENERIC_READ, 7, NULL, OPEN_EXISTING, 0, NULL);
    if( INVALID_HANDLE_VALUE == FileHandle )
    {
        CryptCATAdminReleaseContext(Context, 0);
        return FALSE;
    }

    //Get the size we need for our hash.
    CryptCATAdminCalcHashFromFileHandle(FileHandle, &HashSize, NULL, 0);
    if( HashSize == 0 )
    {
        //0-sized has means error!
        CryptCATAdminReleaseContext(Context, 0);
        CloseHandle(FileHandle);
        return FALSE;
    }

    //Allocate memory.
    Buffer = (PBYTE)calloc(HashSize, 1);

    //Actually calculate the hash
    if( !CryptCATAdminCalcHashFromFileHandle(FileHandle, &HashSize, Buffer, 0) )
    {
        CryptCATAdminReleaseContext(Context, 0);
        free(Buffer);
        CloseHandle(FileHandle);
        return FALSE;
    }

    //Convert the hash to a string.
    MemberTag = (PWCHAR)calloc((HashSize * 2) + 1, sizeof(WCHAR));
    for( unsigned int i = 0; i < HashSize; i++ )
    {
        swprintf(&MemberTag[i * 2], L"%02X", Buffer[i ]);
    }

    //Get catalog for our context.
    CatalogContext = CryptCATAdminEnumCatalogFromHash(Context, Buffer, HashSize, 0, NULL);
    if ( CatalogContext )
    {
        //If we couldn't get information
        if ( !CryptCATCatalogInfoFromContext(CatalogContext, &InfoStruct, 0) )
        {
            //Release the context and set the context to null so it gets picked up below.
            CryptCATAdminReleaseCatalogContext(Context, CatalogContext, 0);
            CatalogContext = NULL;
        }
    }
       
    //If we have a valid context, we got our info. 
    //Otherwise, we attempt to verify the internal signature.
    if( !CatalogContext )
    {
        WintrustFileStructure.cbStruct = sizeof(WINTRUST_FILE_INFO);
        WintrustFileStructure.pcwszFilePath = FilePath;
        WintrustFileStructure.hFile = NULL;
        WintrustFileStructure.pgKnownSubject = NULL;

        WintrustStructure.cbStruct = sizeof(WINTRUST_DATA);
        WintrustStructure.dwUnionChoice = WTD_CHOICE_FILE;
        WintrustStructure.pFile = &WintrustFileStructure;
        WintrustStructure.dwUIChoice = WTD_UI_NONE;
        WintrustStructure.fdwRevocationChecks = WTD_REVOKE_NONE;
        WintrustStructure.dwStateAction = WTD_STATEACTION_IGNORE;
        WintrustStructure.dwProvFlags = WTD_SAFER_FLAG;
        WintrustStructure.hWVTStateData = NULL;
        WintrustStructure.pwszURLReference = NULL;
    } else
    {
        //If we get here, we have catalog info!  Verify it.
        WintrustStructure.cbStruct = sizeof(WINTRUST_DATA);
        WintrustStructure.pPolicyCallbackData = 0;
        WintrustStructure.pSIPClientData = 0;
        WintrustStructure.dwUIChoice = WTD_UI_NONE;
        WintrustStructure.fdwRevocationChecks = WTD_REVOKE_NONE;
        WintrustStructure.dwUnionChoice = WTD_CHOICE_CATALOG;
        WintrustStructure.pCatalog = &WintrustCatalogStructure;
        WintrustStructure.dwStateAction = WTD_STATEACTION_VERIFY;
        WintrustStructure.hWVTStateData = NULL;
        WintrustStructure.pwszURLReference = NULL;
        WintrustStructure.dwProvFlags = 0;
        WintrustStructure.dwUIContext = WTD_UICONTEXT_EXECUTE;

        //Fill in catalog info structure.
        WintrustCatalogStructure.cbStruct = sizeof(WINTRUST_CATALOG_INFO);
        WintrustCatalogStructure.dwCatalogVersion = 0;
        WintrustCatalogStructure.pcwszCatalogFilePath = InfoStruct.wszCatalogFile;
        WintrustCatalogStructure.pcwszMemberTag = MemberTag;
        WintrustCatalogStructure.pcwszMemberFilePath = FilePath;
        WintrustCatalogStructure.hMemberFile = NULL;
    }

    //Call our verification function.
    ReturnVal = WinVerifyTrust(0, &ActionGuid, &WintrustStructure);

    //Check return.
    ReturnFlag = SUCCEEDED(ReturnVal);

    //Free context.
    if( CatalogContext )
        CryptCATAdminReleaseCatalogContext(Context, CatalogContext, 0);

    //If we successfully verified, we need to free.
    if( ReturnFlag )
    {
        WintrustStructure.dwStateAction = WTD_STATEACTION_CLOSE;
        WinVerifyTrust(0, &ActionGuid, &WintrustStructure);
    }

    //Free memory.
    free(MemberTag);
    free(Buffer);
    CloseHandle(FileHandle);
    CryptCATAdminReleaseContext(Context, 0);

    return ReturnFlag;
}


To make this work, you need to include the following headers:
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <mscat.h>
#include <wchar.h>


You also need to link with wintrust.lib - you can do this with:
#pragma comment(lib, "wintrust")