public static bool HasValidSignature(string fileName) { try { if (_isValidCache.Contains(fileName)) { return(true); } var wtd = new WinTrustData(fileName); var guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinTrust.WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); bool ret = (result == WinVerifyTrustResult.Success); if (ret) { _isValidCache.Add(fileName); } #if COAPP_ENGINE_CORE var response = Event <GetResponseInterface> .RaiseFirst(); if (response != null) { response.SignatureValidation(fileName, ret, ret ? Verifier.GetPublisherInformation(fileName)["PublisherName"] : null); } #endif return(ret); } catch (Exception) { return(false); } }
/// /// Calls WinTrust.WinVerifyTrust() to check embedded file signature /// /// absolute path and file name /// validation to perform /// enumeration /// true if the signature is valid, otherwise false public static bool VerifyEmbeddedSignature(string fileName, Guid guidAction, WinTrustDataRevocationChecks revocationChecks) { WinTrustData wtd = new WinTrustData(fileName, revocationChecks); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); return(result == WinVerifyTrustResult.Success); }
public static bool VerifyEmbeddedSignature(string fileName) { WinTrustData pWVTData = new WinTrustData(fileName); WinVerifyTrustResult winVerifyTrustResult = WinVerifyTrust(pgActionID: new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2), hwnd: INVALID_HANDLE_VALUE, pWVTData: pWVTData); return(winVerifyTrustResult == WinVerifyTrustResult.Success); }
/// <summary> /// Given a catalog file, extracts the signer name /// </summary> /// <param name="FileName"></param> /// <param name="SignerName"></param> /// <returns></returns> public static WinVerifyTrustResult VerifyCatalogFile(string FileName, string CatalogName, string Hash, IntPtr hCatAdmin) { // Much of this comes from: http://forum.sysinternals.com/howto-verify-the-digital-signature-of-a-file_topic19247.html WinVerifyTrustResult result = WinVerifyTrustResult.FileNotSigned; WinTrustData wtd = new WinTrustData(FileName, true, Hash, CatalogName, hCatAdmin); wtd.dwStateAction = WinTrustDataStateAction.Verify; Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); try { result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); if (result != WinVerifyTrustResult.Success) { return(result); } } finally { // Clean up wtd.dwStateAction = WinTrustDataStateAction.Close; WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); } return(result); }
/// <summary> /// Calls WinVerifyTrust() to check embedded file signature /// </summary> /// <param name="FileName"></param> /// <param name="SignerName"></param> /// <returns></returns> public static WinVerifyTrustResult VerifyEmbeddedSignature(string FileName) { WinVerifyTrustResult result = WinVerifyTrustResult.FileNotSigned; WinTrustData wtd = new WinTrustData(FileName, false, null, null, IntPtr.Zero); wtd.dwStateAction = WinTrustDataStateAction.Verify; Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); try { try { result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); if (result != WinVerifyTrustResult.Success) { return(result); } } catch (Exception) { } } finally { // Clean up wtd.dwStateAction = WinTrustDataStateAction.Close; WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); } return(result); }
// call WinTrust.WinVerifyTrust() to check embedded file signature public static bool VerifyEmbeddedSignature(string fileName) { WinTrustFileInfo winTrustFileInfo = null; WinTrustData winTrustData = null; try { winTrustFileInfo = new WinTrustFileInfo(fileName); winTrustData = new WinTrustData(winTrustFileInfo); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, winTrustData); bool ret = (result == WinVerifyTrustResult.Success); return(ret); } finally { // free the locally-held unmanaged memory in the data structures if (winTrustFileInfo != null) { winTrustFileInfo.Dispose(); } if (winTrustData != null) { winTrustData.Dispose(); } } }
private static string GetVerboseWinVerifyTrustResultErrorString(WinVerifyTrustResult result) { switch (result) { case WinVerifyTrustResult.ActionUnknown: return("Trust provider does not support the specified action"); case WinVerifyTrustResult.FileNotSigned: return("File was not signed"); case WinVerifyTrustResult.ProviderUnknown: return("Trust provider is not recognized on this system"); case WinVerifyTrustResult.SubjectFormUnknown: return("Trust provider does not support the form specified for the subject"); case WinVerifyTrustResult.SubjectNotTrusted: return("Subject failed the specified verification action"); case WinVerifyTrustResult.UntrustedRootCert: return("A certification chain processed correctly but terminated in a root certificate that is not trusted by the trust provider"); default: return("Unknown WinVerifyTrustResult value"); } }
private void Form1_Shown(object sender, EventArgs e) { Form.CheckForIllegalCrossThreadCalls = false; this.listBox1.SelectedIndexChanged += new System.EventHandler(delegate(object o, EventArgs a) { try { Process curr = pArray[this.listBox1.SelectedIndex]; richTextBox1.Text = "Target Process = " + curr.ProcessName + " , pid = " + curr.Id + "\n"; foreach (ProcessModule i in curr.Modules) { richTextBox1.Text += i.FileVersionInfo.ToString() + "path: " + i.FileName + "\n"; WinVerifyTrustResult result = WinTrust.VerifySignatureResult(i.FileName); richTextBox1.Text += ("簽章確認結果:\t" + result + "\n"); richTextBox1.Text += "==============================\n"; } } catch (Exception ex) { richTextBox1.Text = ex.ToString(); } }); this.listBox1.GotFocus += new System.EventHandler(delegate(Object o, EventArgs a) { isHang = true; }); this.listBox1.LostFocus += new System.EventHandler(delegate(Object o, EventArgs a) { isHang = false; }); (new System.Threading.Thread(() => { while (true) { if (isHang) { continue; } if (pArray == null || Process.GetProcesses().Length != pArray.Length) { pArray = Process.GetProcesses(); this.Invoke(new MethodInvoker(() => listBox1.Items.Clear())); foreach (var i in pArray) { this.Invoke(new MethodInvoker(() => listBox1.Items.Add(i.Id + "\t" + i.ProcessName))); } } else { System.Threading.Thread.Sleep(1000); continue; } } }) { IsBackground = true }).Start(); richTextBox1.Focus(); }
// call WinTrust.WinVerifyTrust() to check embedded file signature public static bool VerifyEmbeddedSignature(string fileName, WinVerifyTrustResult expectedResult) { WinTrustData wtd = new WinTrustData(fileName); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); bool ret = (result == expectedResult); return ret; }
public static WinVerifyTrustResult VerifySignatureResult(string fileName) { WinTrustData wtd = new WinTrustData(fileName); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); return(result); }
public static bool VerifyEmbeddedSignature(string fileName) { var wtd = new WinTrustData(fileName); var guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); bool ret = (result == WinVerifyTrustResult.Success); return(ret); }
// call WinTrust.WinVerifyTrust() to check embedded file signature public static bool VerifyEmbeddedSignature(string fileName, bool allowInvalidRoot) { WinTrustData wtd = new WinTrustData(fileName); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); logger.Info("Result: {0}", result); bool ret = (result == WinVerifyTrustResult.Success || (allowInvalidRoot && result == WinVerifyTrustResult.UntrustedRoot)); return(ret); }
// call WinTrust.WinVerifyTrust() to check embedded file signature public static bool VerifyEmbeddedSignature(string fileName) { WinTrustFileInfo wtfi = new WinTrustFileInfo(fileName); WinTrustData wtd = new WinTrustData(wtfi); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); bool ret = (result == WinVerifyTrustResult.Success); wtfi.Dispose(); wtd.Dispose(); return(ret); }
public bool SignatureExist(string fileName) { WinTrustFileInfo wtfi = new WinTrustFileInfo(fileName); WinTrustData wtd = new WinTrustData(wtfi); Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = Win32Api.WinVerifyTrust(new IntPtr(-1), guidAction, wtd); bool ret = (result == WinVerifyTrustResult.Success); wtfi.Dispose(); wtd.Dispose(); return(ret); }
public static bool VerifyEmbeddedSignature(string fileName) { using (WinTrustFileInfo wtfi = new WinTrustFileInfo(fileName)) { using (WinTrustData wtd = new WinTrustData(wtfi)) { Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); return(result == WinVerifyTrustResult.Success || result == WinVerifyTrustResult.UntrustedRoot || result == WinVerifyTrustResult.CertChaining); } } }
/// <summary> /// Checks if a file can be verified by it's code signature /// </summary> /// <param name="FileName"></param> /// <param name="SignerName"></param> /// <returns></returns> public static bool Verify(string FileName, out List <Signer> Signers) { WinVerifyTrustResult result = VerifyEmbeddedSignature(FileName, out Signers); if (result == WinVerifyTrustResult.FileNotSigned) { // File may have been signed in a catalog, so check those. // First look for a SHA256 signature result = VerifyFileFromCatalog(FileName, "SHA256", out Signers); if (result != WinVerifyTrustResult.Success) { // No SHA256 found, so look for whatever we can result = VerifyFileFromCatalog(FileName, null, out Signers); } } return(result == WinVerifyTrustResult.Success); }
/// <summary> /// Calls WinVerifyTrust() to check embedded file signature /// </summary> /// <param name="FileName"></param> /// <param name="SignerName"></param> /// <returns></returns> public static WinVerifyTrustResult VerifyEmbeddedSignature(string FileName, out List <Signer> Signers) { Signers = null; WinVerifyTrustResult result = WinVerifyTrustResult.FileNotSigned; WinTrustData wtd = new WinTrustData(FileName, false, null, null, IntPtr.Zero); wtd.dwStateAction = WinTrustDataStateAction.Verify; Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); try { try { Log.Debug("Getting embedded signature"); result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); if (result != WinVerifyTrustResult.Success) { if (result != WinVerifyTrustResult.FileNotSigned) { // TODO We should handle this as this is weird Log.Warn("Verification failed due to reason {0}", result); } return(result); } var signer = GetSignerFromStateData(wtd.hWVTStateData); Signers = new List <Signer>(); Signers.Add(signer); } catch (Exception e) { Log.Exception(e, "Exception in VerifyEmbeddedSignature"); } } finally { // Clean up wtd.dwStateAction = WinTrustDataStateAction.Close; WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); } return(result); }
/// <summary> /// Given a catalog file, extracts the signer name /// </summary> /// <param name="FileName"></param> /// <param name="SignerName"></param> /// <returns></returns> public static WinVerifyTrustResult VerifyCatalogFile(string FileName, string CatalogName, string Hash, out List <Signer> Signers, IntPtr hCatAdmin) { // Much of this comes from: http://forum.sysinternals.com/howto-verify-the-digital-signature-of-a-file_topic19247.html WinVerifyTrustResult result = WinVerifyTrustResult.FileNotSigned; WinTrustData wtd = new WinTrustData(FileName, true, Hash, CatalogName, hCatAdmin); wtd.dwStateAction = WinTrustDataStateAction.Verify; Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); Signers = null; try { result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); if (result != WinVerifyTrustResult.Success) { if (result != WinVerifyTrustResult.FileNotSigned) { Log.Warn("Verification failed due to reason {0}", result); } return(result); } var signer = GetSignerFromStateData(wtd.hWVTStateData); Signers = new List <Signer>(); Signers.Add(signer); } finally { // Clean up wtd.dwStateAction = WinTrustDataStateAction.Close; WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd); } return(result); }
// call WinTrust.WinVerifyTrust() to check embedded file signature public static string VerifyEmbeddedSignature(string filename) { WinTrustFileInfo winTrustFileInfo = null; WinTrustData winTrustData = null; try { // specify the WinVerifyTrust function/action that we want Guid action = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); // instantiate our WinTrustFileInfo and WinTrustData data structures winTrustFileInfo = new WinTrustFileInfo(filename); winTrustData = new WinTrustData(filename); // call into WinVerifyTrust WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, action, winTrustData); switch (result) { case WinVerifyTrustResult.Success: return("Valid"); case WinVerifyTrustResult.ProviderUnknown: return("ProviderUnknown"); case WinVerifyTrustResult.ActionUnknown: return("ActionUnknown"); case WinVerifyTrustResult.SubjectFormUnknown: return("SubjectFormUnknown"); case WinVerifyTrustResult.SubjectNotTrusted: return("SubjectNotTrusted"); case WinVerifyTrustResult.FileNotSigned: return("FileNotSigned"); case WinVerifyTrustResult.SubjectExplicitlyDistrusted: return("SubjectExplicitlyDistrusted"); case WinVerifyTrustResult.SignatureOrFileCorrupt: return("SignatureOrFileCorrupt"); case WinVerifyTrustResult.SubjectCertExpired: return("SubjectCertExpired"); case WinVerifyTrustResult.SubjectCertificateRevoked: return("SubjectCertificateRevoked"); case WinVerifyTrustResult.UntrustedRoot: return("UntrustedRoot"); default: // The UI was disabled in dwUIChoice or the admin policy // has disabled user trust. lStatus contains the // publisher or time stamp chain error. return(result.ToString()); } } catch (Exception e) { Log.Debug("{0} error decoding signature on {1}", e.GetType().ToString(), filename); } return("Unknown"); }
/// <summary> /// Looks in Microsoft's catalog files to verify a file /// </summary> /// <param name="FileName"></param> /// <param name="HashAlgorithm"></param> /// <param name="SignerName"></param> /// <returns></returns> public static WinVerifyTrustResult VerifyFileFromCatalog(string FileName, string HashAlgorithm, out List <Signer> Signers) { WinVerifyTrustResult result = WinVerifyTrustResult.FileNotSigned; Signers = null; // TODO MUST set this // // Check file is not too large // long length = new System.IO.FileInfo(FileName).Length; if (length > 32 * 1024 * 1024) { // TODO IMPORTANT Do something better for large files return(WinVerifyTrustResult.FileNotSigned); } IntPtr phCatAdmin = IntPtr.Zero; Guid pgSubSystem = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); // // Get phCatAdmin handle. First try using the Windows 8 function CryptCATAdminAcquireContext2, then use the normal function // if (FunctionExists("wintrust.dll", "CryptCATAdminAcquireContext2")) { // Function exists, so use it. if (!CryptCATAdminAcquireContext2(out phCatAdmin, IntPtr.Zero, HashAlgorithm, IntPtr.Zero, 0)) { // Function exists, but could not be used, that is weird. Log.Error("Call to CryptCATAdminAcquireContext2 failed with error {0}", Marshal.GetLastWin32Error()); return(WinVerifyTrustResult.FileNotSigned); } } else { // New function does not exist, so use the old one. if (!CryptCATAdminAcquireContext(out phCatAdmin, IntPtr.Zero, 0)) { Log.Error("Call to CryptCATAdminAcquireContext failed with error {0}", Marshal.GetLastWin32Error()); return(WinVerifyTrustResult.FileNotSigned); } } // // Get handle to file // SafeFileHandle hFile = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (hFile.IsInvalid) { Log.Error("Call to CreateFile failed with error {0}", Marshal.GetLastWin32Error()); return(WinVerifyTrustResult.FileNotSigned); } // // Calc hash // UInt32 fileHashLength = 16; IntPtr fileHash = Marshal.AllocHGlobal((int)fileHashLength); if (FunctionExists("wintrust.dll", "CryptCATAdminCalcHashFromFileHandle2")) { // Get size of the file hash to be used if (!CryptCATAdminCalcHashFromFileHandle2(phCatAdmin, hFile, ref fileHashLength, fileHash, 0)) { // Alloc the correct amount and try again Marshal.FreeHGlobal(fileHash); fileHash = Marshal.AllocHGlobal((int)fileHashLength); if (!CryptCATAdminCalcHashFromFileHandle2(phCatAdmin, hFile, ref fileHashLength, fileHash, 0)) { // Something went wrong Log.Error("Call to CryptCATAdminCalcHashFromFileHandle2 failed with error {0}", Marshal.GetLastWin32Error()); // Clean up CryptCATAdminReleaseContext(phCatAdmin, 0); Marshal.FreeHGlobal(fileHash); return(WinVerifyTrustResult.FileNotSigned); } } } else { // Get size of the file hash to be used if (!CryptCATAdminCalcHashFromFileHandle(hFile, ref fileHashLength, fileHash, 0)) { // Alloc the correct amount and try again Marshal.FreeHGlobal(fileHash); fileHash = Marshal.AllocHGlobal((int)fileHashLength); if (!CryptCATAdminCalcHashFromFileHandle(hFile, ref fileHashLength, fileHash, 0)) { // Something went wrong Log.Error("Call to CryptCATAdminCalcHashFromFileHandle2 failed with error {0}", Marshal.GetLastWin32Error()); // Clean up CryptCATAdminReleaseContext(phCatAdmin, 0); Marshal.FreeHGlobal(fileHash); return(WinVerifyTrustResult.FileNotSigned); } } } // Close the file so we don't get a sharing violation later hFile.Close(); IntPtr hCatInfo = IntPtr.Zero; hCatInfo = CryptCATAdminEnumCatalogFromHash(phCatAdmin, fileHash, fileHashLength, 0, ref hCatInfo); bool found = false; while (hCatInfo != IntPtr.Zero) { IntPtr ci = Marshal.AllocHGlobal((int)Marshal.SizeOf(typeof(CatalogInfo))); if (CryptCATCatalogInfoFromContext(hCatInfo, ci, 0)) { CatalogInfo catInfo = (CatalogInfo)Marshal.PtrToStructure(ci, typeof(CatalogInfo)); string catalogFileName = catInfo.wszCatalogFile; Database.LogCatalogFile(catalogFileName); // Get the hash as a string var fileHashByteArray = new byte[fileHashLength]; System.Runtime.InteropServices.Marshal.Copy(fileHash, fileHashByteArray, 0, (int)fileHashLength); string fileHashTag = ByteArrayToString(fileHashByteArray); // // Use WinVerifyTrust to get the rest of the info // result = VerifyCatalogFile(FileName, catalogFileName, fileHashTag, out Signers, phCatAdmin); found = true; break; } else { Log.Error("Call to CryptCATCatalogInfoFromContext failed with error {0}", Marshal.GetLastWin32Error()); } // Try the next catalog and loop again hCatInfo = CryptCATAdminEnumCatalogFromHash(phCatAdmin, fileHash, fileHashLength, 0, ref hCatInfo); } if (!found) { //Log.Info("Hash not found in any catalogs"); } // Clean up // TODO Need to ensure these are always called CryptCATAdminReleaseCatalogContext(phCatAdmin, hCatInfo, 0); CryptCATAdminReleaseContext(phCatAdmin, 0); //hFile.Close(); Marshal.FreeHGlobal(fileHash); return(result); }
public static string IsFileSignedInfo(string fileName) { WinVerifyTrustResult result = VerifyEmbeddedSignature(fileName); return(result == WinVerifyTrustResult.NO_ERROR ? Html.Yes : Html.cNo + " " + result.ToString()); }
public static string VerifyEmbeddedSignature(string filename) { try { WinTrustFileInfo winTrustFileInfo = null; WinTrustData winTrustData = null; // specify the WinVerifyTrust function/action that we want Guid action = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2); // instantiate our WinTrustFileInfo and WinTrustData data structures winTrustFileInfo = new WinTrustFileInfo(filename); winTrustData = new WinTrustData(filename); WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, action, winTrustData); // call into WinVerifyTrust switch (result) { case WinVerifyTrustResult.Success: return("Valid"); case WinVerifyTrustResult.ProviderUnknown: return("ProviderUnknown"); case WinVerifyTrustResult.ActionUnknown: return("ActionUnknown"); case WinVerifyTrustResult.SubjectFormUnknown: return("SubjectFormUnknown"); case WinVerifyTrustResult.SubjectNotTrusted: return("SubjectNotTrusted"); case WinVerifyTrustResult.FileNotSigned: return("FileNotSigned"); case WinVerifyTrustResult.SubjectExplicitlyDistrusted: return("SubjectExplicitlyDistrusted"); case WinVerifyTrustResult.SignatureOrFileCorrupt: return("SignatureOrFileCorrupt"); case WinVerifyTrustResult.SubjectCertExpired: return("SubjectCertExpired"); case WinVerifyTrustResult.SubjectCertificateRevoked: return("SubjectCertificateRevoked"); case WinVerifyTrustResult.UntrustedRoot: return("UntrustedRoot"); default: // The UI was disabled in dwUIChoice or the admin policy // has disabled user trust. lStatus contains the // publisher or time stamp chain error. return(result.ToString()); } } catch (Exception e) when( e is System.AccessViolationException || e is Exception) { Dictionary <string, string> ExceptionEvent = new Dictionary <string, string>(); ExceptionEvent.Add("Exception Type", e.GetType().ToString()); AsaTelemetry.TrackEvent("VerifyEmbeddedSignatureException", ExceptionEvent); return("FailedToFetch"); } }
private static string ConvertWinVerifyTrustResultToHex(WinVerifyTrustResult result) { return("0x" + result.ToString("X")); }