powershell-command.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import childProcess from "node:child_process";
  2. import { execFileSync } from "node:child_process";
  3. import { join } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. verifyWindowsAuthenticodeSignature,
  7. createEncodedPowerShellArgs,
  8. createWindowsPowerShellSecurityArgs,
  9. } from "../scripts/powershell-command.mjs";
  10. function decodeCommand(args: string[]): string {
  11. expect(args.slice(0, 4)).toEqual(["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand"]);
  12. expect(args).toHaveLength(5);
  13. return Buffer.from(args[4]!, "base64").toString("utf16le");
  14. }
  15. describe("powershell-command", () => {
  16. it("把动态值编码进脚本且不再依赖普通 -Command 的尾随参数", () => {
  17. const values = ["C:\\Program Files\\Z'Code;测试\\helper.exe", "value with spaces & symbols"];
  18. const args = createEncodedPowerShellArgs(
  19. "[Console]::Out.Write($zcodeArg0 + '|' + $zcodeArg1)",
  20. values,
  21. );
  22. const command = decodeCommand(args);
  23. expect(command).not.toContain("$args");
  24. for (const [index, value] of values.entries()) {
  25. expect(command).not.toContain(value);
  26. expect(command).toContain(`$zcodeArg${index}=`);
  27. expect(command).toContain(Buffer.from(value, "utf8").toString("base64"));
  28. }
  29. });
  30. it("从 PSHOME 显式加载 Windows PowerShell Security 模块", () => {
  31. const command = decodeCommand(
  32. createWindowsPowerShellSecurityArgs("[Console]::Out.Write('loaded')"),
  33. );
  34. expect(command).toContain(
  35. "[IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Security'",
  36. );
  37. expect(command).toContain("Import-Module -Name $zcodeSecurityModule -Force -ErrorAction Stop");
  38. expect(command).toContain("Windows PowerShell Security module load failed");
  39. expect(command).toContain("exit 26");
  40. expect(command).not.toContain("$env:PSModulePath");
  41. expect(command).toContain("$ProgressPreference='SilentlyContinue';");
  42. expect(command.indexOf("$ProgressPreference='SilentlyContinue'")).toBeLessThan(
  43. command.indexOf("Import-Module"),
  44. );
  45. });
  46. it.runIf(process.platform === "win32")(
  47. "Windows PowerShell 能还原带空格和脚本元字符的动态值",
  48. () => {
  49. const values = ["C:\\Program Files\\Z'Code;测试\\helper.exe", "value with spaces & symbols"];
  50. const output = execFileSync(
  51. "powershell.exe",
  52. createEncodedPowerShellArgs(
  53. "[Console]::Out.Write($zcodeArg0 + [Environment]::NewLine + $zcodeArg1)",
  54. values,
  55. ),
  56. { encoding: "utf8" },
  57. );
  58. expect(output.split(/\r?\n/)).toEqual(values);
  59. },
  60. );
  61. it.runIf(process.platform === "win32")(
  62. "Windows PowerShell 在 PSModulePath 被污染时仍加载系统 Security 模块",
  63. () => {
  64. const output = execFileSync(
  65. "powershell.exe",
  66. createWindowsPowerShellSecurityArgs(
  67. [
  68. "$signature=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  69. "[Console]::Out.Write($null -ne $signature)",
  70. ].join(""),
  71. [process.execPath],
  72. ),
  73. {
  74. encoding: "utf8",
  75. env: { ...process.env, PSModulePath: "Z:\\zcode-invalid-psmodulepath" },
  76. },
  77. );
  78. expect(output).toBe("True");
  79. },
  80. );
  81. });
  82. // 工程适配器回归:仅替换系统进程,真实执行编码、结果解析及失败传播。
  83. describe("Windows Authenticode 有效性校验", () => {
  84. it.runIf(process.platform === "win32")(
  85. "原生签名查询不会把首次模块加载进度误判为错误",
  86. async () => {
  87. const file = join(
  88. process.env.SystemRoot ?? "C:\\Windows",
  89. "System32",
  90. "WindowsPowerShell",
  91. "v1.0",
  92. "powershell.exe",
  93. );
  94. expect(await verifyWindowsAuthenticodeSignature(file)).toBeNull();
  95. },
  96. );
  97. it.each(["CN=Original Publisher, O=Original, C=US", "CN=Renewed Publisher, O=Changed, C=GB"])(
  98. "有效签名不受发布者 DN 限制:%s",
  99. async (subject) => {
  100. const spy = vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  101. const callback = args.at(-1) as (
  102. error: Error | null,
  103. stdout: string,
  104. stderr: string,
  105. ) => void;
  106. callback(null, JSON.stringify({ status: 0, subject }), "");
  107. return {} as childProcess.ChildProcess;
  108. });
  109. try {
  110. expect(
  111. await verifyWindowsAuthenticodeSignature("C:\\Program Files\\Example';&.exe"),
  112. ).toBeNull();
  113. const args = spy.mock.calls[0]![1] as string[];
  114. const command = decodeCommand(args);
  115. expect(command).toContain("Get-AuthenticodeSignature -LiteralPath $zcodeArg0");
  116. expect(command).not.toContain("Example';&.exe");
  117. } finally {
  118. spy.mockRestore();
  119. }
  120. },
  121. );
  122. it.each([
  123. { status: 2, subject: "CN=Unsigned" },
  124. { status: 1, subject: "CN=Tampered" },
  125. { status: 0, subject: "" },
  126. { status: "0", subject: "CN=Malformed" },
  127. ])("拒绝无效签名或畸形结果:%j", async (result) => {
  128. const spy = vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  129. (args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void)(
  130. null,
  131. JSON.stringify(result),
  132. "",
  133. );
  134. return {} as childProcess.ChildProcess;
  135. });
  136. try {
  137. expect(await verifyWindowsAuthenticodeSignature("C:\\example.exe")).not.toBeNull();
  138. } finally {
  139. spy.mockRestore();
  140. }
  141. });
  142. it("系统查询失败不放行", async () => {
  143. const spy = vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  144. (args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void)(
  145. new Error("PowerShell unavailable"),
  146. "",
  147. "",
  148. );
  149. return {} as childProcess.ChildProcess;
  150. });
  151. try {
  152. await expect(verifyWindowsAuthenticodeSignature("C:\\example.exe")).rejects.toThrow(
  153. "PowerShell unavailable",
  154. );
  155. } finally {
  156. spy.mockRestore();
  157. }
  158. });
  159. it("实际 stderr 仍拒绝,不能把进度静默扩大为忽略错误", async () => {
  160. const spy = vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  161. (args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void)(
  162. null,
  163. JSON.stringify({ status: 0, subject: "CN=Example" }),
  164. "actual module error",
  165. );
  166. return {} as childProcess.ChildProcess;
  167. });
  168. try {
  169. await expect(verifyWindowsAuthenticodeSignature("C:/example.exe")).rejects.toThrow(
  170. "actual module error",
  171. );
  172. } finally {
  173. spy.mockRestore();
  174. }
  175. });
  176. });