Ejemplo n.º 1
0
        public static bool IsSigned(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var file = new WINTRUST_FILE_INFO();

            file.cbStruct      = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO));
            file.pcwszFilePath = filePath;

            var data = new WINTRUST_DATA();

            data.cbStruct            = Marshal.SizeOf(typeof(WINTRUST_DATA));
            data.dwUIChoice          = WTD_UI_NONE;
            data.dwUnionChoice       = WTD_CHOICE_FILE;
            data.fdwRevocationChecks = WTD_REVOKE_NONE;
            data.pFile = Marshal.AllocHGlobal(file.cbStruct);
            Marshal.StructureToPtr(file, data.pFile, false);

            int hr;

            try {
                hr = WinVerifyTrust(INVALID_HANDLE_VALUE, WINTRUST_ACTION_GENERIC_VERIFY_V2, ref data);
            } finally {
                Marshal.FreeHGlobal(data.pFile);
            }
            return(hr == 0);
        }
Ejemplo n.º 2
0
        public static bool CheckFileDigitalSignature(string fileName)
        {
            Guid wintrust_action_generic_verify_v2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
            WINTRUST_FILE_INFO fileInfo            = new WINTRUST_FILE_INFO(fileName, Guid.Empty);
            WINTRUST_DATA      data = new WINTRUST_DATA(fileInfo);

            uint ret = 0;

            using (SignCheckerUnmanagedPointer guidPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid))), SignChecker_MemoryAllocator.HGlobal))
                using (SignCheckerUnmanagedPointer wvtDataPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_DATA))), SignChecker_MemoryAllocator.HGlobal))
                {
                    IntPtr pGuid = guidPtr;
                    IntPtr pData = wvtDataPtr;

                    Marshal.StructureToPtr(wintrust_action_generic_verify_v2, pGuid, false);
                    Marshal.StructureToPtr(data, pData, false);

                    ret = WinVerifyTrust(IntPtr.Zero, pGuid, pData);
                }

            if (ret != 0)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Checks if a file has a valid Authenticode signature.
        /// </summary>
        /// <param name="filePath">The path of a file to be checked.</param>
        /// <returns><c>true</c> if the file has a valid signature; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentException">Thrown if <paramref name="filePath" />
        /// is either <c>null</c> or an empty string.</exception>
        public override bool IsValid(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filePath));
            }

            var WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("{00AAC56B-CD44-11D0-8CC2-00C04FC295EE}");

            using (var pFilePath = new SafeCoTaskMem(filePath))
            {
                var fileInfo = new WINTRUST_FILE_INFO()
                {
                    pcwszFilePath = pFilePath.DangerousGetHandle()
                };

                using (var pFile = new SafeCoTaskMem((int)fileInfo.cbStruct))
                {
                    Marshal.StructureToPtr(fileInfo, pFile.DangerousGetHandle(), fDeleteOld: false);

                    var data = new WINTRUST_DATA()
                    {
                        pFile = pFile.DangerousGetHandle()
                    };

                    return(WinVerifyTrust(IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, data) == 0);
                }
            }
        }
Ejemplo n.º 4
0
    private static uint WinVerifyTrust(string fileName)
    {
        Guid wintrust_action_generic_verify_v2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
        uint result = 0;

        using (WINTRUST_FILE_INFO fileInfo = new WINTRUST_FILE_INFO(fileName,
                                                                    Guid.Empty))
            using (UnmanagedPointer guidPtr = new UnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid))),
                                                                   AllocMethod.HGlobal))
                using (UnmanagedPointer wvtDataPtr = new UnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_DATA))),
                                                                          AllocMethod.HGlobal))
                {
                    WINTRUST_DATA data  = new WINTRUST_DATA(fileInfo);
                    IntPtr        pGuid = guidPtr;
                    IntPtr        pData = wvtDataPtr;
                    Marshal.StructureToPtr(wintrust_action_generic_verify_v2,
                                           pGuid,
                                           true);
                    Marshal.StructureToPtr(data,
                                           pData,
                                           true);
                    result = WinVerifyTrust(IntPtr.Zero,
                                            pGuid,
                                            pData);
                }
        return(result);
    }
