从签名文件中获取 SignedCms 的 C# 实现

C# implementation to get SignedCms from signed file

我正在使用 C++ CRYPT32.DLL 从签名的 c# 程序集 dll 中提取 SignedCms 对象。

用于签署 dll 的证书已过期,但内部有一个有效的证书链。重要的是,证书由三个证书组成,我都想提取。

    private static readonly int CERT_QUERY_OBJECT_FILE = 0x00000001;
    private static readonly int CERT_QUERY_CONTENT_FLAG_ALL = 0x00003ffe;
    private static readonly int CERT_QUERY_FORMAT_FLAG_ALL = 0x0000000e;
    private static readonly int CMSG_ENCODED_MESSAGE = 29;

    [DllImport("CRYPT32.DLL", EntryPoint = "CryptQueryObject", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool CryptQueryObject(
        int dwObjectType,
        IntPtr pvObject,
        int dwExpectedContentTypeFlags,
        int dwExpectedFormatTypeFlags,
        int dwFlags,
        IntPtr pdwMsgAndCertEncodingType,
        IntPtr pdwContentType,
        IntPtr pdwFormatType,
        IntPtr phCertStore,
        IntPtr phMsg,
        IntPtr ppvContext
    );

    [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool CryptMsgGetParam(
        IntPtr hCryptMsg, int dwParamType, int dwIndex, IntPtr pvData, ref int pcbData );

    public static SignedCms GetSignedCmsFromFile(string fileName)
    {
        var pvObject = Marshal.StringToHGlobalUni(fileName);
        var phMessage = Marshal.AllocHGlobal(IntPtr.Size);
        var pvData = IntPtr.Zero;

        try
        {
            SignedCms signedCms = null;
            var success = CryptQueryObject(
                CERT_QUERY_OBJECT_FILE,
                pvObject,
                CERT_QUERY_CONTENT_FLAG_ALL,
                CERT_QUERY_FORMAT_FLAG_ALL,
                0,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                phMessage,
                IntPtr.Zero);

            if (success)
            {
                var hMessage = Marshal.ReadIntPtr(phMessage);
                var cbData = 0;
                success = CryptMsgGetParam(
                    hMessage,
                    CMSG_ENCODED_MESSAGE,
                    0,
                    IntPtr.Zero,
                    ref cbData);

                if (success)
                {
                    var data = new byte[cbData];
                    pvData = Marshal.AllocHGlobal(sizeof(byte) * data.Length);

                    success = CryptMsgGetParam(
                        hMessage,
                        CMSG_ENCODED_MESSAGE,
                        0,
                        pvData,
                        ref cbData);

                    if (success)
                    {
                        Marshal.Copy(pvData, data, 0, cbData);
                        signedCms = new SignedCms();

                        try
                        {
                            signedCms.Decode(data);
                            File.WriteAllBytes(fileName + ".export", data);
                        }
                        catch (CryptographicException)
                        {
                            signedCms = null;
                        }
                    }
                }
            }

            return signedCms;
        }
        finally
        {
            if (pvObject != IntPtr.Zero)
                Marshal.FreeHGlobal(pvObject);

            if (phMessage != IntPtr.Zero)
                Marshal.FreeHGlobal(phMessage);

            if (pvData != IntPtr.Zero)
                Marshal.FreeHGlobal(pvData);
        }
    }

该函数工作得很好,但由于 crypt32.dll 函数被删除,我正在寻找一个纯 C# 实现,它做同样的事情并提供 SignedCms 对象。

到目前为止我能找到的最接近的是 X509Certificate。

X509Certificate2 cert = new X509Certificate2(fileName)

CryptQueryObject function


解决方案

感谢下面的 post,我可以实现纯 C# 方法来提取 SignedCms。

唯一不完美的地方是 startindex 偏移了 8 个字节,大小小了 10 个字节。

    public static SignedCms GetSignedCmsFromFile(string fileName)
    {
        var result = new SignedCms();

        uint startIndex = 0;
        uint size = 0;

        var reader = new PeHeaderReader(fileName);
        if (reader.Is32BitHeader)
        {
            startIndex = reader.OptionalHeader32.CertificateTable.VirtualAddress;
            size = reader.OptionalHeader32.CertificateTable.Size;
        }
        else
        {
            startIndex = reader.OptionalHeader64.CertificateTable.VirtualAddress;
            size = reader.OptionalHeader64.CertificateTable.Size;
        }

        //var data = File.ReadAllBytes(fileName).Skip((int)startIndex).Take((int)size).ToArray();

        //Somehow the start index and size are not fitting perfectly and I have to adapt them
        var data = File.ReadAllBytes(fileName).Skip((int)startIndex + 8).Take((int)size - 10).ToArray();

        result.Decode(data);

        return result;
    }

我还没有找到与该调用等效的 CNG,但这里是 specification,它可以让您提取 PKCS#7,它是 SignedCms 的字节:

规范说:

Authenticode signatures can be “embedded” in a Windows PE file, in a location specified by the Certificate Table entry in Optional Header Data Directories

下面是对 PE header 中字节的很好的概述: - https://resources.infosecinstitute.com/presenting-the-pe-header/ - https://www.red-gate.com/simple-talk/blogs/anatomy-of-a-net-assembly-pe-headers/

几乎所有细节:https://blog.kowalczyk.info/articles/pefileformat.html

在 github 上,我找到了一个读取 PE header 的托管样本:https://gist.github.com/augustoproiete/b51f29f74f5f5b2c59c39e47a8afc3a3

编辑:根据@martin-s 的评论,github 上的代码不可靠,他通过以下替代方案成功了:

https://github.com/secana/PeNet

所有部分一起应该完成工作。