powershell-command.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import childProcess from "node:child_process";
  3. import { execFileSync } from "node:child_process";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { describe, expect, it, vi } from "vitest";
  7. import {
  8. verifyWindowsAuthenticodeSignature,
  9. createEncodedPowerShellArgs,
  10. createWindowsPowerShellSecurityArgs,
  11. escapePowerShellLiteral,
  12. } from "../scripts/powershell-command.mjs";
  13. function decodeCommand(args: string[]): string {
  14. expect(args.slice(0, 4)).toEqual(["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand"]);
  15. expect(args).toHaveLength(5);
  16. return Buffer.from(args[4]!, "base64").toString("utf16le");
  17. }
  18. describe("powershell-command", () => {
  19. it.each([
  20. ["a'b", "'a''b'"],
  21. ["a‘b", "'a‘‘b'"],
  22. ["a’b", "'a’’b'"],
  23. ["a‚b", "'a‚‚b'"],
  24. ["a‛b", "'a‛‛b'"],
  25. ])("PowerShell 路径字面量安全转义 %j", (value, expected) => {
  26. expect(escapePowerShellLiteral(value)).toBe(expected);
  27. });
  28. it.each(["a\u0000b", "a\nb", "a\rb"])("拒绝 PowerShell 路径控制符 %j", (value) => {
  29. expect(() => escapePowerShellLiteral(value)).toThrow("NUL or newline");
  30. });
  31. it("把动态值编码进脚本且不再依赖普通 -Command 的尾随参数", () => {
  32. const values = ["C:\\Program Files\\Z'Code;测试\\helper.exe", "value with spaces & symbols"];
  33. const args = createEncodedPowerShellArgs(
  34. "[Console]::Out.Write($zcodeArg0 + '|' + $zcodeArg1)",
  35. values,
  36. );
  37. const command = decodeCommand(args);
  38. expect(command).not.toContain("$args");
  39. for (const [index, value] of values.entries()) {
  40. expect(command).not.toContain(value);
  41. expect(command).toContain(`$zcodeArg${index}=`);
  42. expect(command).toContain(Buffer.from(value, "utf8").toString("base64"));
  43. }
  44. });
  45. it("从 PSHOME 显式加载 Windows PowerShell Security 模块", () => {
  46. const command = decodeCommand(
  47. createWindowsPowerShellSecurityArgs("[Console]::Out.Write('loaded')"),
  48. );
  49. expect(command).toContain(
  50. "[IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Security'",
  51. );
  52. expect(command).toContain("Import-Module -Name $zcodeSecurityModule -Force -ErrorAction Stop");
  53. expect(command).toContain("Windows PowerShell Security module load failed");
  54. expect(command).toContain("exit 26");
  55. expect(command).not.toContain("$env:PSModulePath");
  56. expect(command).toContain("$ProgressPreference='SilentlyContinue';");
  57. expect(command.indexOf("$ProgressPreference='SilentlyContinue'")).toBeLessThan(
  58. command.indexOf("Import-Module"),
  59. );
  60. });
  61. it.runIf(process.platform === "win32")(
  62. "Windows PowerShell 能还原带空格和脚本元字符的动态值",
  63. () => {
  64. const values = ["C:\\Program Files\\Z'Code;测试\\helper.exe", "value with spaces & symbols"];
  65. const output = execFileSync(
  66. "powershell.exe",
  67. createEncodedPowerShellArgs(
  68. "[Console]::Out.Write($zcodeArg0 + [Environment]::NewLine + $zcodeArg1)",
  69. values,
  70. ),
  71. { encoding: "utf8" },
  72. );
  73. expect(output.split(/\r?\n/)).toEqual(values);
  74. },
  75. );
  76. it.runIf(process.platform === "win32")(
  77. "Windows PowerShell 在 PSModulePath 被污染时仍加载系统 Security 模块",
  78. () => {
  79. const output = execFileSync(
  80. "powershell.exe",
  81. createWindowsPowerShellSecurityArgs(
  82. [
  83. "$signature=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  84. "[Console]::Out.Write($null -ne $signature)",
  85. ].join(""),
  86. [process.execPath],
  87. ),
  88. {
  89. encoding: "utf8",
  90. env: { ...process.env, PSModulePath: "Z:\\zcode-invalid-psmodulepath" },
  91. },
  92. );
  93. expect(output).toBe("True");
  94. },
  95. );
  96. });
  97. // 工程适配器回归:只替换系统进程,仍执行真实临时文件读取与清理。
  98. function mockSignatureQuery(
  99. result: unknown,
  100. options: { stderr?: string; error?: Error; output?: string } = {},
  101. ) {
  102. return vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  103. const command = decodeCommand(args[1] as string[]);
  104. const output = command
  105. .match(
  106. /\$zcodeSignatureOutput='((?:[^'\u2018\u2019\u201A\u201B]|(['\u2018\u2019\u201A\u201B])\2)*)';/,
  107. )?.[1]
  108. ?.replace(/(['\u2018\u2019\u201A\u201B])\1/g, "$1");
  109. const callback = args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void;
  110. if (options.error) {
  111. callback(options.error, "", "");
  112. } else if (output && options.output !== "missing") {
  113. void writeFile(output, options.output ?? `\uFEFF${JSON.stringify(result)}`, "utf8").then(
  114. () => callback(null, "", options.stderr ?? ""),
  115. (error) => callback(error, "", ""),
  116. );
  117. } else {
  118. callback(null, "", options.stderr ?? "");
  119. }
  120. return {} as childProcess.ChildProcess;
  121. });
  122. }
  123. describe("Windows Authenticode 有效性校验", () => {
  124. it.runIf(process.platform === "win32")(
  125. "原生签名查询不会把首次模块加载进度误判为错误",
  126. async () => {
  127. const file = join(
  128. process.env.SystemRoot ?? "C:\\Windows",
  129. "System32",
  130. "WindowsPowerShell",
  131. "v1.0",
  132. "powershell.exe",
  133. );
  134. expect(await verifyWindowsAuthenticodeSignature(file)).toBeNull();
  135. },
  136. );
  137. it.each(["CN=Original Publisher, O=Original, C=US", "CN=换发证书, O=测试公司, C=CN"])(
  138. "有效签名不受发布者 DN 限制:%s",
  139. async (subject) => {
  140. const spy = mockSignatureQuery({ status: 0, subject });
  141. try {
  142. expect(
  143. await verifyWindowsAuthenticodeSignature("C:\\Program Files\\Example';&.exe"),
  144. ).toBeNull();
  145. const command = decodeCommand(spy.mock.calls[0]![1] as string[]);
  146. expect(command).toContain("Get-AuthenticodeSignature -LiteralPath $zcodeArg0");
  147. expect(command).toContain("Example'';&.exe");
  148. expect(command).not.toMatch(/\[(?:Console|Convert|Text\.|IO\.)/);
  149. const output = command
  150. .match(
  151. /\$zcodeSignatureOutput='((?:[^'\u2018\u2019\u201A\u201B]|(['\u2018\u2019\u201A\u201B])\2)*)';/,
  152. )![1]!
  153. .replace(/''/g, "'");
  154. await expect(readFile(output)).rejects.toMatchObject({ code: "ENOENT" });
  155. } finally {
  156. spy.mockRestore();
  157. }
  158. },
  159. );
  160. it.each([
  161. { status: 2, subject: "CN=Unsigned" },
  162. { status: 1, subject: "CN=Tampered" },
  163. { status: 0, subject: "" },
  164. { status: "0", subject: "CN=Malformed" },
  165. ])("拒绝无效签名或畸形结果:%j", async (result) => {
  166. const spy = mockSignatureQuery(result);
  167. try {
  168. expect(await verifyWindowsAuthenticodeSignature("C:\\example.exe")).not.toBeNull();
  169. } finally {
  170. spy.mockRestore();
  171. }
  172. });
  173. it.each([
  174. { error: new Error("PowerShell unavailable") },
  175. { error: Object.assign(new Error("PowerShell timed out"), { killed: true }) },
  176. { stderr: "actual module error" },
  177. { output: "missing" },
  178. { output: "not JSON" },
  179. ])("系统查询、超时或输出失败不放行:%j", async (options) => {
  180. const spy = mockSignatureQuery({ status: 0, subject: "CN=Example" }, options);
  181. try {
  182. await expect(verifyWindowsAuthenticodeSignature("C:\\example.exe")).rejects.toThrow();
  183. const command = decodeCommand(spy.mock.calls[0]![1] as string[]);
  184. const output = command
  185. .match(
  186. /\$zcodeSignatureOutput='((?:[^'\u2018\u2019\u201A\u201B]|(['\u2018\u2019\u201A\u201B])\2)*)';/,
  187. )![1]!
  188. .replace(/''/g, "'");
  189. await expect(readFile(output)).rejects.toMatchObject({ code: "ENOENT" });
  190. } finally {
  191. spy.mockRestore();
  192. }
  193. });
  194. it.runIf(process.platform === "win32").each(["FullLanguage", "ConstrainedLanguage"])(
  195. "%s 下真实查询保留安全边界和特殊字符路径",
  196. async (mode) => {
  197. const original = childProcess.execFile;
  198. const spy = vi.spyOn(childProcess, "execFile").mockImplementation((...args: unknown[]) => {
  199. const command = decodeCommand(args[1] as string[]);
  200. const encoded = Buffer.from(
  201. `$ExecutionContext.SessionState.LanguageMode='${mode}';${command}`,
  202. "utf16le",
  203. ).toString("base64");
  204. return Reflect.apply(original, childProcess, [
  205. args[0],
  206. [...(args[1] as string[]).slice(0, -1), encoded],
  207. { ...(args[2] as object), env: { ...process.env, PSModulePath: "Z:\\invalid-modules" } },
  208. args[3],
  209. ]);
  210. });
  211. const unicodeTemp = await mkdtemp(join(tmpdir(), "signature-temp-‘’‚‛-"));
  212. const root = await mkdtemp(join(unicodeTemp, "signature-测试'‘’‚‛-"));
  213. const originalTemp = process.env.TEMP;
  214. const originalTmp = process.env.TMP;
  215. try {
  216. process.env.TEMP = unicodeTemp;
  217. process.env.TMP = unicodeTemp;
  218. const unsigned = join(root, "unsigned'‘’‚‛;&.exe");
  219. await writeFile(unsigned, "not a signed executable");
  220. expect(await verifyWindowsAuthenticodeSignature(unsigned)).not.toBeNull();
  221. const signed = join(
  222. process.env.SystemRoot ?? "C:\\Windows",
  223. "System32",
  224. "WindowsPowerShell",
  225. "v1.0",
  226. "powershell.exe",
  227. );
  228. const signedCopy = join(root, "signed'‘’‚‛;&.exe");
  229. await copyFile(signed, signedCopy);
  230. expect(await verifyWindowsAuthenticodeSignature(signedCopy)).toBeNull();
  231. expect(await verifyWindowsAuthenticodeSignature(signed)).toBeNull();
  232. } finally {
  233. spy.mockRestore();
  234. if (originalTemp === undefined) delete process.env.TEMP;
  235. else process.env.TEMP = originalTemp;
  236. if (originalTmp === undefined) delete process.env.TMP;
  237. else process.env.TMP = originalTmp;
  238. await rm(unicodeTemp, { recursive: true, force: true });
  239. }
  240. },
  241. 30_000,
  242. );
  243. });