Ejemplo n.º 5
0
        public static unsafe SignatureVerificationResult VerifyAuthenticodeTrust(
            ProviderFlags flags,
            string file)
        {
            var fileInfo     = new WINTRUST_FILE_INFO();
            var wintrustData = new WINTRUST_DATA();

            try {
                fileInfo.cbStruct      = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO));
                fileInfo.pcwszFilePath = Marshal.StringToHGlobalAuto(file);

                wintrustData.cbStruct            = Marshal.SizeOf(typeof(WINTRUST_DATA));
                wintrustData.dwUIChoice          = WTD_UI_NONE;
                wintrustData.dwUnionChoice       = WTD_CHOICE_FILE;
                wintrustData.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
                wintrustData.pFile         = &fileInfo;
                wintrustData.dwStateAction = WTD_STATEACTION_VERIFY;
                wintrustData.dwProvFlags   = flags;
                wintrustData.dwUIContext   = WTD_UICONTEXT_INSTALL;

                try {
                    fixed(Guid *pgActionID = &WINTRUST_ACTION_GENERIC_VERIFY_V2)
                    return(WinVerifyTrust(IntPtr.Zero, pgActionID, &wintrustData));
                } finally {
                    wintrustData.dwStateAction = WTD_STATEACTION_CLOSE;

                    fixed(Guid *pgActionID = &WINTRUST_ACTION_GENERIC_VERIFY_V2)
                    WinVerifyTrust(IntPtr.Zero, pgActionID, &wintrustData);
                }
            } finally {
                Marshal.FreeHGlobal(fileInfo.pcwszFilePath);
            }
        }
Ejemplo n.º 6
0
 private void Dispose(bool disposing)
 {
     if (dwUnionChoice == UnionChoice.File)
     {
         WINTRUST_FILE_INFO info = new WINTRUST_FILE_INFO();
         Marshal.PtrToStructure(pInfoStruct, info);
         info.Dispose();
         Marshal.DestroyStructure(pInfoStruct, typeof(WINTRUST_FILE_INFO));
     }
     Marshal.FreeHGlobal(pInfoStruct);
 }
Ejemplo n.º 7
0
 public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
 {
     this.cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA));
     pInfoStruct   = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
     Marshal.StructureToPtr(fileInfo, pInfoStruct, false);
     this.dwUnionChoice  = UnionChoice.File;
     pPolicyCallbackData = IntPtr.Zero;
     pSIPCallbackData    = IntPtr.Zero;
     dwUIChoice          = UiChoice.NoUI;
     fdwRevocationChecks = RevocationCheckFlags.None;
     dwStateAction       = StateAction.Ignore;
     hWVTStateData       = IntPtr.Zero;
     pwszURLReference    = IntPtr.Zero;
     dwProvFlags         = TrustProviderFlags.Safer;
     dwUIContext         = UIContext.Execute;
 }
        public static bool Signed(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                Log.Error("SIGNED: File Path cannot be Null");
            }
            else
            {
                try
                {
                    var File = new WINTRUST_FILE_INFO
                    {
                        cbStruct      = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)),
                        pcwszFilePath = filePath
                    };

                    var Data = new WINTRUST_DATA
                    {
                        cbStruct            = Marshal.SizeOf(typeof(WINTRUST_DATA)),
                        dwUIChoice          = WTD_UI_NONE,
                        dwUnionChoice       = WTD_CHOICE_FILE,
                        fdwRevocationChecks = WTD_REVOKE_NONE,
                        pFile = Marshal.AllocHGlobal(File.cbStruct)
                    };
                    Marshal.StructureToPtr(File, Data.pFile, false);

                    int hr;
                    try
                    {
                        hr = WinVerifyTrust(INVALID_HANDLE_VALUE, WINTRUST_ACTION_GENERIC_VERIFY_V2, ref Data);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(Data.pFile);
                    }

                    return(hr == 0);
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("SIGNED", null, Error, null, true);
                    return(false);
                }
            }

            return(false);
        }
