public IMalwareScanningResult Scan(Func <Stream> getFileFunc, string fileName = null) { if (this.disposed) { throw new ObjectDisposedException("AMSI context is closed."); } AMSI_RESULT result; using (Stream s = getFileFunc()) { if (s.Length > MaxSizeOfContentToBeScanned) { throw new MalwareScanningException(string.Format( "Content is too big to be scanned ({0} bytes).The maximum allowed size is {1} bytes)", s.Length, MaxSizeOfContentToBeScanned)); } using (MemoryStream ms = new MemoryStream()) { s.CopyTo(ms); var contentLength = (uint)s.Length; byte[] contentBuffer = ms.ToArray(); fileName = fileName ?? "file-" + Guid.NewGuid(); AmsiNativeMethods.AmsiScanBuffer(this.contextHandle, contentBuffer, contentLength, fileName, IntPtr.Zero, out result); } } return(new AmsiMalwareScanningResult(result)); }
public AmsiMalwareScanner() { AmsiContextSafeHandle handle; int pInvokeResult = AmsiNativeMethods.AmsiInitialize(AppIdentifier, out handle); if (pInvokeResult != 0 || handle.IsInvalid) { throw new MalwareScanningException( "Failed to initialize AMSI context. For more details see inner exception.", new Win32Exception(Marshal.GetLastWin32Error())); } this.contextHandle = handle; }
protected override bool ReleaseHandle() { AmsiNativeMethods.AmsiUninitialize(this.handle); return(true); }