powershell-command.mjs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import childProcess from "node:child_process";
  2. import { mkdtemp, readFile, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. const POWERSHELL_COMMON_ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive"];
  6. const WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP = [
  7. // 首次模块导入会向 stderr 写进度 CLIXML;只静默进度,实际错误仍须拒绝更新。
  8. "$ProgressPreference='SilentlyContinue';",
  9. "$ErrorActionPreference='Stop';",
  10. "try{",
  11. "$zcodeSecurityModule=[IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Security','Microsoft.PowerShell.Security.psd1');",
  12. "Import-Module -Name $zcodeSecurityModule -Force -ErrorAction Stop;",
  13. "}catch{",
  14. "[Console]::Error.WriteLine(('Windows PowerShell Security module load failed: {0}' -f $_.Exception.Message));",
  15. "exit 26;",
  16. "};",
  17. ].join("");
  18. function encodeUtf8Value(value) {
  19. return Buffer.from(value, "utf8").toString("base64");
  20. }
  21. export function createEncodedPowerShellArgs(script, values = []) {
  22. // Windows PowerShell 5.1 会把普通 `-Command` 后续 argv 拼回命令文本,
  23. // 不会把它们注入 `$args`。动态值先单独编码,再放进 `-EncodedCommand`,同时避免
  24. // Program Files 空格、引号或分号被 PowerShell 二次解析成脚本内容。
  25. const valueBindings = values
  26. .map(
  27. (value, index) =>
  28. `$zcodeArg${index}=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodeUtf8Value(value)}'));`,
  29. )
  30. .join("");
  31. const encodedCommand = Buffer.from(`${valueBindings}${script}`, "utf16le").toString("base64");
  32. return [...POWERSHELL_COMMON_ARGS, "-EncodedCommand", encodedCommand];
  33. }
  34. export function escapePowerShellLiteral(value) {
  35. // PowerShell 将排版单引号也视为定界符,必须与 ASCII 单引号一样双写,防止路径变成代码。
  36. if (/[\0\r\n]/u.test(value)) {
  37. throw new Error("PowerShell path literal cannot contain NUL or newline characters");
  38. }
  39. return `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
  40. }
  41. export function createWindowsPowerShellSecurityArgs(script, values = []) {
  42. // 由 pwsh 启动的 Node 会继承 PowerShell 7 的 PSModulePath,随后再启动
  43. // Windows PowerShell 5.1 时可能错误发现不兼容的 Security 模块。直接从当前
  44. // powershell.exe 的 PSHOME 显式加载系统模块,避免把外部环境变量当作模块信任根。
  45. return createEncodedPowerShellArgs(`${WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP}${script}`, values);
  46. }
  47. export async function readWindowsAuthenticodeSignature(filePath) {
  48. const pathLiteral = escapePowerShellLiteral(filePath);
  49. const outputDir = await mkdtemp(join(tmpdir(), "zcode-signature-"));
  50. try {
  51. const outputPath = join(outputDir, "signature.json");
  52. // 受限语言模式会禁止路径解码和 Console 编码的 .NET 调用;专用查询只用 cmdlet,
  53. // 结果写入独立 UTF-8 文件,既保留中文签名者,也不改变其他 PowerShell 消费者。
  54. const script = [
  55. `$zcodeArg0=${pathLiteral};`,
  56. `$zcodeSignatureOutput=${escapePowerShellLiteral(outputPath)};`,
  57. "$ProgressPreference='SilentlyContinue';",
  58. "$ErrorActionPreference='Stop';",
  59. "try{",
  60. "$securityModule=Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1';",
  61. "Import-Module -Name $securityModule -Force -ErrorAction Stop;",
  62. "$signature=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  63. "@{status=[int]$signature.Status;subject=$signature.SignerCertificate.Subject}|ConvertTo-Json -Compress|Out-File -LiteralPath $zcodeSignatureOutput -Encoding utf8 -NoNewline;",
  64. "}catch{Write-Error ('Windows Authenticode query failed: ' + $_.Exception.Message) -ErrorAction Continue;exit 27};",
  65. ].join("");
  66. await new Promise((resolve, reject) => {
  67. childProcess.execFile(
  68. "powershell.exe",
  69. createEncodedPowerShellArgs(script),
  70. { encoding: "utf8", timeout: 30_000, windowsHide: true },
  71. (error, _stdout, stderr) => {
  72. if (error) reject(error);
  73. else if (stderr) reject(new Error(stderr));
  74. else resolve();
  75. },
  76. );
  77. });
  78. const output = await readFile(outputPath, "utf8");
  79. return JSON.parse(output.replace(/^\uFEFF/u, "").trim());
  80. } finally {
  81. await rm(outputDir, { recursive: true, force: true });
  82. }
  83. }
  84. export async function verifyWindowsAuthenticodeSignature(filePath) {
  85. const signature = await readWindowsAuthenticodeSignature(filePath);
  86. // 官方 HTTPS 清单与文件哈希决定发布授权;这里只检查 Windows 签名有效性。
  87. // 不固定证书 DN,避免换证后长期未升级的客户端只能依赖过渡版本。
  88. if (
  89. signature.status !== 0 ||
  90. typeof signature.subject !== "string" ||
  91. !signature.subject.trim()
  92. ) {
  93. return "Windows update requires a valid Authenticode signature";
  94. }
  95. return null;
  96. }