Ejemplo n.º 9
0
            // constructor for silent WinTrustDataChoice.File check
            public WINTRUST_DATA(String fileName)
            {
                this.cbStruct            = (UInt32)Marshal.SizeOf(typeof(WINTRUST_DATA));
                this.pPolicyCallbackData = IntPtr.Zero;
                this.pSIPClientData      = IntPtr.Zero;
                this.dwUIChoice          = WTDUIChoice.WTD_UI_NONE;
                this.fdwRevocationChecks = WTDRevocationChecks.WTD_REVOKE_NONE;
                this.dwUnionChoice       = WTDUnionChoice.WTD_CHOICE_FILE;
                this.dwStateAction       = WTDStateAction.WTD_STATEACTION_IGNORE;
                this.hWVTStateData       = IntPtr.Zero;
                this.pwszURLReference    = null;
                this.dwProvFlags         = WTDProvFlags.WTD_SAFER_FLAG;
                this.dwUIContext         = WTDUIContext.WTD_UICONTEXT_EXECUTE;

                WINTRUST_FILE_INFO wtfiData = new WINTRUST_FILE_INFO(fileName);

                this.pFile = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
                Marshal.StructureToPtr(wtfiData, pFile, false);
            }
Ejemplo n.º 10
0
                public WinTrustData(
                    WinTrustDataUIChoice uiChoice,
                    WinTrustDataRevocationChecks revocationCheck,
                    WinTrustDataChoice unionChoice,
                    WinTrustDataStateAction stateAction,
                    WinTrustDataProvFlags provFlags,
                    WinTrustDataUIContext uiContext,
                    WINTRUST_FILE_INFO fileInfo)
                {
                    this.UIChoice         = (uint)uiChoice;
                    this.RevocationChecks = (uint)revocationCheck;
                    this.UnionChoice      = (uint)unionChoice;
                    this.StateAction      = (uint)stateAction;
                    this.ProvFlags        = provFlags;
                    this.UIContext        = (uint)uiContext;

                    ProvFlags  |= WinTrustDataProvFlags.DisableMD2andMD4;
                    FileInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
                    Marshal.StructureToPtr(fileInfo, FileInfoPtr, false);
                }
Ejemplo n.º 11
0
        internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi)
        {
            WINTRUST_DATA wintrust_data;

            wintrust_data = new WINTRUST_DATA {
                cbStruct            = (int)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)),
                pPolicyCallbackData = IntPtr.Zero,
                pSIPClientData      = IntPtr.Zero,
                dwUIChoice          = 2,
                fdwRevocationChecks = 0,
                dwUnionChoice       = 1
            };
            IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi));

            Marshal.StructureToPtr(wfi, ptr, false);
            wintrust_data.Choice.pFile     = ptr;
            wintrust_data.dwStateAction    = 1;
            wintrust_data.hWVTStateData    = IntPtr.Zero;
            wintrust_data.pwszURLReference = null;
            wintrust_data.dwProvFlags      = 0;
            return(wintrust_data);
        }
Ejemplo n.º 12
0
            public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
            {
                cbStruct      = Marshal.SizeOf(typeof(WINTRUST_DATA));
                dwUnionChoice = NativeMethods.UnionChoice.File;

                pInfoStruct = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
                Marshal.StructureToPtr(fileInfo, pInfoStruct, false);

                pPolicyCallbackData = IntPtr.Zero;
                pSIPCallbackData    = IntPtr.Zero;

                dwUIChoice          = NativeMethods.UiChoice.NoUI;
                fdwRevocationChecks = NativeMethods.RevocationCheckFlags.None;
                dwStateAction       = NativeMethods.StateAction.Ignore;
                hWVTStateData       = IntPtr.Zero;
                pwszURLReference    = IntPtr.Zero;
                dwProvFlags         = NativeMethods.TrustProviderFlags.DisableMD2MD4;

                dwUIContext = NativeMethods.UIContext.Execute;

                pSignatureSettings = IntPtr.Zero;
            }
