使用 .Net 中的 IAmsiStream 会导致 AccessViolationException

Using IAmsiStream from .Net leads to AccessViolationException

我正在尝试使用 amsi.h 中定义的 Antimalware Scan Interface (AMSI) via C#. I know that there are implementations out there that use the AmsiScanBuffer method, but I want to scan much larger files. So I want to use the IAntimalware COM 接口。

到目前为止,我想出了这个代码:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace AmsiTest
{
    [Guid("82d29c2e-f062-44e6-b5c9-3d9a2f24a2df"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport]
    public interface IAntiMalware {
        uint Scan([MarshalAs(UnmanagedType.Interface)] IAmsiStream stream, out AMSI_RESULT result, [MarshalAs(UnmanagedType.Interface)] out IAntimalwareProvider provider);
        void CloseSession(ulong session);
    }

    [Guid("b2cabfe3-fe04-42b1-a5df-08d483d4d125"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IAntimalwareProvider
    {
        uint Scan([In, MarshalAs(UnmanagedType.Interface)] IAmsiStream stream, [Out] out AMSI_RESULT result);
        void CloseSession(ulong session);
        uint DisplayName(ref IntPtr displayName);
    }

    [ComImport]
    [Guid("fdb00e52-a214-4aa1-8fba-4357bb0072ec")]
    [ComSourceInterfaces(typeof(IAntiMalware))]
    public class CAntimalware
    {
    }

    public enum AMSI_ATTRIBUTE
    {
        AMSI_ATTRIBUTE_APP_NAME = 0,
        AMSI_ATTRIBUTE_CONTENT_NAME = 1,
        AMSI_ATTRIBUTE_CONTENT_SIZE = 2,
        AMSI_ATTRIBUTE_CONTENT_ADDRESS  = 3,
        AMSI_ATTRIBUTE_SESSION  = 4,
        AMSI_ATTRIBUTE_REDIRECT_CHAIN_SIZE  = 5,
        AMSI_ATTRIBUTE_REDIRECT_CHAIN_ADDRESS   = 6,
        AMSI_ATTRIBUTE_ALL_SIZE = 7,
        AMSI_ATTRIBUTE_ALL_ADDRESS  = 8,
        AMSI_ATTRIBUTE_QUIET    = 9
    }   


    [Guid("3e47f2e5-81d4-4d3b-897f-545096770373"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IAmsiStream
    {
        uint GetAttribute(AMSI_ATTRIBUTE attribute, uint dataSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, out int retData);
        
        int Read(
            /* [in] */
            long position,
            /* [range][in] */
            int size,
            /* [length_is][size_is][out] */
            [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
            byte[] buffer,
            /* [out] */
            [Out] out int readSize);
    }

    public class AmsiStream : IAmsiStream
    {
        private readonly Stream _Input;

        public uint GetAttribute(AMSI_ATTRIBUTE attribute, uint dataSize, byte[] data, out int retData)
        {
            const uint E_INSUFFICIENT_BUFFER = 0x8007007A;
            retData = 100;
            return E_INSUFFICIENT_BUFFER;
        }

        public int Read(long position, int size, byte[] buffer, out int readSize)
        {
            _Input.Seek(position, SeekOrigin.Begin);
            readSize = _Input.Read(buffer, 0, size);
            return 0;
        }

            public AmsiStream(Stream input)
        {
            _Input = input ?? throw new ArgumentNullException(nameof(input));
        }

    }

    public enum AMSI_RESULT
    {
        AMSI_RESULT_CLEAN,
        AMSI_RESULT_NOT_DETECTED,
        AMSI_RESULT_BLOCKED_BY_ADMIN_START,
        AMSI_RESULT_BLOCKED_BY_ADMIN_END,
        AMSI_RESULT_DETECTED
    }


    class Program
    {
        static void Main(string[] args)
        {
            var scanner = new CAntimalware() as IAntiMalware;
            var scanResult = AMSI_RESULT.AMSI_RESULT_BLOCKED_BY_ADMIN_END;
            IAntimalwareProvider provider = null;
            IAmsiStream stream = new AmsiStream(new MemoryStream(Encoding.ASCII.GetBytes("TestString")));
            var result = scanner.Scan(stream, out scanResult, out provider);
        }
    }
}

当我 运行 这个程序时,我看到 GetAttribute 方法被调用一次(attribute 设置为 AMSI_ATTRIBUTE_APP_NAMEdataSize 设置为 1data 设置为 byte[1]'. The Read 方法永远不会被调用。但不管我 return 是什么,它总是以 AccessViolationException 结束(当作为 64 位处理器执行时):

mscorlib.dll!System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(int hr, System.IntPtr pCPCMD, object pThis)
[Native to Managed Transition]
ntdll.dll!RtlpFreeHeapInternal()
ntdll.dll!RtlFreeHeap()
mscorlib.ni.dll!00007ff8cad6a76e()
[Managed to Native Transition]
ConsoleApp6.exe!AmsiTest.Program.Main(string[] args) Line 109
    at c:\temp\ConsoleApp6\Program.cs(109)
[Native to Managed Transition]
mscoreei.dll!00007ff8cfb78c01()
mscoree.dll!00007ff8d684ac42()
kernel32.dll!00007ff8e4416fd4()
ntdll.dll!RtlUserThreadStart()

如果我 运行 它作为 32 位程序,我得到这个:

System.ArgumentException: 'Value does not fall within the expected range.'
ConsoleApp6.exe!AmsiTest.Program.Main(string[] args) Line 109
    at c:\temp\ConsoleApp6\Program.cs(109)
[Native to Managed Transition]
mscoreei.dll!__CorExeMain@0()
mscoree.dll!_ShellShim__CorExeMain@0()
mscoree.dll!__CorExeMain_Exported@0()
ntdll.dll!773974b4()

据此我假设我的 COM 声明有些错误,但我无法弄清楚。我还尝试用 IntPtr 替换 byte[] data 声明,但无济于事。

知道我做错了什么吗?

这些是 amsi.idl 文件中的声明:

[
    local,
    object,
    pointer_default(unique),
    uuid(3e47f2e5-81d4-4d3b-897f-545096770373)
]
interface IAmsiStream : IUnknown
{
    HRESULT GetAttribute(
                [in]                        AMSI_ATTRIBUTE  attribute,
                [in, range(0, 1024*1024)]   ULONG           dataSize,
                [out, size_is(dataSize), length_is(*retData)] unsigned char* data,
                [out]                       ULONG*          retData);

    HRESULT Read(
                [in]                        ULONGLONG       position,
                [in, range(0, 1024*1024)]   ULONG           size,
                [out, size_is(size), length_is(*readSize)] unsigned char* buffer,
                [out]                       ULONG*          readSize);
}


[
    local,
    object,
    pointer_default(unique),
    uuid(b2cabfe3-fe04-42b1-a5df-08d483d4d125)
]
interface IAntimalwareProvider : IUnknown
{
    HRESULT Scan(
                [in]  IAmsiStream*      stream,
                [out] AMSI_RESULT*      result);

    void CloseSession([in] ULONGLONG session);

    HRESULT DisplayName([out, string, annotation("_Out_")] LPWSTR* displayName);
}

[
    local,
    object,
    pointer_default(unique),
    uuid(82d29c2e-f062-44e6-b5c9-3d9a2f24a2df)
]
interface IAntimalware : IUnknown
{
    HRESULT Scan(
                [in]   IAmsiStream*           stream,
                [out]  AMSI_RESULT*           result,
                [out]  IAntimalwareProvider** provider);

    void CloseSession([in] ULONGLONG session);
}

typedef [v1_enum] enum AMSI_ATTRIBUTE
{
    AMSI_ATTRIBUTE_APP_NAME     = 0,
    AMSI_ATTRIBUTE_CONTENT_NAME = 1,
    AMSI_ATTRIBUTE_CONTENT_SIZE = 2,
    AMSI_ATTRIBUTE_CONTENT_ADDRESS = 3,
    AMSI_ATTRIBUTE_SESSION = 4,
    AMSI_ATTRIBUTE_REDIRECT_CHAIN_SIZE = 5,
    AMSI_ATTRIBUTE_REDIRECT_CHAIN_ADDRESS = 6,
    AMSI_ATTRIBUTE_ALL_SIZE = 7,
    AMSI_ATTRIBUTE_ALL_ADDRESS = 8,
    AMSI_ATTRIBUTE_QUIET = 9,
} AMSI_ATTRIBUTE;

typedef [v1_enum] enum AMSI_RESULT
{
    AMSI_RESULT_CLEAN        = 0,
    AMSI_RESULT_NOT_DETECTED = 1,
    AMSI_RESULT_BLOCKED_BY_ADMIN_START = 0x4000,
    AMSI_RESULT_BLOCKED_BY_ADMIN_END   = 0x4fff,
    AMSI_RESULT_DETECTED     = 32768,
} AMSI_RESULT;

您需要告诉 .NET 数组是 IAnsiStream 中的 Out 参数,如下所示:

[Guid("3e47f2e5-81d4-4d3b-897f-545096770373"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAmsiStream
{
    [PreserveSig]
    int GetAttribute(AMSI_ATTRIBUTE attribute, int dataSize, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, out int retData);
    
    [PreserveSig]
    int Read(long position, int size, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] buffer, out int readSize);
}

另请注意,我使用 PreserveSig 将方法 return 值明确定义为 HRESULT。

下面是 GetAttribute 方法的示例实现:

public int GetAttribute(AMSI_ATTRIBUTE attribute, int dataSize, byte[] data, out int retData)
{
    const int E_NOT_SUFFICIENT_BUFFER = unchecked((int)0x8007007A);
    switch (attribute)
    {
        case AMSI_ATTRIBUTE.AMSI_ATTRIBUTE_APP_NAME:
            const string appName = "My App Name";
            var bytes = Encoding.Unicode.GetBytes(appName + "[=11=]"); // force terminating zero
            retData = bytes.Length;
            if (dataSize < bytes.Length)
                return E_NOT_SUFFICIENT_BUFFER;

            Array.Copy(bytes, data, bytes.Length);
            return 0;

        // TODO: implement what's needed

        default:
            retData = 0;
            const int E_NOTIMPL = unchecked((int)0x80004001);
            return E_NOTIMPL;
    }
}