#nullable enable using IPA.AntiMalware.ComAPI; using IPA.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPA.AntiMalware { internal class WindowsCOMAntiMalware : IAntiMalware { internal static WindowsCOMAntiMalware? TryInitialize() { try { return new(); } catch (Exception e) { Logger.AntiMalware.Warn("Could not initialize antimalware engine:"); Logger.AntiMalware.Warn(e); return null; } } private readonly IAntimalware amInterface; private WindowsCOMAntiMalware() { var amType = Type.GetTypeFromCLSID(AmsiConstants.CAntimalwareGuid, true); amInterface = (IAntimalware)Activator.CreateInstance(amType); } private static ScanResult ScanResultFromAmsiResult(AmsiResult result) => result switch { AmsiResult.Clean => ScanResult.KnownSafe, AmsiResult.NotDetected => ScanResult.NotDetected, AmsiResult.Detected => ScanResult.Detected, _ => ScanResult.MaybeMalware }; public ScanResult ScanFile(FileInfo file) { using var stream = new AmsiFileStream(file, IntPtr.Zero); amInterface.Scan(stream, out var result, out var provider); Logger.AntiMalware.Debug($"Scanned file '{file}' with {provider.DisplayName()}, and got '{result}'"); return ScanResultFromAmsiResult(result); } public ScanResult ScanData(byte[] data, string? contentName = null) { contentName ??= $"unknown_data_{Guid.NewGuid()}"; using var stream = new AmsiMemoryStream(contentName, data, IntPtr.Zero); amInterface.Scan(stream, out var result, out var provider); Logger.AntiMalware.Debug($"Scanned data named '{contentName}' with {provider.DisplayName()}, and got '{result}'"); return ScanResultFromAmsiResult(result); } } }