Ejemplo n.º 13
0
        internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName)
        {
            WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO();

            fi.cbStruct = (DWORD)Marshal.SizeOf(fi);
            fi.pcwszFilePath = fileName;
            fi.hFileNotUsed = IntPtr.Zero;
            fi.pgKnownSubjectNotUsed = IntPtr.Zero;

            return fi;
        }
Ejemplo n.º 14
0
        public static WinVerifyTrustResult WinVerifyTrust(string fileName)
        {
            WINTRUST_FILE_INFO fileInfo = new WINTRUST_FILE_INFO(fileName, Guid.Empty);
            WINTRUST_DATA      data     = new WINTRUST_DATA(fileInfo);

            uint result;

#if DEBUG
            uint r2;
#endif

            using (UnmanagedPointer guidPtr = new UnmanagedPointer(typeof(Guid), true))
                using (UnmanagedPointer wvtDataPtr = new UnmanagedPointer(typeof(WINTRUST_DATA), true))
                {
                    IntPtr pGuid = guidPtr;
                    IntPtr pData = wvtDataPtr;

                    Marshal.StructureToPtr(wintrust_action_generic_verify_v2, pGuid, false);

                    data.dwStateAction = NativeMethods.StateAction.Verify;
                    Marshal.StructureToPtr(data, pData, false);

                    result = NativeMethods.WinVerifyTrust(INVALID_HANDLE_VALUE, pGuid, pData);

                    data.dwStateAction = NativeMethods.StateAction.Close;
                    Marshal.StructureToPtr(data, pData, true);
#if DEBUG
                    r2 =
#endif
                    NativeMethods.WinVerifyTrust(INVALID_HANDLE_VALUE, pGuid, pData);
                }

            if ((result >= (uint)NativeMethods.TrustE.ProviderUnknown) && (result <= (uint)NativeMethods.TrustE.SubjectNotTrusted))
            {
                return((WinVerifyTrustResult)((int)(result - (uint)NativeMethods.TrustE.Unknown) + (int)WinVerifyTrustResult.FunctionCallFailed));
            }

            switch (result)
            {
            case NativeMethods.ERROR_SUCCESS:
                return(WinVerifyTrustResult.Success);

            case (uint)NativeMethods.TrustE.FileError:
                return(WinVerifyTrustResult.FileError);

            case (uint)NativeMethods.TrustE.BadMsg:
                return(WinVerifyTrustResult.BadMsg);

            case (uint)NativeMethods.TrustE.SecuritySettings:
                return(WinVerifyTrustResult.SecuritySettings);

            case (uint)NativeMethods.TrustE.ASN1BadTag:
                return(WinVerifyTrustResult.ASN1BadTag);

            case (uint)NativeMethods.TrustE.CounterSigner:
                return(WinVerifyTrustResult.CounterSigner);

            case (uint)NativeMethods.TrustE.BadDigest:
                return(WinVerifyTrustResult.BadDigest);

            case (uint)NativeMethods.TrustE.NoSignature:
                return(WinVerifyTrustResult.NoSignature);

            case (uint)NativeMethods.TrustE.CertExpired:
                return(WinVerifyTrustResult.CertExpired);

            case (uint)NativeMethods.TrustE.CertUntrustedRoot:
                return(WinVerifyTrustResult.CertUntrustedRoot);

            case (uint)NativeMethods.TrustE.CertChaining:
                return(WinVerifyTrustResult.CertChaining);

            case (uint)NativeMethods.TrustE.CertRevoked:
                return(WinVerifyTrustResult.CertRevoked);

            case (uint)NativeMethods.TrustE.CertWrongUsage:
                return(WinVerifyTrustResult.CertWrongUsage);

            case (uint)NativeMethods.TrustE.ExplicitDistrust:
                return(WinVerifyTrustResult.ExplicitDistrust);

            default:
                return(WinVerifyTrustResult.FunctionCallFailed);
            }
        }
