diff --git a/PInvoke/Cryptography/Crypt32/Wincrypt.cs b/PInvoke/Cryptography/Crypt32/Wincrypt.cs index cf4db8dc..6d40b264 100644 --- a/PInvoke/Cryptography/Crypt32/Wincrypt.cs +++ b/PInvoke/Cryptography/Crypt32/Wincrypt.cs @@ -1276,6 +1276,145 @@ namespace Vanara.PInvoke public IntPtr rgRDNAttr; } + /// + /// Contains parameters used to check for strong signatures on certificates, certificate revocation lists (CRLs), online certificate + /// status protocol (OCSP) responses, and PKCS #7 messages. + /// + /// + /// The parameters needed to check for a strong signature include the following: + /// + /// + /// Name of the public (asymmetric) algorithm + /// + /// + /// Size, in bits, of the public key + /// + /// + /// Name of the signature algorithm + /// + /// + /// Name of the hashing algorithm + /// + /// + /// + /// The value you specify for the dwInfoChoice member of this structure chooses whether the parameters are transmitted as + /// serialized strings or are predefined by using an object identifier. + /// + /// The CERT_STRONG_SIGN_PARA structure is directly referenced by the following functions: + /// + /// + /// CertIsStrongHashToSign + /// + /// + /// CryptMsgControl + /// + /// + /// CryptMsgVerifyCountersignatureEncodedEx + /// + /// + /// + /// The CERT_STRONG_SIGN_PARA structure is also directly referenced by the CRYPT_VERIFY_MESSAGE_PARA structure and is + /// therefore available for use by the following functions: + /// + /// + /// + /// CryptDecodeMessage + /// + /// + /// CryptDecryptAndVerifyMessageSignature + /// + /// + /// CryptVerifyDetachedMessageSignature + /// + /// + /// CryptVerifyMessageSignature + /// + /// + /// + /// Finally, the CERT_STRONG_SIGN_PARA structure is directly referenced by the CERT_CHAIN_PARA structure and is therefore + /// available for use by the following functions: + /// + /// + /// + /// CertGetCertificateChain + /// + /// + /// CertSelectCertificateChains + /// + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_strong_sign_para typedef struct + // _CERT_STRONG_SIGN_PARA { DWORD cbSize; DWORD dwInfoChoice; union { void *pvInfo; PCERT_STRONG_SIGN_SERIALIZED_INFO + // pSerializedInfo; LPSTR pszOID; } DUMMYUNIONNAME; } CERT_STRONG_SIGN_PARA, *PCERT_STRONG_SIGN_PARA; + [PInvokeData("wincrypt.h", MSDNShortId = "12D9F82C-F484-43B0-BD55-F07321058671")] + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct CERT_STRONG_SIGN_PARA + { + /// Size, in bytes, of this structure. + [FieldOffset(0)] + public uint cbSize; + + /// + /// Indicates which nested union member points to the strong signature information. This can be one of the following values: + /// + /// + /// Value + /// Description + /// + /// + /// CERT_STRONG_SIGN_SERIALIZED_INFO_CHOICE + /// Specifies the pSerializedInfo member. + /// + /// + /// CERT_STRONG_SIGN_OID_INFO_CHOICE + /// Specifies the pszOID member. + /// + /// + /// + [FieldOffset(4)] + public uint dwInfoChoice; + + /// Reserved. + [FieldOffset(8)] + public IntPtr pvInfo; + + /// Pointer to a CERT_STRONG_SIGN_SERIALIZED_INFO structure that specifies the parameters. + [FieldOffset(8)] + public IntPtr pSerializedInfo; + + /// + /// + /// Pointer to a string that contains an object identifier (OID) that represents predefined parameters that can be used for + /// strong signature checking. This can be one of the following values: + /// + /// + /// + /// Value + /// Meaning + /// + /// + /// szOID_CERT_STRONG_SIGN_OS_1 "1.3.6.1.4.1.311.72.1.1" + /// + /// The SHA2 hash algorithm is supported. MD2, MD4, MD5, and SSHA1 are not supported. The signing and public key algorithms can + /// be RSA or ECDSA. The DSA algorithm is not supported. The key size for the RSA algorithm must equal or be greater than 2047 + /// bits. The key size for the ECDSA algorithm must equal or be greater than 256 bits. Strong signing of CRLs and OCSP responses + /// are enabled. + /// + /// + /// + /// szOID_CERT_STRONG_KEY_OS_1 "1.3.6.1.4.1.311.72.2.1" + /// + /// SHA1 and SHA2 hashes are supported. MD2, MD4, and MD5 are not. The signing and public key algorithms can be RSA or ECDSA. + /// The DSA algorithm is not supported. The key size for the RSA algorithm must equal or be greater than 2047 bits. The key size + /// for the ECDSA algorithm must equal or be greater than 256 bits. Strong signing of CRLs and OCSP responses are enabled. + /// + /// + /// + /// + [FieldOffset(8)] + public StrPtrAnsi pszOID; + } + /// /// The CERT_SYSTEM_STORE_INFO structure contains information used by functions that work with system stores. Currently, no /// essential information is contained in this structure. diff --git a/PInvoke/WinTrust/MsCat.cs b/PInvoke/WinTrust/MsCat.cs index 7382edd6..5dea6ee3 100644 --- a/PInvoke/WinTrust/MsCat.cs +++ b/PInvoke/WinTrust/MsCat.cs @@ -1,23 +1,1014 @@ using System; using System.Runtime.InteropServices; -using Vanara.Extensions; -using Vanara.InteropServices; using static Vanara.PInvoke.Crypt32; -using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { public static partial class WinTrust { + /// + /// The PFN_CDF_PARSE_ERROR_CALLBACK function is called for Catalog Definition Function errors while parsing a catalog + /// definition file (CDF). + /// + /// A value that indicates in which area of the CDF the error occurred. + /// A value that indicates the type of error. + /// + /// This callback function does not return a value. + /// + /// The dwErrorArea parameter can have the following possible values. + /// + /// + /// Value + /// Description + /// + /// + /// CRYPTCAT_E_AREA_HEADER + /// The header section of the CDF + /// + /// + /// CRYPTCAT_E_AREA_MEMBER + /// A member file entry in the CatalogFiles section of the CDF + /// + /// + /// CRYPTCAT_E_AREA_ATTRIBUTE + /// An attribute entry in the CDF + /// + /// + /// The dwLocalError parameter can have the following possible values. + /// + /// + /// Value + /// Description + /// + /// + /// CRYPTCAT_E_CDF_UNSUPPORTED + /// The function does not support the attribute. + /// + /// + /// CRYPTCAT_E_CDF_DUPLICATE + /// The file member already exists. + /// + /// + /// CRYPTCAT_E_CDF_TAGNOTFOUND + /// The CatalogHeader or Name tag is missing. + /// + /// + /// CRYPTCAT_E_CDF_MEMBER_FILE_PATH + /// The member file name or path is missing. + /// + /// + /// CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA + /// The function failed to create a hash of the member subject. + /// + /// + /// CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND + /// The function failed to find the member file. + /// + /// + /// CRYPTCAT_E_CDF_BAD_GUID_CONV + /// The function failed to convert the subject string to a GUID. + /// + /// + /// CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES + /// + /// The attribute line is missing one or more elements of its composition including type, object identifier (OID) or name, or value. + /// + /// + /// + /// CRYPTCAT_E_CDF_ATTR_TYPECOMBO + /// The attribute contains an invalid OID, or the combination of type, name or OID, and value is not valid. + /// + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nc-mscat-pfn_cdf_parse_error_callback PFN_CDF_PARSE_ERROR_CALLBACK + // PfnCdfParseErrorCallback; void PfnCdfParseErrorCallback( IN DWORD dwErrorArea, IN DWORD dwLocalError, IN WCHAR *pwszLine ) {...} + [PInvokeData("mscat.h", MSDNShortId = "94c12ad7-dcb0-4099-8eba-da38367f0d79")] + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + public delegate void PfnCdfParseErrorCallback(CRYPTCAT_E dwErrorArea, CRYPTCAT_E dwLocalError, [In, MarshalAs(UnmanagedType.LPWStr)] string pwszLine); + + /// CRYPTCATATTRIBUTE attributes and actions. + [PInvokeData("mscat.h", MSDNShortId = "41b91303-f3eb-4288-9ad2-98f170680988")] + [Flags] + public enum CRYPTCAT_ATTR : uint + { + /// The attribute is authenticated. + CRYPTCAT_ATTR_AUTHENTICATED = 0x10000000, + + /// The attribute is unauthenticated. + CRYPTCAT_ATTR_UNAUTHENTICATED = 0x20000000, + + /// The attribute is an ASCII string. + CRYPTCAT_ATTR_NAMEASCII = 0x00000001, + + /// The attribute is a cryptographic object identifier (OID). + CRYPTCAT_ATTR_NAMEOBJID = 0x00000002, + + /// The attribute contains simple ASCII characters that should not be decoded. + CRYPTCAT_ATTR_DATAASCII = 0x00010000, + + /// The attribute is in base 64 format. + CRYPTCAT_ATTR_DATABASE64 = 0x00020000, + + /// The attribute replaces the value for an existing attribute. + CRYPTCAT_ATTR_DATAREPLACE = 0x00040000, + } + + /// Errors used by . + [PInvokeData("mscat.h", MSDNShortId = "94c12ad7-dcb0-4099-8eba-da38367f0d79")] + public enum CRYPTCAT_E + { + /// The header section of the CDF + CRYPTCAT_E_AREA_HEADER = 0x00000000, + + /// A member file entry in the CatalogFiles section of the CDF + CRYPTCAT_E_AREA_MEMBER = 0x00010000, + + /// An attribute entry in the CDF + CRYPTCAT_E_AREA_ATTRIBUTE = 0x00020000, + + /// The function does not support the attribute. + CRYPTCAT_E_CDF_UNSUPPORTED = 0x00000001, + + /// The file member already exists. + CRYPTCAT_E_CDF_DUPLICATE = 0x00000002, + + /// The CatalogHeader or Name tag is missing. + CRYPTCAT_E_CDF_TAGNOTFOUND = 0x00000004, + + /// The member file name or path is missing. + CRYPTCAT_E_CDF_MEMBER_FILE_PATH = 0x00010001, + + /// The function failed to create a hash of the member subject. + CRYPTCAT_E_CDF_MEMBER_INDIRECTDATA = 0x00010002, + + /// The function failed to find the member file. + CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND = 0x00010004, + + /// The function failed to convert the subject string to a GUID. + CRYPTCAT_E_CDF_BAD_GUID_CONV = 0x00020001, + + /// + /// The attribute line is missing one or more elements of its composition including type, object identifier (OID) or name, or value. + /// + CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES = 0x00020002, + + /// The attribute contains an invalid OID, or the combination of type, name or OID, and value is not valid. + CRYPTCAT_E_CDF_ATTR_TYPECOMBO = 0x00020004, + } + + /// Flags used by CRYPTCATSTORE. + [PInvokeData("mscat.h", MSDNShortId = "65a15797-453c-4f47-8ea1-c92e616b50aa")] + [Flags] + public enum CRYPTCAT_OPEN : uint + { + /// Exclude page hashes in SPC_INDIRECT_DATA. + CRYPTCAT_OPEN_EXCLUDE_PAGE_HASHES = 0x00010000, + + /// For all flags with a value in the upper word, set or clear the flag. + CRYPTCAT_OPEN_FLAGS_MASK = 0xffff0000, + + /// + /// Include page hashes in SPC_INDIRECT_DATA. The CRYPTCAT_OPEN_EXCLUDE_PAGE_HASHES flag takes precedence if it is also set. + /// + CRYPTCAT_OPEN_INCLUDE_PAGE_HASHES = 0x00020000, + + /// Open the file for decoding without detached content. + CRYPTCAT_OPEN_NO_CONTENT_HCRYPTMSG = 0x20000000, + + /// Open the catalog with the entries sorted alphabetically by subject. + CRYPTCAT_OPEN_SORTED = 0x40000000, + + /// Verify the signature hash but not the certificate chain. + CRYPTCAT_OPEN_VERIFYSIGHASH = 0x10000000, + } + + /// + /// + /// [The CryptCATAdminAcquireContext function is available for use in the operating systems specified in the Requirements + /// section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminAcquireContext function acquires a handle to a catalog administrator context. This handle can be used by + /// subsequent calls to the CryptCATAdminAddCatalog, CryptCATAdminEnumCatalogFromHash, and CryptCATAdminRemoveCatalog functions. + /// This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// + /// A pointer to the catalog administrator context handle that is assigned by this function. When you have finished using the + /// handle, close it by calling the CryptCATAdminReleaseContext function. + /// + /// + /// A pointer to the GUID that identifies the subsystem. DRIVER_ACTION_VERIFY represents the subsystem for operating system + /// components and third party drivers. This is the subsystem used by most implementations. + /// + /// Not used; set to zero. + /// + /// The return value is TRUE if the function succeeds; FALSE if the function fails. + /// + /// For extended error information, call the GetLastError function. For a complete list of error codes provided by the operating + /// system, see System Error Codes. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminacquirecontext BOOL CryptCATAdminAcquireContext( + // HCATADMIN *phCatAdmin, const GUID *pgSubsystem, DWORD dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "693af055-fa93-4526-aa9c-3a659f8ff78f")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminAcquireContext(out SafeHCATADMIN phCatAdmin, in Guid pgSubsystem, uint dwFlags = 0); + + /// + /// + /// The CryptCATAdminAcquireContext2 function acquires a handle to a catalog administrator context for a given hash algorithm + /// and hash policy. + /// + /// You can use this handle in subsequent calls to the following functions: + /// + /// + /// CryptCATAdminAddCatalog + /// + /// + /// CryptCATAdminEnumCatalogFromHash + /// + /// + /// CryptCATAdminRemoveCatalog + /// + /// + /// + /// This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// + /// A pointer to the catalog administrator context handle that is assigned by this function. When you have finished using the + /// handle, close it by calling the CryptCATAdminReleaseContext function. + /// + /// + /// A pointer to the GUID that identifies the subsystem. DRIVER_ACTION_VERIFY represents the subsystem for operating system + /// components and third party drivers. This is the subsystem used by most implementations. + /// + /// + /// Optional null-terminated Unicode string that specifies the name of the hash algorithm to use when calculating and verifying + /// hashes. This value can be NULL. If it is NULL, the default hashing algorithm may be chosen, depending on the value + /// you set for the pStrongHashPolicy parameter. The default algorithm in Windows 8 is SHA1. The default may change in future + /// Windows versions. For more information, see Remarks. + /// + /// + /// Pointer to a CERT_STRONG_SIGN_PARA structure that contains the parameters used to check for strong signatures. The function + /// chooses the lowest common hashing algorithm that satisfies the specified policy and the algorithm specified by the + /// pwszHashAlgorithm parameter or the system default algorithm (if no algorithm is specified). + /// + /// Reserved. This value must be zero. + /// + /// If the function succeeds, the return value is nonzero ( TRUE). + /// If the function fails, the return value is zero ( FALSE). For extended error information, call GetLastError. + /// The following table lists the error codes most commonly returned by the GetLastError function. + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// The phCatAdmin parameter cannot be NULL. The dwFlags parameter must be zero (0). + /// + /// + /// ERROR_NOT_ENOUGH_MEMORY + /// There was insufficient memory to create a new catalog administrator object. + /// + /// + /// NTE_BAD_ALGID + /// The hash algorithm specified by the pwszHashAlgorithm parameter cannot be found. + /// + /// + /// + /// + /// This function enables you to choose, or chooses for you, the hash algorithm to be used in functions that require the catalog + /// administrator context. Although you can set the name of the hashing algorithm, we recommend that you let the function determine + /// the algorithm. Doing so protects your application from hard coding algorithms that may become untrusted in the future. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminacquirecontext2 BOOL CryptCATAdminAcquireContext2( + // HCATADMIN *phCatAdmin, const GUID *pgSubsystem, PCWSTR pwszHashAlgorithm, PCCERT_STRONG_SIGN_PARA pStrongHashPolicy, DWORD + // dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "B089217A-5C12-4C51-8E46-3A9243347B21")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminAcquireContext2(out SafeHCATADMIN phCatAdmin, in Guid pgSubsystem, [MarshalAs(UnmanagedType.LPWStr), Optional] string pwszHashAlgorithm, in CERT_STRONG_SIGN_PARA pStrongHashPolicy, uint dwFlags = 0); + + /// + /// + /// The CryptCATAdminAcquireContext2 function acquires a handle to a catalog administrator context for a given hash algorithm + /// and hash policy. + /// + /// You can use this handle in subsequent calls to the following functions: + /// + /// + /// CryptCATAdminAddCatalog + /// + /// + /// CryptCATAdminEnumCatalogFromHash + /// + /// + /// CryptCATAdminRemoveCatalog + /// + /// + /// + /// This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// + /// A pointer to the catalog administrator context handle that is assigned by this function. When you have finished using the + /// handle, close it by calling the CryptCATAdminReleaseContext function. + /// + /// + /// A pointer to the GUID that identifies the subsystem. DRIVER_ACTION_VERIFY represents the subsystem for operating system + /// components and third party drivers. This is the subsystem used by most implementations. + /// + /// + /// Optional null-terminated Unicode string that specifies the name of the hash algorithm to use when calculating and verifying + /// hashes. This value can be NULL. If it is NULL, the default hashing algorithm may be chosen, depending on the value + /// you set for the pStrongHashPolicy parameter. The default algorithm in Windows 8 is SHA1. The default may change in future + /// Windows versions. For more information, see Remarks. + /// + /// + /// Pointer to a CERT_STRONG_SIGN_PARA structure that contains the parameters used to check for strong signatures. The function + /// chooses the lowest common hashing algorithm that satisfies the specified policy and the algorithm specified by the + /// pwszHashAlgorithm parameter or the system default algorithm (if no algorithm is specified). + /// + /// Reserved. This value must be zero. + /// + /// If the function succeeds, the return value is nonzero ( TRUE). + /// If the function fails, the return value is zero ( FALSE). For extended error information, call GetLastError. + /// The following table lists the error codes most commonly returned by the GetLastError function. + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// The phCatAdmin parameter cannot be NULL. The dwFlags parameter must be zero (0). + /// + /// + /// ERROR_NOT_ENOUGH_MEMORY + /// There was insufficient memory to create a new catalog administrator object. + /// + /// + /// NTE_BAD_ALGID + /// The hash algorithm specified by the pwszHashAlgorithm parameter cannot be found. + /// + /// + /// + /// + /// This function enables you to choose, or chooses for you, the hash algorithm to be used in functions that require the catalog + /// administrator context. Although you can set the name of the hashing algorithm, we recommend that you let the function determine + /// the algorithm. Doing so protects your application from hard coding algorithms that may become untrusted in the future. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminacquirecontext2 BOOL CryptCATAdminAcquireContext2( + // HCATADMIN *phCatAdmin, const GUID *pgSubsystem, PCWSTR pwszHashAlgorithm, PCCERT_STRONG_SIGN_PARA pStrongHashPolicy, DWORD + // dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "B089217A-5C12-4C51-8E46-3A9243347B21")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminAcquireContext2(out SafeHCATADMIN phCatAdmin, [Optional] IntPtr pgSubsystem, [MarshalAs(UnmanagedType.LPWStr), Optional] string pwszHashAlgorithm, [Optional] IntPtr pStrongHashPolicy, uint dwFlags = 0); + + /// + /// + /// [The CryptCATAdminAddCatalog function is available for use in the operating systems specified in the Requirements + /// section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminAddCatalog function adds a catalog to the catalog database. The catalog database is an index that + /// associates file hashes with the catalogs that contain them. It is used to speed the identification of the catalogs when + /// verifying the file signature. This function is the only supported way to programmatically add catalogs to the Windows catalog + /// database. The function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to + /// dynamically link to Wintrust.dll. + /// + /// + /// Handle previously assigned by the CryptCATAdminAcquireContext function. + /// + /// A pointer to a null-terminated string for the fully qualified path of the catalog to be added. + /// + /// + /// A pointer to a null-terminated string for the name of the catalog when it is stored. If the parameter is NULL, + /// then a unique name will be generated for the catalog. + /// + /// + /// If the CRYPTCAT_ADDCATALOG_HARDLINK (0x00000001) flag is specified, the catalog specified in the call will be hard-linked to + /// rather than copied. Hard-linking instead of copying a catalog reduces the amount of disk space required by Windows. + /// + /// + /// + /// If the function succeeds, the return value is a handle to the catalog information context. If the function fails, the return + /// value is NULL. After you have finished using the returned handle, free it by calling the + /// CryptCATAdminReleaseCatalogContext function. + /// + /// + /// For extended error information, call the GetLastError function. For a complete list of error codes provided by the operating + /// system, see System Error Codes. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminaddcatalog HCATINFO CryptCATAdminAddCatalog( + // HCATADMIN hCatAdmin, PWSTR pwszCatalogFile, PWSTR pwszSelectBaseName, DWORD dwFlags ); + [PInvokeData("mscat.h", MSDNShortId = "a227597c-a0af-4b86-bd29-03f478aef244")] + public static SafeHCATINFO CryptCATAdminAddCatalog(SafeHCATADMIN hCatAdmin, [MarshalAs(UnmanagedType.LPWStr)] string pwszCatalogFile, [MarshalAs(UnmanagedType.LPWStr), Optional] string pwszSelectBaseName, uint dwFlags) => + new SafeHCATINFO(InternalCryptCATAdminAddCatalog(hCatAdmin, pwszCatalogFile, pwszSelectBaseName, dwFlags), hCatAdmin, true); + + /// + /// + /// [The CryptCATAdminCalcHashFromFileHandle function is available for use in the operating systems specified in the + /// Requirements section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminCalcHashFromFileHandle function calculates the hash for a file. This function has no associated import + /// library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// + /// A handle to the file whose hash is being calculated. This parameter cannot be NULL and must be a valid file handle. + /// + /// + /// A pointer to a DWORD variable that contains the number of bytes in pbHash. Upon input, set pcbHash to the number of bytes + /// allocated for pbHash. Upon return, pcbHash contains the number of returned bytes in pbHash. If pbHash is passed as NULL, + /// then pcbHash contains the number of bytes to allocate for pbHash. + /// + /// + /// A pointer to a BYTE buffer that receives the hash. If this parameter is passed in as NULL, then pcbHash contains + /// the number of bytes to allocate for pbHash, and a subsequent call can be made to retrieve the hash. + /// + /// This parameter is reserved for future use and must be set to zero. + /// + /// The return value is TRUE if the function succeeds; FALSE if the function fails. If FALSE is returned, call + /// the GetLastError function to determine the reason for failure. If not enough memory has been allocated for pbHash, the + /// CryptCATAdminCalcHashFromFileHandle function will set the last error to ERROR_INSUFFICIENT_BUFFER. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadmincalchashfromfilehandle BOOL + // CryptCATAdminCalcHashFromFileHandle( HANDLE hFile, DWORD *pcbHash, BYTE *pbHash, DWORD dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "4dc5688f-4b7a-4baf-9671-868cac7f1896")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminCalcHashFromFileHandle(HFILE hFile, ref uint pcbHash, IntPtr pbHash, uint dwFlags = 0); + + /// + /// The CryptCATAdminCalcHashFromFileHandle2 function calculates the hash for a file by using the specified algorithm. + /// + /// This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// Handle of an open catalog administrator context. For more information, see CryptCATAdminAcquireContext2. + /// + /// A handle to the file whose hash is being calculated. This parameter cannot be NULL and must be a valid file handle. + /// + /// + /// Pointer to a DWORD variable that contains the number of bytes in the pbHash parameter. Upon input, set pcbHash to the + /// number of bytes allocated for pbHash. Upon return, pcbHash contains the number of returned bytes in pbHash. If pbHash is set to + /// NULL, then pcbHash contains the number of bytes to allocate for pbHash. + /// + /// + /// Pointer to a BYTE buffer that receives the hash. If you set this parameter to NULL, then pcbHash will contain the + /// number of bytes to allocate for pbHash, and a subsequent call can be made to retrieve the hash. + /// + /// Reserved. This value must be zero. + /// + /// If the function succeeds, the return value is nonzero ( TRUE). + /// If the function fails, the return value is zero ( FALSE). For extended error information, call GetLastError. + /// The following table lists the error codes most commonly returned by the GetLastError function. + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// + /// The hFile parameter must not be NULL. The hFile parameter must be a valid file handle. The pcbHash parameter must not be NULL. + /// The dwFlags parameter must be zero (0). + /// + /// + /// + /// ERROR_INSUFFICIENT_BUFFER + /// + /// The buffer pointed to by the pbHash parameter was not NULL but was not large enough to be written. The correct size of the + /// required buffer is contained in the value pointed to by the pcbHash parameter. + /// + /// + /// + /// NTE_BAD_ALGID + /// The hash algorithm specified by the pwszHashAlgorithm parameter cannot be found. + /// + /// + /// + /// + /// The amount of time this function takes to execute depends on the length of the file being hashed, the algorithm being used, and + /// the file location. For example, it takes several seconds to calculate the hash of a local file that is very large (a few hundred megabytes). + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadmincalchashfromfilehandle2 BOOL + // CryptCATAdminCalcHashFromFileHandle2( HCATADMIN hCatAdmin, HANDLE hFile, DWORD *pcbHash, BYTE *pbHash, DWORD dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "CBFA60A8-5E5A-4FAD-8AD3-26539802CD53")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminCalcHashFromFileHandle2(HCATADMIN hCatAdmin, HFILE hFile, ref uint pcbHash, IntPtr pbHash, uint dwFlags = 0); + + /// + /// + /// [The CryptCATAdminEnumCatalogFromHash function is available for use in the operating systems specified in the + /// Requirements section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminEnumCatalogFromHash function enumerates the catalogs that contain a specified hash. The hash is + /// typically returned from the CryptCATAdminCalcHashFromFileHandle function. This function has no associated import library. You + /// must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. After the final call to this + /// function, call CryptCATAdminReleaseCatalogContext to release allocated memory. + /// + /// + /// + /// A handle to a catalog administrator context previously assigned by the CryptCATAdminAcquireContext function. + /// + /// A pointer to the buffer that contains the hash retrieved by calling CryptCATAdminCalcHashFromFileHandle. + /// Number of bytes in the buffer allocated for pbHash. + /// This parameter is reserved for future use and must be set to zero. + /// + /// A pointer to the handle to the previous catalog context or NULL, if an enumeration is re-queried. If NULL is + /// passed in for this parameter, then the caller gets information only for the first catalog that contains the hash; an enumeration + /// is not made. If phPrevCatInfo contains NULL, then an enumeration of the catalogs that contain the hash is started, and + /// subsequent calls to CryptCATAdminEnumCatalogFromHash must set phPrevCatInfo to the return value from the previous call. + /// + /// + /// The return value is a handle to the catalog context or NULL, if there are no more catalogs to enumerate or retrieve. + /// + /// For extended error information, call the GetLastError function. For a complete list of error codes provided by the operating + /// system, see System Error Codes. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminenumcatalogfromhash HCATINFO + // CryptCATAdminEnumCatalogFromHash( HCATADMIN hCatAdmin, BYTE *pbHash, DWORD cbHash, DWORD dwFlags, HCATINFO *phPrevCatInfo ); + [PInvokeData("mscat.h", MSDNShortId = "33ab2d01-94ab-4d23-a054-9da0731485d6")] + public static SafeHCATINFO CryptCATAdminEnumCatalogFromHash(SafeHCATADMIN hCatAdmin, IntPtr pbHash, uint cbHash, [Optional] uint dwFlags, ref HCATINFO phPrevCatInfo) => + new SafeHCATINFO(InternalCryptCATAdminEnumCatalogFromHash(hCatAdmin, pbHash, cbHash, dwFlags, ref phPrevCatInfo), hCatAdmin, true); + + /// + /// + /// [The CryptCATAdminReleaseCatalogContext function is available for use in the operating systems specified in the + /// Requirements section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminReleaseCatalogContext function releases a handle to a catalog context previously returned by the + /// CryptCATAdminAddCatalog function. This function has no associated import library. You must use the LoadLibrary and + /// GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// Handle previously assigned by the CryptCATAdminAcquireContext function. + /// + /// Handle previously assigned by the CryptCATAdminAddCatalog function or the CryptCATAdminEnumCatalogFromHash function. + /// + /// This parameter is reserved for future use and must be set to zero. + /// The return value is TRUE if the function succeeds; FALSE if the function fails. + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminreleasecatalogcontext BOOL + // CryptCATAdminReleaseCatalogContext( IN HCATADMIN hCatAdmin, IN HCATINFO hCatInfo, IN DWORD dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "6cc13013-2c0a-4934-a866-30b69cbcf934")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminReleaseCatalogContext(HCATADMIN hCatAdmin, HCATINFO hCatInfo, uint dwFlags = 0); + + /// + /// + /// [The CryptCATAdminReleaseContext function is available for use in the operating systems specified in the Requirements + /// section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The CryptCATAdminReleaseContext function releases the handle previously assigned by the CryptCATAdminAcquireContext + /// function. This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to + /// dynamically link to Wintrust.dll. + /// + /// + /// + /// Catalog administrator context handle previously assigned by a call to the CryptCATAdminAcquireContext function. + /// + /// Not used; set to zero. + /// The return value is TRUE if the function succeeds; FALSE if the function fails. + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-cryptcatadminreleasecontext BOOL CryptCATAdminReleaseContext( + // IN HCATADMIN hCatAdmin, IN DWORD dwFlags ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "dff253dc-c444-46be-a383-41340d634cce")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptCATAdminReleaseContext([In] HCATADMIN hCatAdmin, [In] uint dwFlags = 0); + + /// + /// + /// [The IsCatalogFile function is available for use in the operating systems specified in the Requirements section. It may + /// be altered or unavailable in subsequent versions.] + /// + /// The IsCatalogFile function retrieves a Boolean value that indicates whether the specified file is a catalog file. + /// + /// Note This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to + /// dynamically link to Wintrust.dll. + /// + /// + /// + /// A handle to the file to check. This parameter is optional, but it must contain a valid handle if the pwszFileName parameter is NULL. + /// + /// + /// A pointer to a null-terminated wide character string that contains the name of the file to check. This parameter is optional, + /// but it must contain a valid file name if the hFile parameter is NULL. + /// + /// Returns nonzero if the specified file is a catalog file or zero otherwise. + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/nf-mscat-iscatalogfile BOOL IsCatalogFile( IN HANDLE hFile, WCHAR + // *pwszFileName ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("mscat.h", MSDNShortId = "eeba34d4-08aa-456a-8fdc-16795cbce36a")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool IsCatalogFile([In] HFILE hFile, [MarshalAs(UnmanagedType.LPWStr)] string pwszFileName); + + [DllImport(Lib.Wintrust, SetLastError = true, EntryPoint = "CryptCATAdminAddCatalog")] + private static extern IntPtr InternalCryptCATAdminAddCatalog(HCATADMIN hCatAdmin, [MarshalAs(UnmanagedType.LPWStr)] string pwszCatalogFile, [MarshalAs(UnmanagedType.LPWStr), Optional] string pwszSelectBaseName, uint dwFlags); + + [DllImport(Lib.Wintrust, SetLastError = true, EntryPoint = "CryptCATAdminEnumCatalogFromHash")] + private static extern IntPtr InternalCryptCATAdminEnumCatalogFromHash(HCATADMIN hCatAdmin, IntPtr pbHash, uint cbHash, [Optional] uint dwFlags, ref HCATINFO phPrevCatInfo); + + /// + /// + /// [The CATALOG_INFO structure is available for use in the operating systems specified in the Requirements section. It may + /// be altered or unavailable in subsequent versions.] + /// + /// + /// The CATALOG_INFO structure contains the name of a catalog file. This structure is used by the + /// CryptCATCatalogInfoFromContext function. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/ns-mscat-catalog_info typedef struct CATALOG_INFO_ { DWORD cbStruct; + // WCHAR wszCatalogFile[MAX_PATH]; } CATALOG_INFO; + [PInvokeData("mscat.h", MSDNShortId = "f6e66412-3ed2-48d9-a377-5df11500db59")] + [StructLayout(LayoutKind.Sequential)] + public struct CATALOG_INFO + { + /// Specifies the size, in bytes, of this structure. + public uint cbStruct; + + /// Name of the catalog file. + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public string wszCatalogFile; + } + + /// + /// + /// [The CRYPTCATATTRIBUTE structure is available for use in the operating systems specified in the Requirements section. It + /// may be altered or unavailable in subsequent versions.] + /// + /// + /// The CRYPTCATATTRIBUTE structure defines a catalog attribute. This structure is used by the CryptCATEnumerateAttr and + /// CryptCATEnumerateCatAttr functions. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/ns-mscat-cryptcatattribute typedef struct CRYPTCATATTRIBUTE_ { DWORD + // cbStruct; LPWSTR pwszReferenceTag; DWORD dwAttrTypeAndAction; DWORD cbValue; BYTE *pbValue; DWORD dwReserved; } CRYPTCATATTRIBUTE; + [PInvokeData("mscat.h", MSDNShortId = "41b91303-f3eb-4288-9ad2-98f170680988")] + [StructLayout(LayoutKind.Sequential)] + public struct CRYPTCATATTRIBUTE + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A pointer to a null-terminated string that contains the reference tag value. + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + + /// + /// Bitwise combination of the following flags. + /// + /// + /// Value + /// Meaning + /// + /// + /// CRYPTCAT_ATTR_AUTHENTICATED 0x10000000 + /// The attribute is authenticated. + /// + /// + /// CRYPTCAT_ATTR_UNAUTHENTICATED 0x20000000 + /// The attribute is unauthenticated. + /// + /// + /// CRYPTCAT_ATTR_NAMEASCII 0x00000001 + /// The attribute is an ASCII string. + /// + /// + /// CRYPTCAT_ATTR_NAMEOBJID 0x00000002 + /// The attribute is a cryptographic object identifier (OID). + /// + /// + /// CRYPTCAT_ATTR_DATAASCII 0x00010000 + /// The attribute contains simple ASCII characters that should not be decoded. + /// + /// + /// CRYPTCAT_ATTR_DATABASE64 0x00020000 + /// The attribute is in base 64 format. + /// + /// + /// CRYPTCAT_ATTR_DATAREPLACE 0x00040000 + /// The attribute replaces the value for an existing attribute. + /// + /// + /// + public CRYPTCAT_ATTR dwAttrTypeAndAction; + + /// Number of bytes used by pbValue. + public uint cbValue; + + /// A pointer to the encoded bytes. + public IntPtr pbValue; + + /// Reserved; do not use. + public uint dwReserved; + } + + /// + /// + /// [The CRYPTCATCDF structure is available for use in the operating systems specified in the Requirements section. It may be + /// altered or unavailable in subsequent versions.] + /// + /// + /// The CRYPTCATCDF structure contains information used to create a signed catalog file (.cat) from a catalog definition file + /// (CDF). This structure is used by the MakeCat tool. + /// + /// + /// + /// A parser can update dwCurFilePos and dwLastMemberOffset as it reads the CDF. A user-defined callback function can use this + /// information for recoverable parse errors in the CDF. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/ns-mscat-cryptcatcdf typedef struct CRYPTCATCDF_ { DWORD cbStruct; + // HANDLE hFile; DWORD dwCurFilePos; DWORD dwLastMemberOffset; BOOL fEOF; LPWSTR pwszResultDir; HANDLE hCATStore; } CRYPTCATCDF; + [PInvokeData("mscat.h", MSDNShortId = "15d5710a-d4df-4e45-b161-5d4f7509ba29")] + [StructLayout(LayoutKind.Sequential)] + public struct CRYPTCATCDF + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A handle to the catalog definition file (.cdf). + public HFILE hFile; + + /// + /// A value that specifies the current position of the parser measured in bytes from the beginning of the catalog definition file. + /// + public uint dwCurFilePos; + + /// + /// A value that specifies the number of bytes to the position of the last member parsed in the catalog definition file. + /// + public uint dwLastMemberOffset; + + /// + /// An integer that indicates whether the parser finished reading the file. TRUE indicates that the last read operation + /// returned zero bytes. + /// + [MarshalAs(UnmanagedType.Bool)] public bool fEOF; + + /// + /// A pointer to a null-terminated string that contains the name of a directory where the catalog file (.cat) will be written. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszResultDir; + + /// A handle to the catalog file (.cat). + public HANDLE hCATStore; + } + + /// + /// + /// [The CRYPTCATMEMBER structure is available for use in the operating systems specified in the Requirements section. It may + /// be altered or unavailable in subsequent versions.] + /// + /// + /// The CRYPTCATMEMBER structure provides information about a catalog member. This structure is used by the + /// CryptCATGetMemberInfo and CryptCATEnumerateAttr functions. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/ns-mscat-cryptcatmember typedef struct CRYPTCATMEMBER_ { DWORD cbStruct; + // LPWSTR pwszReferenceTag; LPWSTR pwszFileName; GUID gSubjectType; DWORD fdwMemberFlags; struct SIP_INDIRECT_DATA_ *pIndirectData; + // DWORD dwCertVersion; DWORD dwReserved; HANDLE hReserved; CRYPT_ATTR_BLOB sEncodedIndirectData; CRYPT_ATTR_BLOB + // sEncodedMemberInfo; } CRYPTCATMEMBER; + [PInvokeData("mscat.h", MSDNShortId = "08f663d9-9dc2-4ac9-95c5-7f2ed972eb9b")] + [StructLayout(LayoutKind.Sequential)] + public struct CRYPTCATMEMBER + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A pointer to a null-terminated string that contains the reference tag value. + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + + /// A pointer to a null-terminated string that contains the file name. + [MarshalAs(UnmanagedType.LPWStr)] public string pwszFileName; + + /// GUID that identifies the subject type. + public Guid gSubjectType; + + /// Value that specifies the member flags. + public uint fdwMemberFlags; + + /// A pointer to a SIP_INDIRECT_DATA structure. + public IntPtr pIndirectData; + + /// Value that specifies the certificate version. + public uint dwCertVersion; + + /// Reserved; do not use. + public uint dwReserved; + + /// Reserved; do not use. + public HANDLE hReserved; + + /// A CRYPT_ATTR_BLOB structure that contains encoded indirect data. + public CRYPTOAPI_BLOB sEncodedIndirectData; + + /// A CRYPT_ATTR_BLOB structure that contains encoded member information. + public CRYPTOAPI_BLOB sEncodedMemberInfo; + } + + /// + /// + /// [The CRYPTCATSTORE structure is available for use in the operating systems specified in the Requirements section. It may + /// be altered or unavailable in subsequent versions.] + /// + /// + /// The CRYPTCATSTORE structure represents a catalog file. The CryptCATStoreFromHandle function populates this structure by + /// using the handle returned by CryptCATOpen. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mscat/ns-mscat-cryptcatstore typedef struct CRYPTCATSTORE_ { DWORD cbStruct; + // DWORD dwPublicVersion; LPWSTR pwszP7File; HCRYPTPROV hProv; DWORD dwEncodingType; DWORD fdwStoreFlags; HANDLE hReserved; HANDLE + // hAttrs; HCRYPTMSG hCryptMsg; HANDLE hSorted; } CRYPTCATSTORE; + [PInvokeData("mscat.h", MSDNShortId = "65a15797-453c-4f47-8ea1-c92e616b50aa")] + [StructLayout(LayoutKind.Sequential)] + public struct CRYPTCATSTORE + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A value that specifies the "PublicVersion" of the catalog file. + public uint dwPublicVersion; + + /// + /// A pointer to a null-terminated string that contains the name of the catalog file. This member must be initialized before a + /// call to the CryptCATPersistStore function. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszP7File; + + /// A handle to the cryptographic service provider (CSP). + public HCRYPTPROV hProv; + + /// + /// A value that specifies the encoding type used for the file. Currently, only X509_ASN_ENCODING and PKCS_7_ASN_ENCODING are + /// being used; however, additional encoding types may be added in the future. For either current encoding type, use: + /// X509_ASN_ENCODING | PKCS_7_ASN_ENCODING. + /// + public CertEncodingType dwEncodingType; + + /// + /// A bitwise combination of the following values. + /// + /// + /// Value + /// Meaning + /// + /// + /// CRYPTCAT_OPEN_EXCLUDE_PAGE_HASHES 0x00010000 + /// Exclude page hashes in SPC_INDIRECT_DATA. + /// + /// + /// CRYPTCAT_OPEN_FLAGS_MASK 0xffff0000 + /// For all flags with a value in the upper word, set or clear the flag. + /// + /// + /// CRYPTCAT_OPEN_INCLUDE_PAGE_HASHES 0x00020000 + /// + /// Include page hashes in SPC_INDIRECT_DATA. The CRYPTCAT_OPEN_EXCLUDE_PAGE_HASHES flag takes precedence if it is also set. + /// + /// + /// + /// CRYPTCAT_OPEN_NO_CONTENT_HCRYPTMSG 0x20000000 + /// Open the file for decoding without detached content. + /// + /// + /// CRYPTCAT_OPEN_SORTED 0x40000000 + /// Open the catalog with the entries sorted alphabetically by subject. + /// + /// + /// CRYPTCAT_OPEN_VERIFYSIGHASH 0x10000000 + /// Verify the signature hash but not the certificate chain. + /// + /// + /// + public CRYPTCAT_OPEN fdwStoreFlags; + + /// This member is reserved and must be NULL. + public HANDLE hReserved; + + /// This member is reserved and must be NULL. + public HANDLE hAttrs; + + /// + /// A handle to the decoded bytes. This member is only set if the file was opened with the + /// CRYPTCAT_OPEN_NO_CONTENT_HCRYPTMSG flag set. + /// + public HCRYPTMSG hCryptMsg; + + /// This member is reserved and must be NULL. + public HANDLE hSorted; + } + + /// Provides a handle to a catalog information context. + [StructLayout(LayoutKind.Sequential)] + public struct HCATINFO : IHandle + { + private readonly IntPtr handle; + + /// Initializes a new instance of the struct. + /// An object that represents the pre-existing handle to use. + public HCATINFO(IntPtr preexistingHandle) => handle = preexistingHandle; + + /// Returns an invalid handle by instantiating a object with . + public static HCATINFO NULL => new HCATINFO(IntPtr.Zero); + + /// Gets a value indicating whether this instance is a null handle. + public bool IsNull => handle == IntPtr.Zero; + + /// Performs an explicit conversion from to . + /// The handle. + /// The result of the conversion. + public static explicit operator IntPtr(HCATINFO h) => h.handle; + + /// Performs an implicit conversion from to . + /// The pointer to a handle. + /// The result of the conversion. + public static implicit operator HCATINFO(IntPtr h) => new HCATINFO(h); + + /// Implements the operator !=. + /// The first handle. + /// The second handle. + /// The result of the operator. + public static bool operator !=(HCATINFO h1, HCATINFO h2) => !(h1 == h2); + + /// Implements the operator ==. + /// The first handle. + /// The second handle. + /// The result of the operator. + public static bool operator ==(HCATINFO h1, HCATINFO h2) => h1.Equals(h2); + + /// + public override bool Equals(object obj) => obj is HCATINFO h ? handle == h.handle : false; + + /// + public override int GetHashCode() => handle.GetHashCode(); + + /// + public IntPtr DangerousGetHandle() => handle; + } + + /// Provides a for that is disposed using . + public class SafeHCATADMIN : SafeHANDLE + { + /// Initializes a new instance of the class and assigns an existing handle. + /// An object that represents the pre-existing handle to use. + /// + /// to reliably release the handle during the finalization phase; otherwise, (not recommended). + /// + public SafeHCATADMIN(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } + + /// Initializes a new instance of the class. + private SafeHCATADMIN() : base() { } + + /// Performs an implicit conversion from to . + /// The safe handle instance. + /// The result of the conversion. + public static implicit operator HCATADMIN(SafeHCATADMIN h) => h.handle; + + /// + protected override bool InternalReleaseHandle() => CryptCATAdminReleaseContext(handle); + } + + /// Provides a for that is disposed using . + public class SafeHCATINFO : SafeHANDLE + { + private readonly SafeHCATADMIN hAdmin; + + /// Initializes a new instance of the class and assigns an existing handle. + /// An object that represents the pre-existing handle to use. + /// + /// to reliably release the handle during the finalization phase; otherwise, (not recommended). + /// + public SafeHCATINFO(IntPtr preexistingHandle, SafeHCATADMIN hCatAdmin, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) => + hAdmin = hCatAdmin ?? throw new ArgumentNullException(nameof(hCatAdmin)); + + /// Initializes a new instance of the class. + private SafeHCATINFO() : base() { } + + /// Performs an implicit conversion from to . + /// The safe handle instance. + /// The result of the conversion. + public static implicit operator HCATINFO(SafeHCATINFO h) => h.handle; + + /// + protected override bool InternalReleaseHandle() => CryptCATAdminReleaseCatalogContext(hAdmin, handle); + } + /* - CryptCATAdminAcquireContext Acquires a handle to a catalog administrator context. - CryptCATAdminAcquireContext2 Acquires a handle to a catalog administrator context for a given hash algorithm and hash policy. - CryptCATAdminAddCatalog Adds a catalog to the catalog database. - CryptCATAdminCalcHashFromFileHandle Calculates the hash for a file. - CryptCATAdminCalcHashFromFileHandle2 Calculates the hash for a file by using the specified algorithm. - CryptCATAdminEnumCatalogFromHash Enumerates the catalogs that contain a specified hash. - CryptCATAdminReleaseCatalogContext Releases a handle to a catalog context previously returned by the CryptCATAdminAddCatalog function. - CryptCATAdminReleaseContext Releases the handle previously assigned by the CryptCATAdminAcquireContext function. CryptCATAdminRemoveCatalog Deletes a catalog file and removes that catalog's entry from the Windows catalog database. CryptCATAdminResolveCatalogPath Retrieves the fully qualified path of the specified catalog. CryptCATCatalogInfoFromContext Retrieves catalog information from a specified catalog context. @@ -37,15 +1028,6 @@ namespace Vanara.PInvoke CryptCATPutCatAttrInfo Allocates memory for a catalog file attribute and adds it to the catalog. CryptCATPutMemberInfo Allocates memory for a catalog member and adds it to the catalog. CryptCATStoreFromHandle Retrieves a CRYPTCATSTORE structure from a catalog handle. - IsCatalogFile Retrieves a Boolean value that indicates whether the specified file is a catalog file. - - PFN_CDF_PARSE_ERROR_CALLBACK Called for Catalog Definition Function errors while parsing a catalog definition file (CDF). - - CATALOG_INFO The CATALOG_INFO structure contains the name of a catalog file. This structure is used by the CryptCATCatalogInfoFromContext function. - CRYPTCATATTRIBUTE The CRYPTCATATTRIBUTE structure defines a catalog attribute. This structure is used by the CryptCATEnumerateAttr and CryptCATEnumerateCatAttr functions. - CRYPTCATCDF Contains information used to create a signed catalog file (.cat) from a catalog definition file (CDF). - CRYPTCATMEMBER The CRYPTCATMEMBER structure provides information about a catalog member. This structure is used by the CryptCATGetMemberInfo and CryptCATEnumerateAttr functions. - CRYPTCATSTORE Represents a catalog file. */ } } \ No newline at end of file diff --git a/PInvoke/WinTrust/MsSip.cs b/PInvoke/WinTrust/MsSip.cs index 3a3f097f..dda8aa48 100644 --- a/PInvoke/WinTrust/MsSip.cs +++ b/PInvoke/WinTrust/MsSip.cs @@ -1,40 +1,1078 @@ using System; using System.Runtime.InteropServices; -using Vanara.Extensions; using Vanara.InteropServices; using static Vanara.PInvoke.Crypt32; -using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { public static partial class WinTrust { - /* - CryptSIPAddProvider The CryptSIPAddProvider function registers functions that are exported by a given DLL file that implements a Subject Interface Package (SIP). - CryptSIPCreateIndirectData Returns a SIP_INDIRECT_DATA structure that contains a hash of the supplied SIP_SUBJECTINFO structure, the digest algorithm, and an encoding attribute. The hash can be used as an indirect reference to the data. - CryptSIPGetCaps Retrieves the capabilities of a subject interface package (SIP). - CryptSIPGetSignedDataMsg Retrieves an Authenticode signature from the file. - CryptSIPLoad Loads the dynamic-link library (DLL) that implements a subject interface package (SIP) and assigns appropriate library export functions to a SIP_DISPATCH_INFO structure. - CryptSIPPutSignedDataMsg Stores an Authenticode signature in the target file. - CryptSIPRemoveProvider Removes registry details of a Subject Interface Package (SIP) DLL file added by a previous call to the CryptSIPAddProvider function. - CryptSIPRemoveSignedDataMsg Removes a specified Authenticode signature. - CryptSIPRetrieveSubjectGuid Retrieves a GUID based on the header information in a specified file. - CryptSIPRetrieveSubjectGuidForCatalogFile Retrieves the subject GUID associated with the specified file. - CryptSIPVerifyIndirectData Validates the indirect hashed data against the supplied subject. + /// + /// The CryptSIPCreateIndirectData function returns a SIP_INDIRECT_DATA structure that contains a hash of the supplied + /// SIP_SUBJECTINFO structure, the digest algorithm, and an encoding attribute. The hash can be used as an indirect reference to the data. + /// + /// + /// A pointer to a SIP_SUBJECTINFO structure that contains the subject to which the indirect data reference will point. + /// + /// A pointer to a DWORD value to receive the size of the returned SIP_INDIRECT_DATA structure. + /// A pointer to a SIP_INDIRECT_DATA structure to receive the catalog item. + /// + /// The return value is TRUE if the function succeeds; otherwise, FALSE. + /// + /// If this function returns FALSE, additional error information can be obtained by calling the GetLastError function. + /// GetLastError will return one of the following error codes. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_BAD_FORMAT + /// The file or data format is not correct for the specified subject interface package (SIP) type. + /// + /// + /// ERROR_INVALID_PARAMETER + /// One or more of the parameters are not valid. + /// + /// + /// ERROR_NOT_ENOUGH_MEMORY + /// There was an error allocating memory. + /// + /// + /// NTE_BAD_ALGID + /// The specified algorithm is not supported by the SIP. + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The subject type is not recognized. + /// + /// + /// + /// + /// If pcbIndirectData points to a DWORD and pIndirectData points to NULL, the size of the data will be returned in pcbIndirectData. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipcreateindirectdata BOOL CryptSIPCreateIndirectData( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN OUT DWORD *pcbIndirectData, OUT SIP_INDIRECT_DATA *pIndirectData ); + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "bb4ecc95-972f-415c-9722-59b00a27cddc")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPCreateIndirectData(in SIP_SUBJECTINFO pSubjectInfo, ref uint pcbIndirectData, IntPtr pIndirectData); - pCryptSIPGetCaps Is implemented by an subject interface package (SIP) to report capabilities. - pfnIsFileSupported Queries the subject interface packages (SIPs) listed in the registry to determine which SIP handles the file type. - pfnIsFileSupportedName Queries the subject interface packages (SIPs) listed in the registry to determine which SIP handles the file type. + /// The pCryptSIPGetCaps function is implemented by an subject interface package (SIP) to report capabilities. + /// Pointer to a SIP_SUBJECTINFO structure that specifies subject information data to the SIP APIs. + /// Pointer to a SIP_CAP_SET structure that defines the capabilities of an SIP. + /// None + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nc-mssip-pcryptsipgetcaps pCryptSIPGetCaps Pcryptsipgetcaps; BOOL + // Pcryptsipgetcaps( SIP_SUBJECTINFO *pSubjInfo, SIP_CAP_SET *pCaps ) {...} + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "8EA46B67-F542-4B15-81F4-3DD83DD45764")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPGetCaps(in SIP_SUBJECTINFO pSubjInfo, IntPtr pCaps); - MS_ADDINFO_BLOB Provides additional information for in-memory BLOB subject types. - MS_ADDINFO_CATALOGMEMBER Provides additional information for catalog member subject types. - MS_ADDINFO_FLAT Provides additional information about flat or end-to-end subject types. - SIP_ADD_NEWPROVIDER Defines a subject interface package (SIP). This structure is used by the CryptSIPAddProvider function. - SIP_CAP_SET_V2 Defines the capabilities of a subject interface package (SIP). - SIP_CAP_SET_V3 Defines the capabilities of a subject interface package (SIP). - SIP_DISPATCH_INFO Contains a set of function pointers assigned by the CryptSIPLoad function that your application uses to perform subject interface package (SIP) operations. - SIP_INDIRECT_DATA Contains the digest of the hashed subject information. - SIP_SUBJECTINFO Specifies subject information data to the subject interface package (SIP) APIs. - */ + /// The CryptSIPGetSignedDataMsg function retrieves an Authenticode signature from the file. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// + /// The encoding type of the Authenticode signature. + /// This parameter can be a combination of one or more of the following values. + /// + /// + /// Value + /// Meaning + /// + /// + /// PKCS_7_ASN_ENCODING 65536 (0x10000) + /// Specifies PKCS #7 message encoding. + /// + /// + /// X509_ASN_ENCODING 1 (0x1) + /// Specifies X.509 certificate encoding. + /// + /// + /// + /// This parameter is reserved and should be set to zero. + /// The length, in bytes, of the buffer pointed to by the pbSignedDataMsg parameter. + /// + /// A pointer to a buffer to receive the returned Authenticode signature. + /// + /// To determine the size of the buffer needed, set the pbSignedDataMsg parameter to NULL and call the + /// CryptSIPGetSignedDataMsg function. This function will place the required size of the buffer, in bytes, in the value + /// pointed to by pcbSignedDataMsg. For more information, see Retrieving Data of Unknown Length. + /// + /// + /// + /// If the function succeeds, the function returns TRUE. + /// + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. Some possible error codes follow. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// CRYPT_E_NO_MATCH + /// The signature specified by the index could not be found. + /// + /// + /// ERROR_BAD_FORMAT + /// The specified data or file format of the subject interface package (SIP) is not valid. + /// + /// + /// ERROR_INVALID_PARAMETER + /// The pSubjectInfo parameter or the pgSubjectType member of the SIP_SUBJECTINFO structure is a null pointer. + /// + /// + /// ERROR_INSUFFICIENT_BUFFER + /// + /// The size of the message buffer was insufficient to hold the retrieved data, the pcbSignedDataMsgparameter has been set to + /// indicate the required buffer size. + /// + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The specified subject type is not valid. + /// + /// + /// + /// + /// Subjects include, but are not limited to, portable executable images (.exe), cabinet (.cab) images, flat files, and catalog + /// files. Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage + /// and retrieval. Therefore, each subject type has a unique SIP specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipgetsigneddatamsg BOOL CryptSIPGetSignedDataMsg( IN + // SIP_SUBJECTINFO *pSubjectInfo, OUT DWORD *pdwEncodingType, IN DWORD dwIndex, IN OUT DWORD *pcbSignedDataMsg, OUT BYTE + // *pbSignedDataMsg ); + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "e3fabaa7-2dda-4c6c-8d1a-3ee5363e10b5")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPGetSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, out CertEncodingType pdwEncodingType, uint dwIndex, ref uint pcbSignedDataMsg, [Out] IntPtr pbSignedDataMsg); + + /// The CryptSIPPutSignedDataMsg function stores an Authenticode signature in the target file. + /// Pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// + /// The encoding type of the message. This can be a combination of one or more of the following values. + /// + /// + /// Value + /// Meaning + /// + /// + /// PKCS_7_ASN_ENCODING 65536 (0x10000) + /// Specifies PKCS #7 message encoding. + /// + /// + /// X509_ASN_ENCODING 1 (0x1) + /// Specifies X.509 certificate encoding. + /// + /// + /// + /// Pointer to the message index. + /// Length, in bytes, of the buffer pointed to by the pbSignedDataMsg parameter. + /// Pointer to the buffer that contains the message. + /// + /// If the function succeeds, the function returns TRUE. + /// + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. Some possible error codes follow. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_BAD_FORMAT + /// The specified data or file format of the subject interface package (SIP) is not valid. + /// + /// + /// ERROR_INVALID_PARAMETER + /// This code can be returned for the following reasons: + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The specified subject type is not valid. + /// + /// + /// + /// + /// Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage and + /// retrieval. Therefore, each subject type has a unique SIP specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipputsigneddatamsg BOOL CryptSIPPutSignedDataMsg( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN DWORD dwEncodingType, OUT DWORD *pdwIndex, IN DWORD cbSignedDataMsg, IN BYTE *pbSignedDataMsg ); + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "731f64bf-49f0-4799-b84a-9ca04292aa91")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPPutSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, CertEncodingType dwEncodingType, out uint pdwIndex, uint cbSignedDataMsg, [In] IntPtr pbSignedDataMsg); + + /// The CryptSIPRemoveSignedDataMsg function removes a specified Authenticode signature. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// This parameter is reserved and should be set to zero. + /// + /// If the function succeeds, the function returns TRUE. + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipremovesigneddatamsg BOOL CryptSIPRemoveSignedDataMsg( + // IN SIP_SUBJECTINFO *pSubjectInfo, IN DWORD dwIndex ); + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "c3ea46bb-931a-4ca6-93f5-db7e07b4cb7a")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPRemoveSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, uint dwIndex = 0); + + /// The CryptSIPVerifyIndirectData function validates the indirect hashed data against the supplied subject. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// A pointer to a SIP_INDIRECT_DATA structure that contains information about the hashed subject information. + /// + /// The return value is TRUE if the function succeeds; otherwise, FALSE. + /// + /// If this function returns FALSE, additional error information can be obtained by calling the GetLastError function. + /// GetLastError will return one of the following error codes. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// One or more of the parameters are not valid. + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The subject type is an unknown type. + /// + /// + /// + /// + /// Subjects include, but are not limited to, portable executable images (.exe), cabinet (.cab) images, flat files, and catalog + /// files. Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage + /// and retrieval. Therefore each subject type has a unique subject interface package specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipverifyindirectdata BOOL CryptSIPVerifyIndirectData( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN SIP_INDIRECT_DATA *pIndirectData ); + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "137b8858-a31f-4ef6-96bd-c5e26ae7b3e8")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pCryptSIPVerifyIndirectData(in SIP_SUBJECTINFO pSubjectInfo, in SIP_INDIRECT_DATA pIndirectData); + + /// + /// The pfnIsFileSupported callback function queries the subject interface packages (SIPs) listed in the registry to + /// determine which SIP handles the file type. + /// + /// A handle to the file. + /// + /// + /// If the function succeeds, the function returns TRUE. + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. + /// + /// + /// + /// If the SIP supports the file type passed by hfile, the function returns TRUE, and sets pgSubject to the GUID that + /// identifies the SIP for handling the file type. + /// + /// + /// Each SIP implements its own version of the function that determines whether the file type is supported. The specific name of the + /// function may vary depending on the implementation of the SIP, but the signature of the function will match that of the + /// pfnIsFileSupported function. The function name is added to the registry by the CryptSIPAddProvider function, which takes + /// the function name as a parameter in the pwszIsFunctionName field of the SIP_ADD_NEWPROVIDER structure. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nc-mssip-pfnisfilesupported pfnIsFileSupported Pfnisfilesupported; BOOL + // Pfnisfilesupported( IN HANDLE hFile, OUT GUID *pgSubject ) {...} + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "cf12d057-328a-4975-b7e5-842c4ea2e760")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pfnIsFileSupported(HFILE hFile, out Guid pgSubject); + + /// + /// The pfnIsFileSupportedName callback function queries the subject interface packages (SIPs) listed in the registry to + /// determine which SIP handles the file type. + /// + /// + /// + /// + /// The return value is TRUE if the function succeeds; FALSE if the function fails. If the function fails, call the + /// GetLastError function to determine the reason for failure. + /// + /// + /// + /// If the SIP supports the file type passed by hfile, the function returns TRUE, and sets pgSubject to the GUID that + /// identifies the SIP for handling the file type. + /// + /// + /// Each SIP implements its own version of the function that determines if the file type is supported. The specific name of the + /// function may vary depending on the implementation of the SIP, but the signature of the function will match that of the + /// pfnIsFileSupportedName function. The function name is added to the registry by the CryptSIPAddProvider function, which + /// takes the function name as parameter in the pwszIsFunctionNameFmt2 field in the SIP_ADD_NEWPROVIDER structure. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nc-mssip-pfnisfilesupportedname pfnIsFileSupportedName + // Pfnisfilesupportedname; BOOL Pfnisfilesupportedname( IN WCHAR *pwszFileName, OUT GUID *pgSubject ) {...} + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + [PInvokeData("mssip.h", MSDNShortId = "cc2304ef-c319-45eb-b2ec-7410510af213")] + [return: MarshalAs(UnmanagedType.Bool)] + public delegate bool pfnIsFileSupportedName([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, out Guid pgSubject); + + /// + /// The CryptSIPAddProvider function registers functions that are exported by a given DLL file that implements a Subject + /// Interface Package (SIP). + /// + /// A pointer to a SIP_ADD_NEWPROVIDER structure that specifies the DLL file and function names to register. + /// + /// The return value is TRUE if the function succeeds; FALSE if the function fails. If the function fails, call the + /// GetLastError function to determine the reason for failure. + /// + /// + /// + /// Typically, you call this function as part of an in-process COM server registration. The CryptSIPAddProvider function + /// persists the appropriate Registry entries for the SIP provider functions. + /// + /// When you have finished using the added SIP provider, remove it by calling the CryptSIPRemoveProvider function. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipaddprovider BOOL CryptSIPAddProvider( IN + // SIP_ADD_NEWPROVIDER *psNewProv ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "99633c2f-e5ed-49e4-9c98-7501f66e5571")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPAddProvider([In] in SIP_ADD_NEWPROVIDER psNewProv); + + /// + /// The CryptSIPCreateIndirectData function returns a SIP_INDIRECT_DATA structure that contains a hash of the supplied + /// SIP_SUBJECTINFO structure, the digest algorithm, and an encoding attribute. The hash can be used as an indirect reference to the data. + /// + /// + /// A pointer to a SIP_SUBJECTINFO structure that contains the subject to which the indirect data reference will point. + /// + /// A pointer to a DWORD value to receive the size of the returned SIP_INDIRECT_DATA structure. + /// A pointer to a SIP_INDIRECT_DATA structure to receive the catalog item. + /// + /// The return value is TRUE if the function succeeds; otherwise, FALSE. + /// + /// If this function returns FALSE, additional error information can be obtained by calling the GetLastError function. + /// GetLastError will return one of the following error codes. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_BAD_FORMAT + /// The file or data format is not correct for the specified subject interface package (SIP) type. + /// + /// + /// ERROR_INVALID_PARAMETER + /// One or more of the parameters are not valid. + /// + /// + /// ERROR_NOT_ENOUGH_MEMORY + /// There was an error allocating memory. + /// + /// + /// NTE_BAD_ALGID + /// The specified algorithm is not supported by the SIP. + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The subject type is not recognized. + /// + /// + /// + /// + /// If pcbIndirectData points to a DWORD and pIndirectData points to NULL, the size of the data will be returned in pcbIndirectData. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipcreateindirectdata BOOL CryptSIPCreateIndirectData( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN OUT DWORD *pcbIndirectData, OUT SIP_INDIRECT_DATA *pIndirectData ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "bb4ecc95-972f-415c-9722-59b00a27cddc")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPCreateIndirectData(in SIP_SUBJECTINFO pSubjectInfo, ref uint pcbIndirectData, IntPtr pIndirectData); + + /// The CryptSIPGetCaps function retrieves the capabilities of a subject interface package (SIP). + /// Pointer to a SIP_SUBJECTINFO structure that specifies subject information data to the SIP APIs. + /// Pointer to a SIP_CAP_SET structure that defines the capabilities of an SIP. + /// None + /// + /// Unlike other SIP functions, CryptSIPGetCaps is not registered in the dispatch table. For more information, see the + /// SIP_DISPATCH_INFO structure. Instead, callers must map the object identifier (OID) to the function entry point. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipgetcaps BOOL CryptSIPGetCaps( SIP_SUBJECTINFO + // *pSubjInfo, SIP_CAP_SET *pCaps ); + [DllImport(Lib.Crypt32, SetLastError = false, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "F939F6D5-DDFE-478F-8FDD-8FA9FAB26010")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPGetCaps(in SIP_SUBJECTINFO pSubjInfo, ref SIP_CAP_SET_V2 pCaps); + + /// The CryptSIPGetCaps function retrieves the capabilities of a subject interface package (SIP). + /// Pointer to a SIP_SUBJECTINFO structure that specifies subject information data to the SIP APIs. + /// Pointer to a SIP_CAP_SET structure that defines the capabilities of an SIP. + /// None + /// + /// Unlike other SIP functions, CryptSIPGetCaps is not registered in the dispatch table. For more information, see the + /// SIP_DISPATCH_INFO structure. Instead, callers must map the object identifier (OID) to the function entry point. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipgetcaps BOOL CryptSIPGetCaps( SIP_SUBJECTINFO + // *pSubjInfo, SIP_CAP_SET *pCaps ); + [DllImport(Lib.Crypt32, SetLastError = false, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "F939F6D5-DDFE-478F-8FDD-8FA9FAB26010")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPGetCaps(in SIP_SUBJECTINFO pSubjInfo, ref SIP_CAP_SET_V3 pCaps); + + /// The CryptSIPGetSignedDataMsg function retrieves an Authenticode signature from the file. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// + /// The encoding type of the Authenticode signature. + /// This parameter can be a combination of one or more of the following values. + /// + /// + /// Value + /// Meaning + /// + /// + /// PKCS_7_ASN_ENCODING 65536 (0x10000) + /// Specifies PKCS #7 message encoding. + /// + /// + /// X509_ASN_ENCODING 1 (0x1) + /// Specifies X.509 certificate encoding. + /// + /// + /// + /// This parameter is reserved and should be set to zero. + /// The length, in bytes, of the buffer pointed to by the pbSignedDataMsg parameter. + /// + /// A pointer to a buffer to receive the returned Authenticode signature. + /// + /// To determine the size of the buffer needed, set the pbSignedDataMsg parameter to NULL and call the + /// CryptSIPGetSignedDataMsg function. This function will place the required size of the buffer, in bytes, in the value + /// pointed to by pcbSignedDataMsg. For more information, see Retrieving Data of Unknown Length. + /// + /// + /// + /// If the function succeeds, the function returns TRUE. + /// + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. Some possible error codes follow. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// CRYPT_E_NO_MATCH + /// The signature specified by the index could not be found. + /// + /// + /// ERROR_BAD_FORMAT + /// The specified data or file format of the subject interface package (SIP) is not valid. + /// + /// + /// ERROR_INVALID_PARAMETER + /// The pSubjectInfo parameter or the pgSubjectType member of the SIP_SUBJECTINFO structure is a null pointer. + /// + /// + /// ERROR_INSUFFICIENT_BUFFER + /// + /// The size of the message buffer was insufficient to hold the retrieved data, the pcbSignedDataMsgparameter has been set to + /// indicate the required buffer size. + /// + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The specified subject type is not valid. + /// + /// + /// + /// + /// Subjects include, but are not limited to, portable executable images (.exe), cabinet (.cab) images, flat files, and catalog + /// files. Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage + /// and retrieval. Therefore, each subject type has a unique SIP specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipgetsigneddatamsg BOOL CryptSIPGetSignedDataMsg( IN + // SIP_SUBJECTINFO *pSubjectInfo, OUT DWORD *pdwEncodingType, IN DWORD dwIndex, IN OUT DWORD *pcbSignedDataMsg, OUT BYTE + // *pbSignedDataMsg ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "e3fabaa7-2dda-4c6c-8d1a-3ee5363e10b5")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPGetSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, out CertEncodingType pdwEncodingType, uint dwIndex, ref uint pcbSignedDataMsg, [Out] IntPtr pbSignedDataMsg); + + /// + /// The CryptSIPLoad function loads the dynamic-link library (DLL) that implements a subject interface package (SIP) and + /// assigns appropriate library export functions to a SIP_DISPATCH_INFO structure. The exported functions must have been previously + /// registered by calling the CryptSIPAddProvider function. + /// + /// A pointer to a GUID returned by calling the CryptSIPRetrieveSubjectGuid function. + /// This parameter is reserved and must be set to zero. + /// + /// A pointer to a SIP_DISPATCH_INFO structure that contains pointers to SIP provider functions that are specific to the subject + /// type. The caller must initialize this structure to binary zeros, and set the cbSize member to before calling the + /// CryptSIPLoad function. + /// + /// + /// If the function succeeds, the function returns TRUE. + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipload BOOL CryptSIPLoad( IN const GUID *pgSubject, IN + // DWORD dwFlags, IN OUT SIP_DISPATCH_INFO *pSipDispatch ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "3378ecee-bd5d-45e5-9a1f-a3734d086782")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPLoad(in Guid pgSubject, [Optional] uint dwFlags, ref SIP_DISPATCH_INFO pSipDispatch); + + /// The CryptSIPPutSignedDataMsg function stores an Authenticode signature in the target file. + /// Pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// + /// The encoding type of the message. This can be a combination of one or more of the following values. + /// + /// + /// Value + /// Meaning + /// + /// + /// PKCS_7_ASN_ENCODING 65536 (0x10000) + /// Specifies PKCS #7 message encoding. + /// + /// + /// X509_ASN_ENCODING 1 (0x1) + /// Specifies X.509 certificate encoding. + /// + /// + /// + /// Pointer to the message index. + /// Length, in bytes, of the buffer pointed to by the pbSignedDataMsg parameter. + /// Pointer to the buffer that contains the message. + /// + /// If the function succeeds, the function returns TRUE. + /// + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. Some possible error codes follow. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_BAD_FORMAT + /// The specified data or file format of the subject interface package (SIP) is not valid. + /// + /// + /// ERROR_INVALID_PARAMETER + /// This code can be returned for the following reasons: + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The specified subject type is not valid. + /// + /// + /// + /// + /// Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage and + /// retrieval. Therefore, each subject type has a unique SIP specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipputsigneddatamsg BOOL CryptSIPPutSignedDataMsg( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN DWORD dwEncodingType, OUT DWORD *pdwIndex, IN DWORD cbSignedDataMsg, IN BYTE *pbSignedDataMsg ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "731f64bf-49f0-4799-b84a-9ca04292aa91")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPPutSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, CertEncodingType dwEncodingType, out uint pdwIndex, uint cbSignedDataMsg, [In] IntPtr pbSignedDataMsg); + + /// + /// The CryptSIPRemoveProvider function removes registry details of a Subject Interface Package (SIP) DLL file added by a + /// previous call to the CryptSIPAddProvider function. + /// + /// A pointer to the GUID that identifies the SIP DLL to remove. + /// + /// The return value is TRUE if the function succeeds; FALSE if the function fails. If the function fails, call the + /// GetLastError function to determine the reason for failure. + /// + /// + /// Typically you call this function to unregister an in-process COM server. The CryptSIPRemoveProvider function removes the + /// appropriate Registry entries for the SIP provider functions. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipremoveprovider BOOL CryptSIPRemoveProvider( IN GUID + // *pgProv ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "0a269956-b2c7-414a-b002-7cec0d52bfd6")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPRemoveProvider(in Guid pgProv); + + /// The CryptSIPRemoveSignedDataMsg function removes a specified Authenticode signature. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// This parameter is reserved and should be set to zero. + /// + /// If the function succeeds, the function returns TRUE. + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipremovesigneddatamsg BOOL CryptSIPRemoveSignedDataMsg( + // IN SIP_SUBJECTINFO *pSubjectInfo, IN DWORD dwIndex ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "c3ea46bb-931a-4ca6-93f5-db7e07b4cb7a")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPRemoveSignedDataMsg(in SIP_SUBJECTINFO pSubjectInfo, uint dwIndex = 0); + + /// + /// The CryptSIPRetrieveSubjectGuid function retrieves a GUID based on the header information in a specified file. The GUID + /// is used by the CryptSIPLoad function to load the subject interface package (SIP) implementation for the given file type. + /// + /// The name of the file. + /// A handle to the file to check. + /// A GUID that identifies the subject. + /// + /// If the function succeeds, the function returns TRUE. + /// If the function fails, it returns FALSE. For extended error information, call GetLastError. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipretrievesubjectguid BOOL CryptSIPRetrieveSubjectGuid( + // IN LPCWSTR FileName, IN HANDLE hFileIn, OUT GUID *pgSubject ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "b81472bc-6d9c-4634-a378-e39786a0ca09")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPRetrieveSubjectGuid([MarshalAs(UnmanagedType.LPWStr)] string FileName, HFILE hFileIn, out Guid pgSubject); + + /// + /// The CryptSIPRetrieveSubjectGuidForCatalogFile function retrieves the subject GUID associated with the specified file. + /// + /// The name of the file. If the hFileIn parameter is set, the value in this parameter is ignored. + /// + /// A handle to the file to check. This parameter must contain a valid handle if the FileName parameter is NULL. + /// + /// A globally unique ID that identifies the subject. + /// + /// The return value is TRUE if the function succeeds; otherwise, FALSE. + /// + /// If this function returns FALSE, additional error information can be obtained by calling the GetLastError function. + /// GetLastError will return one of the following error codes. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// One or more of the parameters are not valid. + /// + /// + /// + /// + /// This function only supports subject interface packages (SIPs) that are used for portable executable images (.exe), cabinet + /// (.cab) images, and flat files. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipretrievesubjectguidforcatalogfile BOOL + // CryptSIPRetrieveSubjectGuidForCatalogFile( IN LPCWSTR FileName, IN HANDLE hFileIn, OUT GUID *pgSubject ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "7f757dc8-948c-476e-aca3-a9051e962ed4")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPRetrieveSubjectGuidForCatalogFile([MarshalAs(UnmanagedType.LPWStr)] string FileName, HFILE hFileIn, out Guid pgSubject); + + /// The CryptSIPVerifyIndirectData function validates the indirect hashed data against the supplied subject. + /// A pointer to a SIP_SUBJECTINFO structure that contains information about the message subject. + /// A pointer to a SIP_INDIRECT_DATA structure that contains information about the hashed subject information. + /// + /// The return value is TRUE if the function succeeds; otherwise, FALSE. + /// + /// If this function returns FALSE, additional error information can be obtained by calling the GetLastError function. + /// GetLastError will return one of the following error codes. + /// + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_INVALID_PARAMETER + /// One or more of the parameters are not valid. + /// + /// + /// TRUST_E_SUBJECT_FORM_UNKNOWN + /// The subject type is an unknown type. + /// + /// + /// + /// + /// Subjects include, but are not limited to, portable executable images (.exe), cabinet (.cab) images, flat files, and catalog + /// files. Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage + /// and retrieval. Therefore each subject type has a unique subject interface package specification. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/nf-mssip-cryptsipverifyindirectdata BOOL CryptSIPVerifyIndirectData( IN + // SIP_SUBJECTINFO *pSubjectInfo, IN SIP_INDIRECT_DATA *pIndirectData ); + [DllImport(Lib.Crypt32, SetLastError = true, ExactSpelling = true)] + [PInvokeData("mssip.h", MSDNShortId = "137b8858-a31f-4ef6-96bd-c5e26ae7b3e8")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CryptSIPVerifyIndirectData(in SIP_SUBJECTINFO pSubjectInfo, in SIP_INDIRECT_DATA pIndirectData); + + /// The MS_ADDINFO_BLOB structure provides additional information for in-memory BLOB subject types. + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-ms_addinfo_blob typedef struct MS_ADDINFO_BLOB_ { DWORD + // cbStruct; DWORD cbMemObject; BYTE *pbMemObject; DWORD cbMemSignedMsg; BYTE *pbMemSignedMsg; } MS_ADDINFO_BLOB, *PMS_ADDINFO_BLOB; + [PInvokeData("mssip.h", MSDNShortId = "236c8778-0b80-4157-8a81-24712ebf9a77")] + [StructLayout(LayoutKind.Sequential)] + public struct MS_ADDINFO_BLOB + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// The size, in bytes, of the data in the pbMemObject member. + public uint cbMemObject; + + /// A pointer to the in-memory BLOB subject. + public IntPtr pbMemObject; + + /// The size, in bytes, of the data in the pbMemSignedMsg member. + public uint cbMemSignedMsg; + + /// A pointer to the signed message. + public IntPtr pbMemSignedMsg; + } + + /// The MS_ADDINFO_CATALOGMEMBER structure provides additional information for catalog member subject types. + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-ms_addinfo_catalogmember typedef struct + // MS_ADDINFO_CATALOGMEMBER_ { DWORD cbStruct; struct CRYPTCATSTORE_ *pStore; struct CRYPTCATMEMBER_ *pMember; } + // MS_ADDINFO_CATALOGMEMBER, *PMS_ADDINFO_CATALOGMEMBER; + [PInvokeData("mssip.h", MSDNShortId = "40a00c8a-95e4-406c-b04e-0d29beb70d67")] + [StructLayout(LayoutKind.Sequential)] + public struct MS_ADDINFO_CATALOGMEMBER + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A CRYPTCATSTORE structure that contains a catalog file store. + public IntPtr pStore; + + /// A CRYPTCATMEMBER structure that contains a catalog member. + public IntPtr pMember; + } + + /// The MS_ADDINFO_FLAT structure provides additional information about flat or end-to-end subject types. + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-ms_addinfo_flat typedef struct MS_ADDINFO_FLAT_ { DWORD + // cbStruct; struct SIP_INDIRECT_DATA_ *pIndirectData; } MS_ADDINFO_FLAT, *PMS_ADDINFO_FLAT; + [PInvokeData("mssip.h", MSDNShortId = "9f5bebd1-8eda-456d-9339-3334a19c0ea4")] + [StructLayout(LayoutKind.Sequential)] + public struct MS_ADDINFO_FLAT + { + /// The size, in bytes, of this structure. + public uint cbStruct; + + /// A SIP_INDIRECT_DATA structure that contains the hash of a flat file subject. + public IntPtr pIndirectData; + } + + /// + /// The SIP_ADD_NEWPROVIDER structure defines a subject interface package (SIP). This structure is used by the + /// CryptSIPAddProvider function. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_add_newprovider typedef struct SIP_ADD_NEWPROVIDER_ { DWORD + // cbStruct; GUID *pgSubject; WCHAR *pwszDLLFileName; WCHAR *pwszMagicNumber; WCHAR *pwszIsFunctionName; WCHAR *pwszGetFuncName; + // WCHAR *pwszPutFuncName; WCHAR *pwszCreateFuncName; WCHAR *pwszVerifyFuncName; WCHAR *pwszRemoveFuncName; WCHAR + // *pwszIsFunctionNameFmt2; PWSTR pwszGetCapFuncName; } SIP_ADD_NEWPROVIDER, *PSIP_ADD_NEWPROVIDER; + [PInvokeData("mssip.h", MSDNShortId = "5ca88c0c-a7c9-4517-a874-49d38c1bc7c3")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_ADD_NEWPROVIDER + { + /// The size, in bytes, of this structure. Set this value to . + public uint cbStruct; + + /// Pointer to the GUID that identifies the SIP. + public GuidPtr pgSubject; + + /// Pointer to a null-terminated string that contains the name of the DLL file. + [MarshalAs(UnmanagedType.LPWStr)] public string pwszDLLFileName; + + /// This member is not used. + [MarshalAs(UnmanagedType.LPWStr)] public string pwszMagicNumber; + + /// + /// Pointer to a null-terminated string that contains the name of the function that determines whether the file contents are + /// supported by this SIP. This member can be NULL. The signature for this function pointer is described in pfnIsFileSupported. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszIsFunctionName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that retrieves the signed data. The signature for + /// this function pointer is described in CryptSIPGetSignedDataMsg. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszGetFuncName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that stores the Authenticode signature in the + /// target file. The signature for this function pointer is described in CryptSIPPutSignedDataMsg. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszPutFuncName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that creates the hash. The signature for this + /// function pointer is described in CryptSIPCreateIndirectData. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszCreateFuncName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that verifies the hash. The signature for this + /// function pointer is described in CryptSIPVerifyIndirectData. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszVerifyFuncName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that removes the signed data. The signature for + /// this function pointer is described in CryptSIPRemoveSignedDataMsg. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszRemoveFuncName; + + /// + /// Pointer to a null-terminated string that contains the name of the function that determines whether the file name extension + /// is supported by this SIP. This member can be NULL. The signature for this function pointer is described in pfnIsFileSupportedName. + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszIsFunctionNameFmt2; + + /// + /// + /// Pointer to a null-terminated string that contains the name of the function that determines the capabilities of the SIP. If + /// this parameter is set to NULL, multiple signatures are not available for this SIP. The signature for this function + /// pointer is described in pCryptSIPGetCaps. + /// + /// + /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This + /// member is not available. + /// + /// + [MarshalAs(UnmanagedType.LPWStr)] public string pwszGetCapFuncName; + } + + /// The SIP_CAP_SET structure defines the capabilities of a subject interface package (SIP). + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_cap_set_v2 typedef struct _SIP_CAP_SET_V2 { DWORD cbSize; + // DWORD dwVersion; BOOL isMultiSign; DWORD dwReserved; } SIP_CAP_SET_V2, *PSIP_CAP_SET_V2; + [PInvokeData("mssip.h", MSDNShortId = "0B6D173B-0183-4A7C-BB92-2D451F746164")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_CAP_SET_V2 + { + /// Size, in bytes, of this structure. + public uint cbSize; + + /// The SIP version. By default, this value is two (2). + public uint dwVersion; + + /// + /// A value of one (1) indicates that the SIP supports multiple embedded signatures. Otherwise, set this value to zero (0). + /// + [MarshalAs(UnmanagedType.Bool)] public bool isMultiSign; + + /// Reserved for future use. Set this value to zero (0). + public uint dwReserved; + } + + /// The SIP_CAP_SET structure defines the capabilities of a subject interface package (SIP). + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_cap_set_v3 typedef struct _SIP_CAP_SET_V3 { DWORD cbSize; + // DWORD dwVersion; BOOL isMultiSign; union { DWORD dwFlags; DWORD dwReserved; }; } SIP_CAP_SET_V3, *PSIP_CAP_SET_V3; + [PInvokeData("mssip.h", MSDNShortId = "0B6D173B-0183-4A7C-BB92-2D451F746164")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_CAP_SET_V3 + { + /// Size, in bytes, of this structure. + public uint cbSize; + + /// The SIP version. By default, this value is two (2). + public uint dwVersion; + + /// + /// A value of one (1) indicates that the SIP supports multiple embedded signatures. Otherwise, set this value to zero (0). + /// + [MarshalAs(UnmanagedType.Bool)] public bool isMultiSign; + + /// + public uint dwFlags; + + /// Reserved for future use. Set this value to zero (0). + public uint dwReserved; + } + + /// + /// The SIP_DISPATCH_INFO structure contains a set of function pointers assigned by the CryptSIPLoad function that your + /// application uses to perform subject interface package (SIP) operations. + /// + /// + /// Your application must initialize this structure to binary zeros and set cbSize to by calling the memset function before + /// calling the CryptSIPLoad function. Your application can use the function pointers in the returned SIP_DISPATCH_INFO + /// structure to perform the necessary SIP operations. The function pointers can point to functions exported by third party SIPs. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_dispatch_info typedef struct SIP_DISPATCH_INFO_ { DWORD + // cbSize; HANDLE hSIP; pCryptSIPGetSignedDataMsg pfGet; pCryptSIPPutSignedDataMsg pfPut; pCryptSIPCreateIndirectData pfCreate; + // pCryptSIPVerifyIndirectData pfVerify; pCryptSIPRemoveSignedDataMsg pfRemove; } SIP_DISPATCH_INFO, *LPSIP_DISPATCH_INFO; + [PInvokeData("mssip.h", MSDNShortId = "d34b5081-0af8-4dcc-8133-a91d0603d419")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_DISPATCH_INFO + { + /// The size, in bytes, of this structure. + public uint cbSize; + + /// This member is reserved and must be set to NULL. + public HANDLE hSIP; + + /// + /// A pointer to the function that retrieves the signed data for the subject. The signature for this function pointer is + /// described in CryptSIPGetSignedDataMsg. + /// + public pCryptSIPGetSignedDataMsg pfGet; + + /// + /// A pointer to the function that stores the signed data for the subject. The signature for this function pointer is described + /// in CryptSIPPutSignedDataMsg. + /// + public pCryptSIPPutSignedDataMsg pfPut; + + /// + /// A pointer to the function that returns a SIP_INDIRECT_DATA structure that contains the subject data. This structure contains + /// the hash of the target. The signature for this function pointer is described in CryptSIPCreateIndirectData. + /// + public pCryptSIPCreateIndirectData pfCreate; + + /// + /// A pointer to the function that verifies the SIP_INDIRECT_DATA structure that contains the subject data. This structure + /// contains the hash of the target. The signature for this function pointer is described in CryptSIPVerifyIndirectData. + /// + public pCryptSIPVerifyIndirectData pfVerify; + + /// + /// A pointer to the function that removes the signed data for the subject. The signature for this function pointer is described + /// in CryptSIPRemoveSignedDataMsg. + /// + public pCryptSIPRemoveSignedDataMsg pfRemove; + } + + /// The SIP_INDIRECT_DATA structure contains the digest of the hashed subject information. + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_indirect_data typedef struct SIP_INDIRECT_DATA_ { + // CRYPT_ATTRIBUTE_TYPE_VALUE Data; CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; CRYPT_HASH_BLOB Digest; } SIP_INDIRECT_DATA, *PSIP_INDIRECT_DATA; + [PInvokeData("mssip.h", MSDNShortId = "d34b599b-fe49-47c4-bb52-73ee14d73253")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_INDIRECT_DATA + { + /// A CRYPT_ATTRIBUTE_TYPE_VALUE structure used to encode the attribute. + public CRYPT_ATTRIBUTE_TYPE_VALUE Data; + + /// A CRYPT_ALGORITHM_IDENTIFIER structure that contains the digest algorithm to use to create the hash. + public CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; + + /// + /// A CRYPT_HASH_BLOB structure that contains the hash of the subject. For information about CRYPT_HASH_BLOB, see CRYPT_INTEGER_BLOB. + /// + public CRYPTOAPI_BLOB Digest; + } + + /// The SIP_SUBJECTINFO structure specifies subject information data to the subject interface package (SIP) APIs. + /// + /// + /// Upon first use of the SIP_SUBJECTINFO structure, initialize the entire structure to binary zero. Do not initialize the + /// structure between SIP function calls. + /// + /// + /// Subjects include, but are not limited to, portable executable images (.exe), cabinet (.cab) images, flat files, and catalog + /// files. Each subject type uses a different subset of its data for hash calculation and requires a different procedure for storage + /// and retrieval. Therefore each subject type has a unique subject interface package specification. + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/api/mssip/ns-mssip-sip_subjectinfo typedef struct SIP_SUBJECTINFO_ { DWORD cbSize; + // GUID *pgSubjectType; HANDLE hFile; LPCWSTR pwsFileName; LPCWSTR pwsDisplayName; DWORD dwReserved1; DWORD dwIntVersion; HCRYPTPROV + // hProv; CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; DWORD dwFlags; DWORD dwEncodingType; DWORD dwReserved2; DWORD fdwCAPISettings; + // DWORD fdwSecuritySettings; DWORD dwIndex; DWORD dwUnionChoice; union { #if ... MS_ADDINFO_FLAT_ *psFlat; #else struct + // MS_ADDINFO_FLAT_ *psFlat; #endif #if ... MS_ADDINFO_CATALOGMEMBER_ *psCatMember; #else struct MS_ADDINFO_CATALOGMEMBER_ + // *psCatMember; #endif #if ... MS_ADDINFO_BLOB_ *psBlob; #else struct MS_ADDINFO_BLOB_ *psBlob; #endif }; LPVOID pClientData; } + // SIP_SUBJECTINFO, *LPSIP_SUBJECTINFO; + [PInvokeData("mssip.h", MSDNShortId = "6274cd08-d67f-410d-9303-3a42b7f1edc6")] + [StructLayout(LayoutKind.Sequential)] + public struct SIP_SUBJECTINFO + { + /// The size, in bytes, of this structure. + public uint cbSize; + + /// A pointer to a GUID structure that identifies the subject type. + public GuidPtr pgSubjectType; + + /// + /// A file handle that represents the subject. If the storage type of the subject is a file, set hFile to + /// INVALID_HANDLE_VALUE and set the pwsFileName parameter to the name of the file. + /// + public HFILE hFile; + + /// A pointer to a null-terminated Unicode string that contains the file name of the subject. + [MarshalAs(UnmanagedType.LPWStr)] public string pwsFileName; + + /// A pointer to a null-terminated Unicode string that contains the display name of the subject. + [MarshalAs(UnmanagedType.LPWStr)] public string pwsDisplayName; + + /// This member is reserved for future use. + public uint dwReserved1; + + /// + /// This member is reserved. Do not modify this member. It is used by the SIP to pass the internal version number between get + /// and verify functions. + /// + public uint dwIntVersion; + + /// An HCRYPTPROV handle to the cryptography provider. + public HCRYPTPROV hProv; + + /// + /// A CRYPT_ALGORITHM_IDENTIFIER structure that contains the identifier for the hash algorithm used to hash the file. + /// + public CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; + + /// + /// A value that modifies the behavior of the functions that use this structure. For more information about possible values for + /// this member, see the dwFlags parameter of SignerSignEx. + /// + public uint dwFlags; + + /// + /// A value that specifies the encoding type used for the file. Currently, only X509_ASN_ENCODING and + /// PKCS_7_ASN_ENCODING are being used; however, additional encoding types may be added in the future. For either current + /// encoding type, use: X509_ASN_ENCODING | PKCS_7_ASN_ENCODING. + /// + public CertEncodingType dwEncodingType; + + /// This member is reserved for future use. + public uint dwReserved2; + + /// This member is not used. + public uint fdwCAPISettings; + + /// This member is not used. + public uint fdwSecuritySettings; + + /// The message index of the last call to CryptSIPGetSignedDataMsg. operation. + public uint dwIndex; + + /// + /// Specifies the type of additional information provided. + /// + /// + /// Defined constant/value + /// Meaning + /// + /// + /// MSSIP_ADDINFO_NONE 0 + /// There is no additional information about the subject. + /// + /// + /// MSSIP_ADDINFO_FLAT 1 + /// The additional information is a flat file. + /// + /// + /// MSSIP_ADDINFO_CATMEMBER 2 + /// The additional information is a catalog member. + /// + /// + /// MSSIP_ADDINFO_BLOB 3 + /// The additional information is a BLOB. + /// + /// + /// MSSIP_ADDINFO_NONMSSIP 500 + /// The additional information is in a user defined format. + /// + /// + /// + public uint dwUnionChoice; + + /// A pointer to either a MS_ADDINFO_FLAT, MS_ADDINFO_CATALOGMEMBER, or MS_ADDINFO_BLOB structure. + public IntPtr pUnionData; + + /// A pointer to SIP-specific data. + public IntPtr pClientData; + } } } \ No newline at end of file diff --git a/PInvoke/WinTrust/WinTrust.cs b/PInvoke/WinTrust/WinTrust.cs index f4161f01..bdfa4760 100644 --- a/PInvoke/WinTrust/WinTrust.cs +++ b/PInvoke/WinTrust/WinTrust.cs @@ -9,6 +9,30 @@ namespace Vanara.PInvoke { public static partial class WinTrust { + /// Confidence values. + [PInvokeData("wintrust.h", MSDNShortId = "622e7a72-445a-4820-b236-1c90dad08351")] + [Flags] + public enum CertConfidence + { + /// The signature of the certificate is valid. + CERT_CONFIDENCE_SIG = 0x10000000, + + /// The time of the certificate issuer is valid. + CERT_CONFIDENCE_TIME = 0x01000000, + + /// The time of the certificate is valid. + CERT_CONFIDENCE_TIMENEST = 0x00100000, + + /// The authority ID extension is valid. + CERT_CONFIDENCE_AUTHIDEXT = 0x00010000, + + /// At a minimum, the signature of the certificate and authority ID extension are valid. + CERT_CONFIDENCE_HYGIENE = 0x00001000, + + /// A combination of all of the other confidence values. + CERT_CONFIDENCE_HIGHEST = 0x11111000, + } + /// Action to perform. [PInvokeData("wintrust.h", MSDNShortId = "B2ED5489-792F-4B00-A21E-EE1B1462D1C8")] public enum DWACTION @@ -83,9 +107,10 @@ namespace Vanara.PInvoke public enum WTD_REVOKE { /// - /// No additional revocation checking will be done when the WTD_REVOKE_NONE flag is used in conjunction with the HTTPSPROV_ACTION - /// value set in the pgActionID parameter of the WinVerifyTrust function. To ensure the WinVerifyTrust function does not attempt - /// any network retrieval when verifying code signatures, WTD_CACHE_ONLY_URL_RETRIEVAL must be set in the dwProvFlags parameter. + /// No additional revocation checking will be done when the WTD_REVOKE_NONE flag is used in conjunction with the + /// HTTPSPROV_ACTION value set in the pgActionID parameter of the WinVerifyTrust function. To ensure the WinVerifyTrust function + /// does not attempt any network retrieval when verifying code signatures, WTD_CACHE_ONLY_URL_RETRIEVAL must be set in the + /// dwProvFlags parameter. /// WTD_REVOKE_NONE = 0x00000000, @@ -134,8 +159,8 @@ namespace Vanara.PInvoke WTD_NO_IE4_CHAIN_FLAG = 0x00000002, /// - /// The default verification of the policy provider, such as code signing for Authenticode, is not performed, and the certificate - /// is assumed valid for all usages. + /// The default verification of the policy provider, such as code signing for Authenticode, is not performed, and the + /// certificate is assumed valid for all usages. /// WTD_NO_POLICY_USAGE_FLAG = 0x00000004, @@ -181,9 +206,9 @@ namespace Vanara.PInvoke WTD_DISABLE_MD2_MD4 = 0x00002000, /// - /// If this flag is specified it is assumed that the file being verified has been downloaded from the web and has the Mark of the - /// Web attribute. Policies that are meant to apply to Mark of the Web files will be enforced. Note This flag is supported - /// on Windows 8.1 and later operating systems or on systems that have installed KB2862966. + /// If this flag is specified it is assumed that the file being verified has been downloaded from the web and has the Mark of + /// the Web attribute. Policies that are meant to apply to Mark of the Web files will be enforced. Note This flag is + /// supported on Windows 8.1 and later operating systems or on systems that have installed KB2862966. /// WTD_MOTW = 0x00004000, @@ -209,8 +234,8 @@ namespace Vanara.PInvoke } /// - /// A DWORD value that specifies the user interface context for the WinVerifyTrust function. This causes the text in the Authenticode - /// dialog box to match the action taken on the file. + /// A DWORD value that specifies the user interface context for the WinVerifyTrust function. This causes the text in the + /// Authenticode dialog box to match the action taken on the file. /// [PInvokeData("wintrust.h", MSDNShortId = "8fb68f44-6f69-4eac-90de-02689e3e86cf")] public enum WTD_UICONTEXT @@ -298,8 +323,8 @@ namespace Vanara.PInvoke /// /// WT_TRUSTDBDIALOG_ONLY_PUB_TAB_FLAG 2 (0x2) /// - /// Only display the Trusted Publisher tab. By default, all of the user interface tabs are displayed and the Trusted Publisher tab is - /// initially selected. + /// Only display the Trusted Publisher tab. By default, all of the user interface tabs are displayed and the Trusted Publisher tab + /// is initially selected. /// /// /// @@ -705,8 +730,8 @@ namespace Vanara.PInvoke /// /// - /// The WinVerifyTrust function performs a trust verification action on a specified object. The function passes the inquiry to - /// a trust provider that supports the action identifier, if one exists. + /// The WinVerifyTrust function performs a trust verification action on a specified object. The function passes the inquiry + /// to a trust provider that supports the action identifier, if one exists. /// /// For certificate verification, use the CertGetCertificateChain and CertVerifyCertificateChainPolicy functions. /// @@ -732,8 +757,8 @@ namespace Vanara.PInvoke /// /// A valid window handle /// - /// A trust provider can treat any value other than INVALID_HANDLE_VALUE or zero as a valid window handle that it can use to interact - /// with the user. + /// A trust provider can treat any value other than INVALID_HANDLE_VALUE or zero as a valid window handle that it can use to + /// interact with the user. /// /// /// @@ -813,9 +838,9 @@ namespace Vanara.PInvoke /// from the trust provider. /// /// - /// For example, a trust provider might indicate that the subject is not trusted, or is trusted but with limitations or warnings. The - /// return value can be a trust-provider-specific value described in the documentation for an individual trust provider, or it can be - /// one of the following error codes. + /// For example, a trust provider might indicate that the subject is not trusted, or is trusted but with limitations or warnings. + /// The return value can be a trust-provider-specific value described in the documentation for an individual trust provider, or it + /// can be one of the following error codes. /// /// /// @@ -853,16 +878,16 @@ namespace Vanara.PInvoke /// /// /// For example, the Software Publisher Trust Provider can verify that an executable image file comes from a trusted software - /// publisher and that the file has not been modified since it was published. In this case, the pWinTrustData parameter specifies the - /// name of the file and the type of file, such as a Microsoft Portable Executable image file. + /// publisher and that the file has not been modified since it was published. In this case, the pWinTrustData parameter specifies + /// the name of the file and the type of file, such as a Microsoft Portable Executable image file. /// /// /// Each trust provider supports a specific set of actions that it can evaluate. Each action has a GUID that identifies it. A trust /// provider can support any number of action identifiers, but two trust providers cannot support the same action identifier. /// /// - /// For an example that demonstrates how to use this function to verify the signature of a portable executable (PE) file, see Example - /// C Program: Verifying the Signature of a PE File. + /// For an example that demonstrates how to use this function to verify the signature of a portable executable (PE) file, see + /// Example C Program: Verifying the Signature of a PE File. /// /// // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-winverifytrust LONG WinVerifyTrust( HWND hwnd, GUID @@ -874,8 +899,9 @@ namespace Vanara.PInvoke /// /// /// The WinVerifyTrustEx function performs a trust verification action on a specified object and takes a pointer to a - /// WINTRUST_DATA structure. The function passes the inquiry to a trust provider, if one exists, that supports the action identifier. - /// This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// WINTRUST_DATA structure. The function passes the inquiry to a trust provider, if one exists, that supports the action + /// identifier. This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to + /// dynamically link to Wintrust.dll. /// /// For certificate verification, use the CertGetCertificateChain and CertVerifyCertificateChainPolicy functions. /// @@ -901,8 +927,8 @@ namespace Vanara.PInvoke /// /// A valid window handle /// - /// A trust provider can treat any value other than INVALID_HANDLE_VALUE or zero as a valid window handle that it can use to interact - /// with the user. + /// A trust provider can treat any value other than INVALID_HANDLE_VALUE or zero as a valid window handle that it can use to + /// interact with the user. /// /// /// @@ -983,9 +1009,9 @@ namespace Vanara.PInvoke /// Otherwise, the function returns a status code from the trust provider. /// /// - /// For example, a trust provider might indicate that the subject is not trusted, or is trusted but with limitations or warnings. The - /// return value can be a trust provider–specific value described in the documentation for an individual trust provider, or it can be - /// one of the following error codes. + /// For example, a trust provider might indicate that the subject is not trusted, or is trusted but with limitations or warnings. + /// The return value can be a trust provider–specific value described in the documentation for an individual trust provider, or it + /// can be one of the following error codes. /// /// /// @@ -1026,9 +1052,9 @@ namespace Vanara.PInvoke /// and CertVerifyCertificateChainPolicy functions. For Microsoft Authenticode technology signature verification, use the .NET Framework.] /// /// - /// The WTHelperCertCheckValidSignature function checks whether a signature is valid. It can be used by trust providers to get - /// an initial assessment of the validity of a signature before calling the function pointed to by the pfnFinalPolicy member - /// of a CRYPT_PROVIDER_FUNCTIONS structure. + /// The WTHelperCertCheckValidSignature function checks whether a signature is valid. It can be used by trust providers to + /// get an initial assessment of the validity of a signature before calling the function pointed to by the pfnFinalPolicy + /// member of a CRYPT_PROVIDER_FUNCTIONS structure. /// /// /// A pointer to the CRYPT_PROVIDER_DATA structure that contains the signer and countersigner information. @@ -1044,6 +1070,87 @@ namespace Vanara.PInvoke [PInvokeData("wintrust.h", MSDNShortId = "d46eea18-03cb-4199-873e-0e9e13061598")] public static extern HRESULT WTHelperCertCheckValidSignature(in CRYPT_PROVIDER_DATA pProvData); + /// + /// + /// [The WTHelperCertFindIssuerCertificate function is available for use in the operating systems specified in the + /// Requirements section. It may be altered or unavailable in subsequent versions.] + /// + /// + /// The WTHelperCertFindIssuerCertificate function finds an issuer certificate from the specified certificate stores that + /// matches the specified subject certificate. + /// + /// + /// The subject certificate for which to find a matching issuer certificate. + /// The number of elements in the pahStores array. + /// An array of certificate stores in which to search. + /// The time of verification. + /// + /// A DWORD value that specifies the encoding types of the certificate to check. For information about possible encoding + /// types, see Certificate and Message Encoding Types. + /// + /// + /// This parameter can be a bitwise combination of zero or more of the following confidence values. + /// + /// + /// Value + /// Meaning + /// + /// + /// CERT_CONFIDENCE_SIG 0x10000000 + /// The signature of the certificate is valid. + /// + /// + /// CERT_CONFIDENCE_TIME 0x01000000 + /// The time of the certificate issuer is valid. + /// + /// + /// CERT_CONFIDENCE_TIMENEST 0x00100000 + /// The time of the certificate is valid. + /// + /// + /// CERT_CONFIDENCE_AUTHIDEXT 0x00010000 + /// The authority ID extension is valid. + /// + /// + /// CERT_CONFIDENCE_HYGIENE 0x00001000 + /// At a minimum, the signature of the certificate and authority ID extension are valid. + /// + /// + /// CERT_CONFIDENCE_HIGHEST 0x11111000 + /// A combination of all of the other confidence values. + /// + /// + /// + /// A pointer to a DWORD variable that contains the error value for this certificate, if applicable. + /// An issuer certificate that matches the subject certificate specified by the pChildContext parameter. + /// + /// To successfully find a matching issuer certificate, the following requirements must be met: + /// + /// + /// The signature of the subject certificate specified by the pChildContext parameter must be valid. + /// + /// + /// + /// The rgExtension member of the pCertInfo member of the pChildContext parameter must contain a + /// CERT_AUTHORITY_KEY_ID_INFO structure. The CertIssuer and CertSerialMember members of this structure much + /// match the corresponding members for the issuer certificate. + /// + /// + /// + /// The value of the psftVerifyAsOf parameter must be within the period of validity of the subject certificate. + /// + /// + /// The period of validity of the subject certificate must be within the period of validity of the issuer certificate. + /// + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/seccrypto/wthelpercertfindissuercertificate PCCERT_CONTEXT WINAPI + // WTHelperCertFindIssuerCertificate( _In_ PCCERT_CONTEXT pChildContext, _In_ DWORD chStores, _In_ HCERTSTORE *pahStores, _In_ + // FILETIME *psftVerifyAsOf, _In_ DWORD dwEncoding, _Out_opt_ DWORD *pdwConfidence, _Out_ DWORD *dwError ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("wintrust.h", MSDNShortId = "c724f602-fc73-4857-941f-0f22a9e472d1")] + public static extern IntPtr WTHelperCertFindIssuerCertificate(in CERT_CONTEXT pChildContext, uint chStores, [In] HCERTSTORE[] pahStores, in FILETIME psftVerifyAsOf, CertEncodingType dwEncoding, out CertConfidence pdwConfidence, out Win32Error dwError); + /// /// /// [The WTHelperCertIsSelfSigned function is available for use in the operating systems specified in the Requirements @@ -1071,6 +1178,81 @@ namespace Vanara.PInvoke [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WTHelperCertIsSelfSigned(uint dwEncoding, in CERT_INFO pCert); + /// + /// + /// [The WTHelperGetFileHash function is available for use in the operating systems specified in the Requirements section. It + /// may be altered or unavailable in subsequent versions.] + /// + /// + /// The WTHelperGetFileHash function verifies the signature of a signed file and obtains the hash value and algorithm + /// identifier for the file. + /// + /// + /// + /// A pointer to a null-terminated Unicode string that contains the path and file name of the file to get the hash for. + /// + /// This parameter is not used and should be zero. + /// This parameter is not used and should be NULL. + /// + /// A pointer to a buffer to receive the hash value for the file. The pcbFileHash parameter contains the size of this buffer. + /// + /// + /// + /// A pointer to a DWORD variable that, on input, contains the size, in bytes, of the pbFileHash buffer and, on output, + /// receives the size, in bytes, of the hash value. + /// + /// + /// To obtain the required size of the hash value, pass NULL for the pbFileHash parameter. This function will place the + /// required size, in bytes, of the hash value in this location. + /// + /// + /// If the pbFileHash parameter is not NULL, and the size is not large enough to receive the hash value, this function will + /// place the required size, in bytes, in this location and return ERROR_MORE_DATA. + /// + /// + /// + /// A pointer to an ALG_ID variable to receive the identifier of the algorithm used to create the hash value. This parameter + /// can be NULL if this information is not needed. + /// + /// + /// Returns a status code that indicates the success or failure of the function. + /// Possible return codes include, but are not limited to, the following. + /// + /// + /// Return code + /// Description + /// + /// + /// ERROR_SUCCESS + /// The file is signed, and the signature was verified. + /// + /// + /// ERROR_MORE_DATA + /// + /// The pbFileHash parameter is not NULL, and the size specified by the pcbFileHash parameter is not large enough to receive the hash. + /// + /// + /// + /// ERROR_NOT_ENOUGH_MEMORY + /// A memory allocation failure occurred. + /// + /// + /// TRUST_E_BAD_DIGEST + /// The signature of the file was not verified. + /// + /// + /// TRUST_E_NOSIGNATURE + /// The file was not signed or had a signature that is not valid. + /// + /// + /// + // https://docs.microsoft.com/en-us/windows/win32/seccrypto/wthelpergetfilehash LONG WINAPI WTHelperGetFileHash( _In_ LPCWSTR + // pwszFilename, _In_ DWORD dwFlags, _Inout_opt_ PVOID pvReserved, _Out_opt_ BYTE *pbFileHash, _Inout_opt_ DWORD *pcbFileHash, + // _Out_opt_ ALG_ID *pHashAlgid ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("wintrust.h", MSDNShortId = "130b3c3e-cc67-44ec-acc7-daa87b714299")] + public static extern int WTHelperGetFileHash([MarshalAs(UnmanagedType.LPWStr)] string pwszFilename, [Optional] uint dwFlags, [In, Out, Optional] IntPtr pvReserved, [Out] IntPtr pbFileHash, ref uint pcbFileHash, out ALG_ID pHashAlgid); + /// /// /// [The WTHelperGetProvCertFromChain function is available for use in the operating systems specified in the Requirements @@ -1078,8 +1260,8 @@ namespace Vanara.PInvoke /// and CertVerifyCertificateChainPolicy functions. For Microsoft Authenticode technology signature verification, use the .NET Framework.] /// /// - /// The WTHelperGetProvCertFromChain function retrieves a trust provider certificate from the certificate chain. This function - /// has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// The WTHelperGetProvCertFromChain function retrieves a trust provider certificate from the certificate chain. This + /// function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. /// /// /// @@ -1129,15 +1311,74 @@ namespace Vanara.PInvoke /// /// - /// [The CRYPT_PROVIDER_CERT structure is available for use in the operating systems specified in the Requirements section. It - /// may be altered or unavailable in subsequent versions.] + /// [The WTHelperGetProvSignerFromChain function is available for use in the operating systems specified in the Requirements + /// section. It may be altered or unavailable in subsequent versions. For certificate verification, use the CertGetCertificateChain + /// and CertVerifyCertificateChainPolicy functions. For Microsoft Authenticode technology signature verification, use the .NET Framework.] + /// + /// + /// The WTHelperGetProvSignerFromChain function retrieves a signer or countersigner by index from the chain. This function + /// has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// A pointer to the CRYPT_PROVIDER_DATA structure that contains the signer and countersigner information. + /// The index of the signer. The index is zero based. + /// + /// If TRUE, the countersigner, as specified by idxCounterSigner, is retrieved by this function; the signer that contains the + /// countersigner is identified by idxSigner. If FALSE, the signer, as specified by idxSigner, is retrieved by this function. + /// + /// + /// The index of the countersigner. The index is zero based. The countersigner applies to the signer identified by idxSigner. + /// + /// + /// + /// If the function succeeds, the function returns a pointer to a CRYPT_PROVIDER_SGNR structure for the requested signer or countersigner. + /// + /// If the function fails, it returns NULL. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/wintrust/nf-wintrust-wthelpergetprovsignerfromchain CRYPT_PROVIDER_SGNR * + // WTHelperGetProvSignerFromChain( CRYPT_PROVIDER_DATA *pProvData, DWORD idxSigner, BOOL fCounterSigner, DWORD idxCounterSigner ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("wintrust.h", MSDNShortId = "8e1ebf82-73c2-445b-9964-6739f7c90c47")] + public static extern IntPtr WTHelperGetProvSignerFromChain(in CRYPT_PROVIDER_DATA pProvData, uint idxSigner, [MarshalAs(UnmanagedType.Bool)] bool fCounterSigner, uint idxCounterSigner); + + /// + /// + /// [The WTHelperProvDataFromStateData function is available for use in the operating systems specified in the Requirements + /// section. It may be altered or unavailable in subsequent versions. For certificate verification, use the CertGetCertificateChain + /// and CertVerifyCertificateChainPolicy functions. For Microsoft Authenticode technology signature verification, use the .NET Framework.] + /// + /// + /// The WTHelperProvDataFromStateData function retrieves trust provider information from a specified handle. This function + /// has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Wintrust.dll. + /// + /// + /// + /// A handle previously set by the WinVerifyTrustEx function as the hWVTStateData member of the WINTRUST_DATA structure. + /// + /// + /// + /// If the function succeeds, the function returns a pointer to a CRYPT_PROVIDER_DATA structure. The returned pointer can be used by + /// the WTHelperGetProvSignerFromChain function. + /// + /// If the function fails, it returns NULL. + /// + // https://docs.microsoft.com/en-us/windows/win32/api/wintrust/nf-wintrust-wthelperprovdatafromstatedata CRYPT_PROVIDER_DATA * + // WTHelperProvDataFromStateData( HANDLE hStateData ); + [DllImport(Lib.Wintrust, SetLastError = false, ExactSpelling = true)] + [PInvokeData("wintrust.h", MSDNShortId = "ca2ca612-2da6-4fe1-8b1e-bc6307eb92af")] + public static extern IntPtr WTHelperProvDataFromStateData(HANDLE hStateData); + + /// + /// + /// [The CRYPT_PROVIDER_CERT structure is available for use in the operating systems specified in the Requirements section. + /// It may be altered or unavailable in subsequent versions.] /// /// The CRYPT_PROVIDER_CERT structure provides information about a provider certificate. /// - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provider_cert typedef struct _CRYPT_PROVIDER_CERT - // { DWORD cbStruct; PCCERT_CONTEXT pCert; BOOL fCommercial; BOOL fTrustedRoot; BOOL fSelfSigned; BOOL fTestCert; DWORD - // dwRevokedReason; DWORD dwConfidence; DWORD dwError; CTL_CONTEXT *pTrustListContext; BOOL fTrustListSignerCert; PCCTL_CONTEXT - // pCtlContext; DWORD dwCtlError; BOOL fIsCyclic; PCERT_CHAIN_ELEMENT pChainElement; } CRYPT_PROVIDER_CERT, *PCRYPT_PROVIDER_CERT; + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provider_cert typedef struct + // _CRYPT_PROVIDER_CERT { DWORD cbStruct; PCCERT_CONTEXT pCert; BOOL fCommercial; BOOL fTrustedRoot; BOOL fSelfSigned; BOOL + // fTestCert; DWORD dwRevokedReason; DWORD dwConfidence; DWORD dwError; CTL_CONTEXT *pTrustListContext; BOOL fTrustListSignerCert; + // PCCTL_CONTEXT pCtlContext; DWORD dwCtlError; BOOL fIsCyclic; PCERT_CHAIN_ELEMENT pChainElement; } CRYPT_PROVIDER_CERT, *PCRYPT_PROVIDER_CERT; [PInvokeData("wintrust.h", MSDNShortId = "622e7a72-445a-4820-b236-1c90dad08351")] [StructLayout(LayoutKind.Sequential)] public struct CRYPT_PROVIDER_CERT @@ -1196,7 +1437,7 @@ namespace Vanara.PInvoke /// /// /// - public uint dwConfidence; + public CertConfidence dwConfidence; /// A pointer to a DWORD variable that contains the error value for this certificate, if applicable. public uint dwError; @@ -1226,7 +1467,8 @@ namespace Vanara.PInvoke /// [The CRYPT_PROVUI_DATA structure is available for use in the operating systems specified in the Requirements section. It may be /// altered or unavailable in subsequent versions.] /// - /// The CRYPT_PROVUI_DATA structure provides user interface (UI) data for a provider.This structure is used by the CRYPT_PROVUI_FUNCS structure. + /// The CRYPT_PROVUI_DATA structure provides user interface (UI) data for a provider.This structure is used by the + /// CRYPT_PROVUI_FUNCS structure. /// /// [PInvokeData("wintrust.h", MSDNShortId = "86f819f0-c243-45ba-8b7b-97ed906e6e8a")] @@ -1271,8 +1513,8 @@ namespace Vanara.PInvoke public string pCopyActionTextNoTS; /// - /// A pointer to a null-terminated string for the text used when a signature is not provided. If this parameter is NULL, then "Do - /// you want to install and run ""%1""?" is used. + /// A pointer to a null-terminated string for the text used when a signature is not provided. If this parameter is NULL, then + /// "Do you want to install and run ""%1""?" is used. /// [MarshalAs(UnmanagedType.LPWStr)] public string pCopyActionTextNotSigned; @@ -1435,15 +1677,15 @@ namespace Vanara.PInvoke /// /// - /// [The CRYPT_PROVIDER_SGNR structure is available for use in the operating systems specified in the Requirements section. It - /// may be altered or unavailable in subsequent versions.] + /// [The CRYPT_PROVIDER_SGNR structure is available for use in the operating systems specified in the Requirements section. + /// It may be altered or unavailable in subsequent versions.] /// /// The CRYPT_PROVIDER_SGNR structure provides information about a signer or countersigner. /// - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provider_sgnr typedef struct _CRYPT_PROVIDER_SGNR - // { DWORD cbStruct; FILETIME sftVerifyAsOf; DWORD csCertChain; struct _CRYPT_PROVIDER_CERT *pasCertChain; DWORD dwSignerType; - // CMSG_SIGNER_INFO *psSigner; DWORD dwError; DWORD csCounterSigners; struct _CRYPT_PROVIDER_SGNR *pasCounterSigners; - // PCCERT_CHAIN_CONTEXT pChainContext; } CRYPT_PROVIDER_SGNR, *PCRYPT_PROVIDER_SGNR; + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provider_sgnr typedef struct + // _CRYPT_PROVIDER_SGNR { DWORD cbStruct; FILETIME sftVerifyAsOf; DWORD csCertChain; struct _CRYPT_PROVIDER_CERT *pasCertChain; + // DWORD dwSignerType; CMSG_SIGNER_INFO *psSigner; DWORD dwError; DWORD csCounterSigners; struct _CRYPT_PROVIDER_SGNR + // *pasCounterSigners; PCCERT_CHAIN_CONTEXT pChainContext; } CRYPT_PROVIDER_SGNR, *PCRYPT_PROVIDER_SGNR; [PInvokeData("wintrust.h", MSDNShortId = "39cf9a03-768d-4ae0-a19d-17652181dbe4")] [StructLayout(LayoutKind.Sequential)] public struct CRYPT_PROVIDER_SGNR @@ -1626,8 +1868,8 @@ namespace Vanara.PInvoke /// /// /// The prototype for PFN_PROVUI_CALL is defined as: - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provui_funcs typedef struct _CRYPT_PROVUI_FUNCS { - // DWORD cbStruct; struct _CRYPT_PROVUI_DATA *psUIData; PFN_PROVUI_CALL pfnOnMoreInfoClick; PFN_PROVUI_CALL + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_crypt_provui_funcs typedef struct _CRYPT_PROVUI_FUNCS + // { DWORD cbStruct; struct _CRYPT_PROVUI_DATA *psUIData; PFN_PROVUI_CALL pfnOnMoreInfoClick; PFN_PROVUI_CALL // pfnOnMoreInfoClickDefault; PFN_PROVUI_CALL pfnOnAdvancedClick; PFN_PROVUI_CALL pfnOnAdvancedClickDefault; } CRYPT_PROVUI_FUNCS, *PCRYPT_PROVUI_FUNCS; [PInvokeData("wintrust.h", MSDNShortId = "7cdc32ea-b28a-400f-ad8a-984f86bb95fd")] [StructLayout(LayoutKind.Sequential)] @@ -1729,7 +1971,7 @@ namespace Vanara.PInvoke [StructLayout(LayoutKind.Sequential)] public struct HCATADMIN : IHandle { - private IntPtr handle; + private readonly IntPtr handle; /// Initializes a new instance of the struct. /// An object that represents the pre-existing handle to use. @@ -1777,7 +2019,7 @@ namespace Vanara.PInvoke [StructLayout(LayoutKind.Sequential)] public struct HCRYPTMSG : IHandle { - private IntPtr handle; + private readonly IntPtr handle; /// Initializes a new instance of the struct. /// An object that represents the pre-existing handle to use. @@ -1822,8 +2064,8 @@ namespace Vanara.PInvoke } /// - /// The SPC_INDIRECT_DATA_CONTENT structure is used in Authenticode signatures to store the digest and other attributes of the - /// signed file. + /// The SPC_INDIRECT_DATA_CONTENT structure is used in Authenticode signatures to store the digest and other attributes of + /// the signed file. /// // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_spc_indirect_data_content typedef struct // _SPC_INDIRECT_DATA_CONTENT { CRYPT_ATTRIBUTE_TYPE_VALUE Data; CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; CRYPT_HASH_BLOB Digest; @@ -1843,8 +2085,8 @@ namespace Vanara.PInvoke } /// This structure encapsulates a signature used in verifying executable files. - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_win_certificate typedef struct _WIN_CERTIFICATE { DWORD - // dwLength; WORD wRevision; WORD wCertificateType; BYTE bCertificate[ANYSIZE_ARRAY]; } WIN_CERTIFICATE, *LPWIN_CERTIFICATE; + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-_win_certificate typedef struct _WIN_CERTIFICATE { + // DWORD dwLength; WORD wRevision; WORD wCertificateType; BYTE bCertificate[ANYSIZE_ARRAY]; } WIN_CERTIFICATE, *LPWIN_CERTIFICATE; [PInvokeData("wintrust.h", MSDNShortId = "AC666871-265B-4D09-B7A6-DEC48D4645FD")] [StructLayout(LayoutKind.Sequential)] public struct WIN_CERTIFICATE @@ -1904,8 +2146,8 @@ namespace Vanara.PInvoke /// that support this structure. /// /// - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_blob_info_ typedef struct WINTRUST_BLOB_INFO_ { - // DWORD cbStruct; GUID gSubject; LPCWSTR pcwszDisplayName; DWORD cbMemObject; BYTE *pbMemObject; DWORD cbMemSignedMsg; BYTE + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_blob_info_ typedef struct WINTRUST_BLOB_INFO_ + // { DWORD cbStruct; GUID gSubject; LPCWSTR pcwszDisplayName; DWORD cbMemObject; BYTE *pbMemObject; DWORD cbMemSignedMsg; BYTE // *pbMemSignedMsg; } WINTRUST_BLOB_INFO, *PWINTRUST_BLOB_INFO; [PInvokeData("wintrust.h", MSDNShortId = "8b13d355-4d24-4d8e-aae3-db16467999be")] [StructLayout(LayoutKind.Sequential)] @@ -1990,8 +2232,8 @@ namespace Vanara.PInvoke /// /// The WINTRUST_CERT_INFO structure is used when calling WinVerifyTrust to verify a CERT_CONTEXT. /// - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_cert_info_ typedef struct WINTRUST_CERT_INFO_ { - // DWORD cbStruct; LPCWSTR pcwszDisplayName; CERT_CONTEXT *psCertContext; DWORD chStores; HCERTSTORE *pahStores; DWORD dwFlags; + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_cert_info_ typedef struct WINTRUST_CERT_INFO_ + // { DWORD cbStruct; LPCWSTR pcwszDisplayName; CERT_CONTEXT *psCertContext; DWORD chStores; HCERTSTORE *pahStores; DWORD dwFlags; // FILETIME *psftVerifyAsOf; } WINTRUST_CERT_INFO, *PWINTRUST_CERT_INFO; [PInvokeData("wintrust.h", MSDNShortId = "6522d1f0-3d96-4499-9220-23288122e0e6")] [StructLayout(LayoutKind.Sequential)] @@ -2010,8 +2252,8 @@ namespace Vanara.PInvoke public uint chStores; /// - /// An array of open certificate stores to add to the list of stores that the policy provider looks in to find certificates while - /// building a trust chain. + /// An array of open certificate stores to add to the list of stores that the policy provider looks in to find certificates + /// while building a trust chain. /// public IntPtr pahStores; @@ -2023,8 +2265,8 @@ namespace Vanara.PInvoke } /// The WINTRUST_FILE_INFO structure is used when calling WinVerifyTrust to verify an individual file. - // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_file_info_ typedef struct WINTRUST_FILE_INFO_ { - // DWORD cbStruct; LPCWSTR pcwszFilePath; HANDLE hFile; GUID *pgKnownSubject; } WINTRUST_FILE_INFO, *PWINTRUST_FILE_INFO; + // https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/ns-wintrust-wintrust_file_info_ typedef struct WINTRUST_FILE_INFO_ + // { DWORD cbStruct; LPCWSTR pcwszFilePath; HANDLE hFile; GUID *pgKnownSubject; } WINTRUST_FILE_INFO, *PWINTRUST_FILE_INFO; [PInvokeData("wintrust.h", MSDNShortId = "3c3bef86-a2ed-47d1-a726-90630433358a")] [StructLayout(LayoutKind.Sequential)] public struct WINTRUST_FILE_INFO @@ -2133,7 +2375,7 @@ namespace Vanara.PInvoke public class WINTRUST_DATA : IDisposable { /// The size, in bytes, of this structure. - private int _cbStruct; + private readonly int _cbStruct; /// A pointer to a data buffer used to pass policy-specific data to a policy provider. This member can be NULL. public IntPtr pPolicyCallbackData; @@ -2281,28 +2523,5 @@ namespace Vanara.PInvoke Marshal.FreeCoTaskMem(_pInfoStruct); } } - - /* - OpenPersonalTrustDBDialog https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-openpersonaltrustdbdialog - OpenPersonalTrustDBDialogEx https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-openpersonaltrustdbdialogex - WTHelperCertCheckValidSignature https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelpercertcheckvalidsignature - WTHelperCertFindIssuerCertificate https://docs.microsoft.com/en-us/windows/desktop/SecCrypto/wthelpercertfindissuercertificate - WTHelperCertIsSelfSigned https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelpercertisselfsigned - WTHelperGetFileHash https://docs.microsoft.com/en-us/windows/desktop/SecCrypto/wthelpergetfilehash - WTHelperGetProvCertFromChain https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelpergetprovcertfromchain - WTHelperGetProvPrivateDataFromChain https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelpergetprovprivatedatafromchain - WTHelperGetProvSignerFromChain https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelpergetprovsignerfromchain - WTHelperProvDataFromStateData https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wthelperprovdatafromstatedata - WinVerifyTrust https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-winverifytrust - WinVerifyTrustEx https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-winverifytrustex - WintrustAddActionID https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustaddactionid - WintrustAddDefaultForUsage https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustadddefaultforusage - WintrustGetDefaultForUsage https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustgetdefaultforusage - WintrustGetRegPolicyFlags https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustgetregpolicyflags - WintrustLoadFunctionPointers https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustloadfunctionpointers - WintrustRemoveActionID https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustremoveactionid - WintrustSetDefaultIncludePEPageHashes https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustsetdefaultincludepepagehashes - WintrustSetRegPolicyFlags https://docs.microsoft.com/en-us/windows/desktop/api/wintrust/nf-wintrust-wintrustsetregpolicyflags - */ } } \ No newline at end of file