Using IAmsiStream from .Net leads to AccessViolationException

1

I'm trying to use the 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 interface which is defined in amsi.h.

So far, I've come up with this code:

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);
        }
    }
}

When I run this program, I see the GetAttribute method being called once (with attribute set to AMSI_ATTRIBUTE_APP_NAME, dataSize set to 1 and data set to a byte[1]'. The Read` method is never called. But regardless of what I return, it always ends with an AccessViolationException (when executed as 64 processor):

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()

If I run it as 32 bit program, I get this:

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()

From this I assume my COM declarations are somewhat wrong, but I can't figure it out. I also tried to replace the byte[] data declarations with IntPtr, but to no avail.

Any ideas what I'm doing wrong here?

These are the declarations in the amsi.idl file:

[
    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;

c#
c++
.net
com
com-interop
asked on Stack Overflow Sep 27, 2020 by Henning Krause • edited Sep 27, 2020 by Simon Mourier

1 Answer

2

You need to tell .NET that the arrays are Out parameters in IAnsiStream, like this:

[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);
}

Also note I use PreserveSig to explicitely define methods return value as HRESULT.

And here is a sample implementation for the GetAttribute method:

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 + "\0"); // 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;
    }
}
answered on Stack Overflow Sep 27, 2020 by Simon Mourier • edited Sep 27, 2020 by Simon Mourier

User contributions licensed under CC BY-SA 3.0