Ejemplo n.º 15
0
            public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
            {
                this.cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA));
                pInfoStruct = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
                Marshal.StructureToPtr(fileInfo, pInfoStruct, false);
                dwUnionChoice = SignChecker_UnionChoice.File;
                pPolicyCallbackData = IntPtr.Zero;
                pSIPCallbackData = IntPtr.Zero;
                dwUIChoice = SignChecker_UiChoice.NoUI;
                fdwRevocationChecks = SignChecker_RevocationCheckFlags.WholeChain;
                dwStateAction = SignChecker_StateAction.Ignore;
                hWVTStateData = IntPtr.Zero;
                pwszURLReference = IntPtr.Zero;
                dwProvFlags = SignChecker_TrustProviderFlags.RevocationCheckChain;

                dwUIContext = SignChecker_UIContext.Execute;
            }
Ejemplo n.º 16
0
            private void Dispose(bool disposing)
            {
                if (dwUnionChoice == SignChecker_UnionChoice.File)
                {
                    WINTRUST_FILE_INFO info = new WINTRUST_FILE_INFO();
                    Marshal.PtrToStructure(pInfoStruct, info);
                    info.Dispose();
                    Marshal.DestroyStructure(pInfoStruct, typeof(WINTRUST_FILE_INFO));
                }

                Marshal.FreeHGlobal(pInfoStruct);
            }
Ejemplo n.º 17
0
        public static bool CheckFileDigitalSignature(string fileName)
        {
            Guid wintrust_action_generic_verify_v2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
            WINTRUST_FILE_INFO fileInfo = new WINTRUST_FILE_INFO(fileName, Guid.Empty);
            WINTRUST_DATA data = new WINTRUST_DATA(fileInfo);

            uint ret = 0;

            using (SignCheckerUnmanagedPointer guidPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid))), SignChecker_MemoryAllocator.HGlobal))
            using (SignCheckerUnmanagedPointer wvtDataPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_DATA))), SignChecker_MemoryAllocator.HGlobal))
            {
                IntPtr pGuid = guidPtr;
                IntPtr pData = wvtDataPtr;

                Marshal.StructureToPtr(wintrust_action_generic_verify_v2, pGuid, false);
                Marshal.StructureToPtr(data, pData, false);

                ret = WinVerifyTrust(IntPtr.Zero, pGuid, pData);
            }

            if (ret != 0)
            {
                return false;
            }

            return true;
        }
