{"version":3,"file":"windowsExecutableCodeSignatureVerifier.js","sourceRoot":"","sources":["../src/windowsExecutableCodeSignatureVerifier.ts"],"names":[],"mappings":";;AAwBA,0CA2EC;AAnGD,+DAA8C;AAC9C,iDAAuE;AACvE,yBAAwB;AAExB,6BAA4B;AAE5B,SAAS,qBAAqB,CAAC,OAAe,EAAE,OAAgB;IAC9D,oEAAoE;IACpE,oEAAoE;IACpE,wGAAwG;IACxG,6JAA6J;IAC7J,4FAA4F;IAC5F,MAAM,UAAU,GAAG,wDAAwD,CAAA;IAC3E,MAAM,IAAI,GAAG,CAAC,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IAC3F,MAAM,OAAO,GAAoB;QAC/B,KAAK,EAAE,IAAI;QACX,OAAO;KACR,CAAA;IACD,OAAO,CAAC,UAAU,EAAE,IAAI,EAAE,OAAO,CAAU,CAAA;AAC7C,CAAC;AAED,8DAA8D;AAC9D,kJAAkJ;AAClJ,kEAAkE;AAClE,SAAgB,eAAe,CAAC,cAA6B,EAAE,uBAA+B,EAAE,MAAc;IAC5G,OAAO,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpD,6EAA6E;QAC7E,oDAAoD;QACpD,EAAE;QACF,uCAAuC;QACvC,gBAAgB;QAChB,oEAAoE;QACpE,MAAM;QACN,+FAA+F;QAC/F,wCAAwC;QACxC,EAAE;QACF,iCAAiC;QACjC,2HAA2H;QAC3H,0EAA0E;QAC1E,sEAAsE;QACtE,EAAE;QACF,0FAA0F;QAC1F,kFAAkF;QAClF,sEAAsE;QACtE,MAAM,cAAc,GAAG,uBAAuB,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAClE,MAAM,CAAC,IAAI,CAAC,uBAAuB,cAAc,EAAE,CAAC,CAAA;QAEpD,IAAA,wBAAQ,EAAC,GAAG,qBAAqB,CAAC,4CAA4C,cAAc,+BAA+B,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C,IAAI,KAAK,CAAC,qDAAqD,MAAM,uDAAuD,CAAC,CAAC,CAAA;IACvI,CAAC;AACH,CAAC;AAED,SAAS,SAAS;IAChB,MAAM,UAAU,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAC/B,OAAO,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;AACrE,CAAC","sourcesContent":["import { parseDn } from \"builder-util-runtime\"\nimport { execFile, execFileSync, ExecFileOptions } from \"child_process\"\nimport * as os from \"os\"\nimport { Logger } from \"./types\"\nimport * as path from \"path\"\n\nfunction preparePowerShellExec(command: string, timeout?: number) {\n  // https://github.com/electron-userland/electron-builder/issues/2421\n  // https://github.com/electron-userland/electron-builder/issues/2535\n  // Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127\n  // semicolon wont terminate the set command and run chcp thus leading to verification errors on certificats with special chars like german umlauts, so rather\n  //   join commands using & https://github.com/electron-userland/electron-builder/issues/8162\n  const executable = `set \"PSModulePath=\" & chcp 65001 >NUL & powershell.exe`\n  const args = [\"-NoProfile\", \"-NonInteractive\", \"-InputFormat\", \"None\", \"-Command\", command]\n  const options: ExecFileOptions = {\n    shell: true,\n    timeout,\n  }\n  return [executable, args, options] as const\n}\n\n// $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\nexport function verifySignature(publisherNames: Array<string>, unescapedTempUpdateFile: string, logger: Logger): Promise<string | null> {\n  return new Promise<string | null>((resolve, reject) => {\n    // Escape quotes and backticks in filenames to prevent user from breaking the\n    // arguments and perform a remote command injection.\n    //\n    // Consider example powershell command:\n    // ```powershell\n    // Get-AuthenticodeSignature 'C:\\\\path\\\\my-bad-';calc;'filename.exe'\n    // ```\n    // The above would work expected and find the file name, however, it will also execute `;calc;`\n    // command and start the calculator app.\n    //\n    // From Powershell quoting rules:\n    // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7\n    // * Double quotes `\"` are treated literally within single-quoted strings;\n    // * Single quotes can be escaped by doubling them: 'don''t' -> don't;\n    //\n    // Also note that at this point the file has already been written to the disk, thus we are\n    // guaranteed that the path will not contain any illegal characters like <>:\"/\\|?*\n    // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file\n    const tempUpdateFile = unescapedTempUpdateFile.replace(/'/g, \"''\")\n    logger.info(`Verifying signature ${tempUpdateFile}`)\n\n    execFile(...preparePowerShellExec(`\"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress\"`, 20 * 1000), (error, stdout, stderr) => {\n      try {\n        if (error != null || stderr) {\n          handleError(logger, error, stderr, reject)\n          resolve(null)\n          return\n        }\n        const data = parseOut(stdout)\n        if (data.Status === 0) {\n          try {\n            const normlaizedUpdateFilePath = path.normalize(data.Path)\n            const normalizedTempUpdateFile = path.normalize(unescapedTempUpdateFile)\n            logger.info(`LiteralPath: ${normlaizedUpdateFilePath}. Update Path: ${normalizedTempUpdateFile}`)\n            if (normlaizedUpdateFilePath !== normalizedTempUpdateFile) {\n              handleError(logger, new Error(`LiteralPath of ${normlaizedUpdateFilePath} is different than ${normalizedTempUpdateFile}`), stderr, reject)\n              resolve(null)\n              return\n            }\n          } catch (error: any) {\n            logger.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${error.message ?? error.stack}`)\n          }\n          const subject = parseDn(data.SignerCertificate.Subject)\n          let match = false\n          for (const name of publisherNames) {\n            const dn = parseDn(name)\n            if (dn.size) {\n              // if we have a full DN, compare all values\n              const allKeys = Array.from(dn.keys())\n              match = allKeys.every(key => {\n                return dn.get(key) === subject.get(key)\n              })\n            } else if (name === subject.get(\"CN\")!) {\n              logger.warn(`Signature validated using only CN ${name}. Please add your full Distinguished Name (DN) to publisherNames configuration`)\n              match = true\n            }\n            if (match) {\n              resolve(null)\n              return\n            }\n          }\n        }\n\n        const result = `publisherNames: ${publisherNames.join(\" | \")}, raw info: ` + JSON.stringify(data, (name, value) => (name === \"RawData\" ? undefined : value), 2)\n        logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`)\n        resolve(result)\n      } catch (e: any) {\n        handleError(logger, e, null, reject)\n        resolve(null)\n        return\n      }\n    })\n  })\n}\n\nfunction parseOut(out: string): any {\n  const data = JSON.parse(out)\n  delete data.PrivateKey\n  delete data.IsOSBinary\n  delete data.SignatureType\n  const signerCertificate = data.SignerCertificate\n  if (signerCertificate != null) {\n    delete signerCertificate.Archived\n    delete signerCertificate.Extensions\n    delete signerCertificate.Handle\n    delete signerCertificate.HasPrivateKey\n    // duplicates data.SignerCertificate (contains RawData)\n    delete signerCertificate.SubjectName\n  }\n  return data\n}\n\nfunction handleError(logger: Logger, error: Error | null, stderr: string | null, reject: (reason: any) => void): void {\n  if (isOldWin6()) {\n    logger.warn(\n      `Cannot execute Get-AuthenticodeSignature: ${error || stderr}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n    )\n    return\n  }\n\n  try {\n    execFileSync(...preparePowerShellExec(\"ConvertTo-Json test\", 10 * 1000))\n  } catch (testError: any) {\n    logger.warn(\n      `Cannot execute ConvertTo-Json: ${testError.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n    )\n    return\n  }\n\n  if (error != null) {\n    reject(error)\n  }\n\n  if (stderr) {\n    reject(new Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${stderr}. Failing signature validation due to unknown stderr.`))\n  }\n}\n\nfunction isOldWin6(): boolean {\n  const winVersion = os.release()\n  return winVersion.startsWith(\"6.\") && !winVersion.startsWith(\"6.3\")\n}\n"]}