WindowsDefenderScanService.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using Masuit.Tools.Files;
  7. using Masuit.Tools.Systems;
  8. namespace Masuit.Tools.Win32.AntiVirus;
  9. public static class WindowsDefenderScanService
  10. {
  11. static WindowsDefenderScanService()
  12. {
  13. if (!Directory.Exists(SystemParameter.WindowsDefenderPath))
  14. {
  15. throw new PlatformNotSupportedException("Windows Defender not found");
  16. }
  17. if (!File.Exists($"{SystemParameter.WindowsDefenderPath}\\{SystemParameter.WindowsDefenderExeName}"))
  18. {
  19. throw new PlatformNotSupportedException("Windows Defender not found");
  20. }
  21. }
  22. /// <summary>
  23. /// 扫描文件流
  24. /// </summary>
  25. /// <param name="filePath"></param>
  26. public static ScanResult ScanStream(Stream stream)
  27. {
  28. var temp = Path.Combine(Environment.GetEnvironmentVariable("temp"), SnowFlake.NewId);
  29. stream.SaveFile(temp);
  30. if (stream.CanSeek)
  31. {
  32. stream.Position = 0;
  33. }
  34. var result = ScanFile(temp);
  35. try
  36. {
  37. File.Delete(temp);
  38. }
  39. catch (Exception)
  40. {
  41. // ignored
  42. }
  43. return result;
  44. }
  45. /// <summary>
  46. /// 扫描文件
  47. /// </summary>
  48. /// <param name="filePath"></param>
  49. public static ScanResult ScanFile(string filePath)
  50. {
  51. if (!File.Exists(filePath))
  52. {
  53. throw new FileNotFoundException();
  54. }
  55. try
  56. {
  57. //Scanning xxxxx found 1 threats.
  58. //Scanning xxxxx found no threats.
  59. var result = RunScanCommand(filePath);
  60. if (result.Contains("found no threats"))
  61. {
  62. return new ScanResult
  63. {
  64. Result = ResultCode.NotDetected,
  65. };
  66. }
  67. return new ScanResult
  68. {
  69. Result = ResultCode.Detected,
  70. };
  71. }
  72. catch (Exception ex)
  73. {
  74. return new ScanResult
  75. {
  76. Result = ResultCode.Exception,
  77. Msg = ex.Message
  78. };
  79. }
  80. }
  81. /// <summary>
  82. /// 扫描文件夹(不支持递文件夹嵌套文件夹的扫描)
  83. /// </summary>
  84. /// <param name="directoryPath"></param>
  85. /// <returns>如有威胁文件,只返回文件夹中有威胁的文件</returns>
  86. public static ScanResult ScanDirectory(string directoryPath)
  87. {
  88. if (!Directory.Exists(directoryPath))
  89. {
  90. throw new DirectoryNotFoundException();
  91. }
  92. try
  93. {
  94. var files = Directory.GetFiles(directoryPath);
  95. //文件夹扫描
  96. var result = RunScanCommand(directoryPath);
  97. if (result.Contains("found no threats"))
  98. {
  99. return new ScanResult
  100. {
  101. Result = ResultCode.NotDetected,
  102. };
  103. }
  104. if (result.Contains("CmdTool: Failed"))
  105. {
  106. return new ScanResult
  107. {
  108. Result = ResultCode.Exception,
  109. Msg = result
  110. };
  111. }
  112. result = result.ToLower();
  113. var detectedFile = (from file in files
  114. let filePath = $"{file}\r\n"
  115. where result.Contains(filePath.ToLower())
  116. select file.Replace(directoryPath, "").Replace("\\", "")).ToList();
  117. //解析文件,找到有威胁的文件
  118. return new ScanResult
  119. {
  120. Result = ResultCode.Detected,
  121. Msg = string.Join(";", detectedFile)
  122. };
  123. }
  124. catch (Exception ex)
  125. {
  126. return new ScanResult
  127. {
  128. Result = ResultCode.Exception,
  129. Msg = ex.Message
  130. };
  131. }
  132. }
  133. /// <summary>
  134. /// 运行命令
  135. /// </summary>
  136. /// <param name="path"></param>
  137. /// <returns></returns>
  138. private static string RunScanCommand(string path)
  139. {
  140. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  141. {
  142. throw new PlatformNotSupportedException();
  143. }
  144. var proc = new Process();
  145. try
  146. {
  147. proc.StartInfo.FileName = "cmd.exe";
  148. proc.StartInfo.UseShellExecute = false;
  149. proc.StartInfo.RedirectStandardInput = true;
  150. proc.StartInfo.RedirectStandardOutput = true;
  151. proc.StartInfo.RedirectStandardError = true;
  152. proc.StartInfo.CreateNoWindow = true;
  153. proc.Start();
  154. var command = $"\"{SystemParameter.WindowsDefenderPath}\\{SystemParameter.WindowsDefenderExeName}\" -Scan -ScanType 3 -File \"{path}\" -DisableRemediation";
  155. proc.StandardInput.WriteLine(command);
  156. proc.StandardInput.WriteLine("exit");
  157. while (!proc.HasExited)
  158. {
  159. proc.WaitForExit(1000);
  160. }
  161. return proc.StandardOutput.ReadToEnd();
  162. }
  163. catch (Exception ex)
  164. {
  165. throw new WindowsDefenderScanException();
  166. }
  167. finally
  168. {
  169. proc.Close();
  170. proc.Dispose();
  171. }
  172. }
  173. }