Ejemplo n.º 18
0
        internal static void Main(string[] args)
        {
            string fileName = args[0];
            IntPtr hWind    = IntPtr.Zero;
            Guid   WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");

            byte[] actionIdBytes = WINTRUST_ACTION_GENERIC_VERIFY_V2.ToByteArray();
            IntPtr pcwszFilePath = Marshal.StringToHGlobalAuto(fileName);

            try
            {
                WINTRUST_FILE_INFO File = new WINTRUST_FILE_INFO()
                {
                    cbStruct       = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)),
                    pcwszFilePath  = pcwszFilePath,
                    hFile          = IntPtr.Zero,
                    pgKnownSubject = IntPtr.Zero,
                };
                IntPtr ptrFile = Marshal.AllocHGlobal(File.cbStruct);
                try
                {
                    Marshal.StructureToPtr(File, ptrFile, false);
                    WINTRUST_DATA WVTData = new WINTRUST_DATA()
                    {
                        cbStruct            = Marshal.SizeOf(typeof(WINTRUST_DATA)),
                        pPolicyCallbackData = IntPtr.Zero,
                        pSIPClientData      = IntPtr.Zero,
                        dwUIChoice          = WTD_UI_NONE,
                        fdwRevocationChecks = WTD_REVOKE_NONE,
                        dwUnionChoice       = WTD_CHOICE_FILE,
                        pFile              = ptrFile,
                        dwStateAction      = WTD_STATEACTION_IGNORE,
                        hWVTStateData      = IntPtr.Zero,
                        pwszURLReference   = IntPtr.Zero,
                        dwProvFlags        = WTD_REVOCATION_CHECK_NONE,
                        dwUIContext        = WTD_UICONTEXT_EXECUTE,
                        pSignatureSettings = IntPtr.Zero,
                    };
                    // N.B. Use of this member is only supported on Windows 8 and Windows Server 2012 (and later)
                    WINTRUST_SIGNATURE_SETTINGS signatureSettings = default(WINTRUST_SIGNATURE_SETTINGS);
                    bool   canUseSignatureSettings = Environment.OSVersion.Version > new Version(6, 2, 0, 0);
                    IntPtr pSignatureSettings      = IntPtr.Zero;
                    if (canUseSignatureSettings)
                    {
                        // Setup WINTRUST_SIGNATURE_SETTINGS to get the number of signatures in the file
                        signatureSettings = new WINTRUST_SIGNATURE_SETTINGS()
                        {
                            cbStruct           = Marshal.SizeOf(typeof(WINTRUST_SIGNATURE_SETTINGS)),
                            dwIndex            = 0,
                            dwFlags            = WSS_GET_SECONDARY_SIG_COUNT,
                            cSecondarySigs     = 0,
                            dwVerifiedSigIndex = 0,
                            pCryptoPolicy      = IntPtr.Zero,
                        };
                        pSignatureSettings = Marshal.AllocHGlobal(signatureSettings.cbStruct);
                    }
                    try
                    {
                        if (pSignatureSettings != IntPtr.Zero)
                        {
                            Marshal.StructureToPtr(signatureSettings, pSignatureSettings, false);
                            WVTData.pSignatureSettings = pSignatureSettings;
                        }
                        IntPtr pgActionID = Marshal.AllocHGlobal(actionIdBytes.Length);
                        try
                        {
                            Marshal.Copy(actionIdBytes, 0, pgActionID, actionIdBytes.Length);
                            IntPtr pWVTData = Marshal.AllocHGlobal(WVTData.cbStruct);
                            try
                            {
                                Marshal.StructureToPtr(WVTData, pWVTData, false);
                                int hRESULT = WinVerifyTrust(hWind, pgActionID, pWVTData);
                                if (hRESULT == 0)
                                {
                                    if (pSignatureSettings != IntPtr.Zero)
                                    {
                                        // Read back the signature settings
                                        signatureSettings = (WINTRUST_SIGNATURE_SETTINGS)Marshal.PtrToStructure(pSignatureSettings, typeof(WINTRUST_SIGNATURE_SETTINGS));
                                    }
                                    int signatureCount = signatureSettings.cSecondarySigs + 1;
                                    Console.WriteLine("File: {0}", fileName);
                                    Console.WriteLine("Authenticode signatures: {0}", signatureCount);
                                    Console.WriteLine();
                                    for (int dwIndex = 0; dwIndex < signatureCount; dwIndex++)
                                    {
                                        if (pSignatureSettings != IntPtr.Zero)
                                        {
                                            signatureSettings.dwIndex = dwIndex;
                                            signatureSettings.dwFlags = WSS_VERIFY_SPECIFIC;
                                            Marshal.StructureToPtr(signatureSettings, pSignatureSettings, false);
                                        }
                                        WVTData.dwStateAction = WTD_STATEACTION_VERIFY;
                                        WVTData.hWVTStateData = IntPtr.Zero;
                                        Marshal.StructureToPtr(WVTData, pWVTData, false);
                                        hRESULT = WinVerifyTrust(hWind, pgActionID, pWVTData);
                                        try
                                        {
                                            if (hRESULT == 0)
                                            {
                                                WVTData = (WINTRUST_DATA)Marshal.PtrToStructure(pWVTData, typeof(WINTRUST_DATA));
                                                IntPtr ptrProvData           = WTHelperProvDataFromStateData(WVTData.hWVTStateData);
                                                CRYPT_PROVIDER_DATA provData = (CRYPT_PROVIDER_DATA)Marshal.PtrToStructure(ptrProvData, typeof(CRYPT_PROVIDER_DATA));
                                                for (int idxSigner = 0; idxSigner < provData.csSigners; idxSigner++)
                                                {
                                                    IntPtr ptrProvSigner           = WTHelperGetProvSignerFromChain(ptrProvData, idxSigner, false, 0);
                                                    CRYPT_PROVIDER_SGNR ProvSigner = (CRYPT_PROVIDER_SGNR)Marshal.PtrToStructure(ptrProvSigner, typeof(CRYPT_PROVIDER_SGNR));
                                                    CMSG_SIGNER_INFO    Signer     = (CMSG_SIGNER_INFO)Marshal.PtrToStructure(ProvSigner.psSigner, typeof(CMSG_SIGNER_INFO));
                                                    if (Signer.HashAlgorithm.pszObjId != IntPtr.Zero)
                                                    {
                                                        string objId = Marshal.PtrToStringAnsi(Signer.HashAlgorithm.pszObjId);
                                                        if (objId != null)
                                                        {
                                                            Oid hashOid = Oid.FromOidValue(objId, OidGroup.All);
                                                            if (hashOid != null)
                                                            {
                                                                Console.WriteLine("Hash algorithm of signature {0}: {1}.", dwIndex + 1, hashOid.FriendlyName);
                                                            }
                                                        }
                                                    }
                                                    IntPtr ptrCert           = WTHelperGetProvCertFromChain(ptrProvSigner, idxSigner);
                                                    CRYPT_PROVIDER_CERT cert = (CRYPT_PROVIDER_CERT)Marshal.PtrToStructure(ptrCert, typeof(CRYPT_PROVIDER_CERT));
                                                    if (cert.cbStruct > 0)
                                                    {
                                                        X509Certificate2 certificate = new X509Certificate2(cert.pCert);
                                                        Console.WriteLine("Certificate thumbprint of signature {0}: {1}", dwIndex + 1, certificate.Thumbprint);
                                                    }
                                                    if (ProvSigner.sftVerifyAsOf.dwHighDateTime != provData.sftSystemTime.dwHighDateTime &&
                                                        ProvSigner.sftVerifyAsOf.dwLowDateTime != provData.sftSystemTime.dwLowDateTime)
                                                    {
                                                        DateTime timestamp = DateTime.FromFileTimeUtc(((long)ProvSigner.sftVerifyAsOf.dwHighDateTime << 32) | (uint)ProvSigner.sftVerifyAsOf.dwLowDateTime);
                                                        Console.WriteLine("Timestamp of signature {0}: {1}", dwIndex + 1, timestamp);
                                                    }
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            WVTData.dwStateAction = WTD_STATEACTION_CLOSE;
                                            Marshal.StructureToPtr(WVTData, pWVTData, false);
                                            hRESULT = WinVerifyTrust(hWind, pgActionID, pWVTData);
                                        }
                                        Console.WriteLine();
                                    }
                                }
                                else if ((uint)hRESULT == 0x800b0100)
                                {
                                    Console.WriteLine("{0} has no Authenticode signatures.", fileName);
                                }
                            }
                            finally
                            {
                                Marshal.FreeHGlobal(pWVTData);
                            }
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(pgActionID);
                        }
                    }
                    finally
                    {
                        if (pSignatureSettings != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(pSignatureSettings);
                        }
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(ptrFile);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(pcwszFilePath);
            }
            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 19
0
 internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi)
 {
     WINTRUST_DATA wintrust_data;
     wintrust_data = new WINTRUST_DATA {
         cbStruct = (int)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)),
         pPolicyCallbackData = IntPtr.Zero,
         pSIPClientData = IntPtr.Zero,
         dwUIChoice = 2,
         fdwRevocationChecks = 0,
         dwUnionChoice = 1
     };
     IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi));
     Marshal.StructureToPtr(wfi, ptr, false);
     wintrust_data.Choice.pFile = ptr;
     wintrust_data.dwStateAction = 1;
     wintrust_data.hWVTStateData = IntPtr.Zero;
     wintrust_data.pwszURLReference = null;
     wintrust_data.dwProvFlags = 0;
     return wintrust_data;
 }
Ejemplo n.º 20
0
        public WinVerifyTrustResult GetSign(string filePath)
        {
            var result = new WinVerifyTrustResult();

            var file = new WINTRUST_FILE_INFO
            {
                cbStruct      = Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)),
                pcwszFilePath = filePath
            };

            var data = new WINTRUST_DATA
            {
                cbStruct            = Marshal.SizeOf(typeof(WINTRUST_DATA)),
                dwUIChoice          = NativeMethods.WTD_UI_NONE,
                dwUnionChoice       = NativeMethods.WTD_CHOICE_FILE,
                fdwRevocationChecks = NativeMethods.WTD_REVOKE_NONE,
                dwStateAction       = NativeMethods.WTD_STATEACTION_VERIFY,
                pFile = Marshal.AllocHGlobal(file.cbStruct)
            };

            Marshal.StructureToPtr(file, data.pFile, false);

            try
            {
                var hr = NativeMethods.WinVerifyTrust(NativeMethods.INVALID_HANDLE_VALUE, NativeMethods.WINTRUST_ACTION_GENERIC_VERIFY_V2, ref data);

                result.HasSign     = (hr == NativeMethods.TRUST_SUCCESS || hr == NativeMethods.TRUST_E_BAD_DIGEST);
                result.IsSignValid = hr == NativeMethods.TRUST_SUCCESS;

                if (result.HasSign)
                {
                    IntPtr ptrProvData = NativeMethods.WTHelperProvDataFromStateData(data.hWVTStateData);
                    var    lastError   = Marshal.GetLastWin32Error();

                    if (ptrProvData == IntPtr.Zero && result.IsSignValid)
                    {
                        throw new Win32Exception(lastError);
                    }

                    IntPtr ptrProvSigner = NativeMethods.WTHelperGetProvSignerFromChain(ptrProvData, 0, false, 0);
                    lastError = Marshal.GetLastWin32Error();

                    if (ptrProvSigner == IntPtr.Zero)
                    {
                        throw new Win32Exception(lastError);
                    }

                    IntPtr ptrCert = NativeMethods.WTHelperGetProvCertFromChain(ptrProvSigner, 0);
                    lastError = Marshal.GetLastWin32Error();

                    if (ptrCert == IntPtr.Zero)
                    {
                        throw new Win32Exception(lastError);
                    }

                    CRYPT_PROVIDER_CERT cert = (CRYPT_PROVIDER_CERT)Marshal.PtrToStructure(ptrCert, typeof(CRYPT_PROVIDER_CERT));

                    using (X509Certificate2 certificate = new X509Certificate2(cert.pCert))
                    {
                        result.Publisher = GetPublisherName(certificate.Subject);
                    }
                }
            }
            finally
            {
                data.dwStateAction = NativeMethods.WTD_STATEACTION_CLOSE;

                NativeMethods.WinVerifyTrust(NativeMethods.INVALID_HANDLE_VALUE, NativeMethods.WINTRUST_ACTION_GENERIC_VERIFY_V2, ref data);

                Marshal.FreeHGlobal(data.pFile);
            }
            return(result);
        }
Ejemplo n.º 21
0
        internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi)
        {
            WINTRUST_DATA wtd = new WINTRUST_DATA();

            wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd);
            wtd.pPolicyCallbackData = IntPtr.Zero;
            wtd.pSIPClientData = IntPtr.Zero;
            wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE;
            wtd.fdwRevocationChecks = 0;
            wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_FILE;

            IntPtr pFileBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi));
            Marshal.StructureToPtr(wfi, pFileBuffer, false);
            wtd.Choice.pFile = pFileBuffer;

            wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY;
            wtd.hWVTStateData = IntPtr.Zero;
            wtd.pwszURLReference = null;
            wtd.dwProvFlags = 0;

            return wtd;
        }