| 1 | |
| 2 | import { createHash } from 'node:crypto'; |
| 3 | import { execFileSync, spawn } from 'node:child_process'; |
| 4 | import { copyFile, mkdir, mkdtemp, readFile, rm, stat, writeFile, access, open } from 'node:fs/promises'; |
| 5 | import { tmpdir } from 'node:os'; |
| 6 | import { basename, dirname, join, resolve } from 'node:path'; |
| 7 | import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 8 | import { createInterface } from 'node:readline/promises'; |
| 9 | import { Writable } from 'node:stream'; |
| 10 | |
| 11 | const root = fileURLToPath(new URL('../', import.meta.url)); |
| 12 | const pin = JSON.parse(await readFile(new URL('../packaging/windows/signing.json', import.meta.url), 'utf8')); |
| 13 | const configPath = 'conf/code_sign_tool.properties'; |
| 14 | const secretNames = ['CAGE_ESIGNER_PASSWORD', 'CAGE_ESIGNER_TOTP_SECRET']; |
| 15 | const providerCodes = ['server_error', 'invalid_grant', 'invalid_client', 'access_denied', 'unauthorized', 'invalid_request', 'invalid_otp', 'malware_detected']; |
| 16 | const rejectedOrUncertain = /timeout|timed out|abort|cancel|invalid_grant|invalid_client|access_denied|unauthorized|(?:otp|totp|authentication|authorization|credential|password)[^\n]*(?:invalid|expired|failed|rejected)|(?:invalid|expired|failed|rejected)[^\n]*(?:otp|totp|authentication|credential|password)/i; |
| 17 | const hash = bytes => createHash('sha256').update(bytes).digest('hex'); |
| 18 | const toolDirectory = () => resolve(process.env.CAGE_ESIGNER_TOOL_DIR || join(root, '_output/esigner', `CodeSignTool-v${pin.version}`)); |
| 19 | |
| 20 | export function javaArgument(value) { |
| 21 | |
| 22 | if (/[\r\n\0]/u.test(value)) throw new Error('Signing arguments must not contain newlines or NUL.'); |
| 23 | return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`; |
| 24 | } |
| 25 | |
| 26 | export function redact(text, secrets) { |
| 27 | for (const secret of secrets.filter(Boolean).sort((a, b) => b.length - a.length)) text = text.replaceAll(secret, '[redacted]'); |
| 28 | return text; |
| 29 | } |
| 30 | |
| 31 | export async function verifyTool(directory) { |
| 32 | for (const [name, digest] of [[pin.jar, pin.jarSHA256], [configPath, pin.configSHA256]]) { |
| 33 | if (hash(await readFile(join(directory, name))) !== digest) throw new Error(`CodeSignTool checksum mismatch: ${name}`); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | async function installTool() { |
| 38 | const directory = toolDirectory(); |
| 39 | try { await verifyTool(directory); return directory; } |
| 40 | catch (error) { if (error.code !== 'ENOENT') throw error; } |
| 41 | await mkdir(dirname(directory), { recursive: true }); |
| 42 | const temp = await mkdtemp(join(dirname(directory), 'download-')); |
| 43 | try { |
| 44 | const archive = join(temp, 'CodeSignTool.zip'); |
| 45 | execFileSync(process.platform === 'win32' ? 'curl.exe' : 'curl', |
| 46 | ['--fail', '--location', '--silent', '--show-error', '--max-time', '180', '--output', archive, pin.url], { stdio: 'inherit' }); |
| 47 | if (hash(await readFile(archive)) !== pin.archiveSHA256) throw new Error('CodeSignTool ZIP checksum mismatch. Review a new vendor version before changing the pin.'); |
| 48 | const extracted = join(temp, 'tool'); |
| 49 | await mkdir(extracted); |
| 50 | execFileSync('tar', ['-xf', archive, '-C', extracted]); |
| 51 | await verifyTool(extracted); |
| 52 | |
| 53 | for (const name of [pin.jar, configPath]) { |
| 54 | await mkdir(dirname(join(directory, name)), { recursive: true }); |
| 55 | await copyFile(join(extracted, name), join(directory, name)); |
| 56 | } |
| 57 | await verifyTool(directory); |
| 58 | return directory; |
| 59 | } finally { await rm(temp, { recursive: true, force: true }); } |
| 60 | } |
| 61 | |
| 62 | async function prompt(label, hidden = false, signal) { |
| 63 | if (!process.stdin.isTTY) throw new Error(`Missing ${label}. Run this command in your own terminal, or configure the signing environment secrets.`); |
| 64 | const sink = new Writable({ write(_chunk, _encoding, callback) { callback(); } }); |
| 65 | const rl = createInterface({ input: process.stdin, output: hidden ? sink : process.stdout, terminal: true }); |
| 66 | const controller = new AbortController(); |
| 67 | const abort = () => controller.abort(); |
| 68 | rl.once('SIGINT', abort); |
| 69 | signal?.addEventListener('abort', abort, { once: true }); |
| 70 | try { |
| 71 | if (signal?.aborted) controller.abort(); |
| 72 | if (hidden) process.stdout.write(`${label}: `); |
| 73 | return await rl.question(hidden ? '' : `${label}: `, { signal: controller.signal }); |
| 74 | } finally { |
| 75 | signal?.removeEventListener('abort', abort); |
| 76 | rl.close(); |
| 77 | if (hidden) process.stdout.write('\n'); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | |
| 82 | export async function invokeJava({ java = 'java', jar, config, arguments: args, otp, secrets = [] }) { |
| 83 | const temp = await mkdtemp(join(tmpdir(), 'cage-esigner-')); |
| 84 | let child; |
| 85 | const controller = new AbortController(); |
| 86 | const knownSecrets = [...secrets]; |
| 87 | try { |
| 88 | if (process.platform !== 'win32') await (await import('node:fs/promises')).chmod(temp, 0o700); |
| 89 | await mkdir(join(temp, 'conf')); |
| 90 | await copyFile(config, join(temp, configPath)); |
| 91 | const argumentFile = join(temp, 'java.args'); |
| 92 | await writeFile(argumentFile, ['-Xmx2048m', '-jar', resolve(jar), ...args].map(javaArgument).join('\n'), { mode: 0o600, flag: 'wx' }); |
| 93 | const env = { ...process.env }; |
| 94 | for (const name of secretNames) delete env[name]; |
| 95 | |
| 96 | child = spawn(java, [`@${argumentFile}`], { cwd: temp, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }); |
| 97 | child.stdin.on('error', () => {}); |
| 98 | let stdout = '', stderr = '', otpRequested = false, otpError; |
| 99 | let otpTask = Promise.resolve(); |
| 100 | child.stdout.on('data', chunk => { |
| 101 | stdout += chunk.toString(); |
| 102 | if (!otpRequested && stdout.includes('Enter the OTP')) { |
| 103 | otpRequested = true; |
| 104 | otpTask = (async () => { |
| 105 | try { |
| 106 | const value = (await otp(controller.signal)).trim(); |
| 107 | if (!/^\d{6}$/u.test(value)) throw new Error('The authenticator code must contain six digits.'); |
| 108 | knownSecrets.push(value); |
| 109 | child.stdin.end(`${value}\n`); |
| 110 | } catch (error) { otpError = error; child.kill(); } |
| 111 | })(); |
| 112 | } |
| 113 | }); |
| 114 | child.stderr.on('data', chunk => { stderr += chunk.toString(); }); |
| 115 | |
| 116 | const stop = () => { controller.abort(); child.kill(); }; |
| 117 | const timeout = setTimeout(stop, 15 * 60 * 1000); |
| 118 | process.once('SIGINT', stop); |
| 119 | process.once('SIGTERM', stop); |
| 120 | let code; |
| 121 | try { |
| 122 | code = await new Promise((done, reject) => { child.once('error', reject); child.once('close', done); }); |
| 123 | controller.abort(); |
| 124 | await otpTask; |
| 125 | } finally { clearTimeout(timeout); process.off('SIGINT', stop); process.off('SIGTERM', stop); } |
| 126 | if (otpError) throw otpError; |
| 127 | const output = redact(`${stdout}\n${stderr}`, knownSecrets); |
| 128 | if (code !== 0 || /\b(?:Error:|Exception|Missing required option|Unmatched argument)/u.test(output)) { |
| 129 | let privateLog = ''; |
| 130 | try { privateLog = await readFile(join(temp, 'logs', 'code_signing_tool.log'), 'utf8'); } catch { } |
| 131 | const stages = { getMalwareScanResponse: 'malware-scan', getScanSettingsResponse: 'scan-settings', getCredentialsAuthorize: 'credentials-authorize', signHash: 'sign-hash', isOtpTypeOnline: 'otp-type', sendOtp: 'send-otp', getCredentialInfo: 'credentials-info', getCredentialIDs: 'credentials-list' }; |
| 132 | const method = /^\s*at com\.ssl\.code\.signing\.tool\.csc\.CscApi\.(getMalwareScanResponse|getScanSettingsResponse|getCredentialsAuthorize|signHash|isOtpTypeOnline|sendOtp|getCredentialInfo|getCredentialIDs)\(/m.exec(privateLog)?.[1]; |
| 133 | const failureStage = stages[method] || 'unknown'; |
| 134 | const rawCode = /"error"\s*:\s*"([a-z_]+)"/.exec(output)?.[1]; |
| 135 | const providerCode = providerCodes.includes(rawCode) ? rawCode : 'unclassified'; |
| 136 | const quotaExceeded = /QuotaExceededError/.test(privateLog + output); |
| 137 | |
| 138 | |
| 139 | throw Object.assign(new Error(`CodeSignTool failed (exit ${code}). stage=${failureStage}; error=${providerCode}; quotaExceeded=${quotaExceeded}.`), { |
| 140 | failureStage, providerCode, quotaExceeded, nonRetryable: quotaExceeded || rejectedOrUncertain.test(output), |
| 141 | }); |
| 142 | } |
| 143 | return output; |
| 144 | } finally { |
| 145 | controller.abort(); |
| 146 | child?.kill(); |
| 147 | |
| 148 | await rm(temp, { recursive: true, force: true }); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | export async function assertWindowsExecutable(path) { |
| 153 | if (!(await stat(path)).isFile()) throw new Error('Provide a Windows PE executable.'); |
| 154 | |
| 155 | const file = await open(path, 'r'); |
| 156 | try { |
| 157 | const header = Buffer.alloc(64); |
| 158 | const pe = Buffer.alloc(4); |
| 159 | const first = await file.read(header, 0, 64, 0); |
| 160 | if (first.bytesRead !== 64 || header.readUInt16LE(0) !== 0x5a4d) throw new Error('Input is not a Windows PE executable.'); |
| 161 | const signature = await file.read(pe, 0, 4, header.readUInt32LE(60)); |
| 162 | if (signature.bytesRead !== 4 || pe.readUInt32LE(0) !== 0x4550) throw new Error('Input is not a Windows PE executable.'); |
| 163 | } finally { await file.close(); } |
| 164 | } |
| 165 | |
| 166 | export async function prepareVendorInput(input, stage) { |
| 167 | |
| 168 | |
| 169 | const path = join(stage, 'input', 'payload.exe'); |
| 170 | const output = join(stage, 'signed'); |
| 171 | await mkdir(dirname(path)); |
| 172 | await mkdir(output); |
| 173 | await copyFile(input, path); |
| 174 | return { path, output }; |
| 175 | } |
| 176 | |
| 177 | async function credentials() { |
| 178 | const username = process.env.CAGE_ESIGNER_USERNAME || await prompt('SSL.com username'); |
| 179 | const password = process.env.CAGE_ESIGNER_PASSWORD || await prompt('SSL.com password', true); |
| 180 | const credential = process.env.CAGE_ESIGNER_CREDENTIAL_ID || await prompt('eSigner credential ID'); |
| 181 | if (!username || !password || !/^[a-f0-9-]{36}$/iu.test(credential)) throw new Error('A username, password and valid eSigner credential ID are required.'); |
| 182 | return { username, password, credential, totp: process.env.CAGE_ESIGNER_TOTP_SECRET }; |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | export async function invokeSigning({ invoke, outputPath, pause = ms => new Promise(done => setTimeout(done, ms)) }) { |
| 189 | for (let attempt = 0; attempt < 3; attempt++) { |
| 190 | try { return await invoke(); } |
| 191 | catch (error) { |
| 192 | try { await access(outputPath); return ''; } |
| 193 | catch (outputError) { if (outputError.code !== 'ENOENT') throw error; } |
| 194 | const uncertainOrRejected = error.nonRetryable || error.quotaExceeded || rejectedOrUncertain.test(error.message) || /QuotaExceededError/.test(error.message); |
| 195 | const serverError = error.providerCode === 'server_error' || /"error"\s*:\s*"server_error"/.test(error.message); |
| 196 | if (attempt === 2 || uncertainOrRejected || !/^CodeSignTool failed \(exit 11\)/.test(error.message) || !serverError) throw error; |
| 197 | console.error(`Signing service returned server_error; retrying in ${(attempt + 1) * 15} seconds.`); |
| 198 | await pause((attempt + 1) * 15000); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | export function credentialDiagnostic(error) { |
| 206 | if (!error) return { operation: 'credential_info', success: true, stage: 'csc-credential-info', exitCode: 0, error: '' }; |
| 207 | const match = /^CodeSignTool failed \(exit ([0-9]{1,3})\)/.exec(error.message); |
| 208 | const exitCode = match && Number(match[1]) <= 255 ? Number(match[1]) : null; |
| 209 | const code = error.providerCode || /"error"\s*:\s*"([a-z_]+)"/.exec(error.message)?.[1]; |
| 210 | return { operation: 'credential_info', success: false, stage: exitCode === 1 ? 'oauth-token' : exitCode === 2 ? 'csc-credential-info' : 'client', exitCode, error: providerCodes.includes(code) ? code : 'unclassified' }; |
| 211 | } |
| 212 | |
| 213 | async function main(argv) { |
| 214 | const [command, input, flag, destination] = argv; |
| 215 | if (command === 'install' && argv.length === 1) { console.log(`Verified CodeSignTool ${pin.version}: ${await installTool()}`); return; } |
| 216 | if (!['info', 'diagnose', 'sign'].includes(command) || (['info', 'diagnose'].includes(command) && argv.length !== 1) || |
| 217 | (command === 'sign' && (argv.length !== 4 || flag !== '--output-dir'))) { |
| 218 | throw new Error('Usage: node scripts/esigner.mjs install | info | diagnose | sign INPUT.exe --output-dir DIRECTORY'); |
| 219 | } |
| 220 | if (command === 'sign') await assertWindowsExecutable(resolve(input)); |
| 221 | const directory = await installTool(); |
| 222 | const auth = await credentials(); |
| 223 | if (command === 'sign' && !auth.totp && !process.stdin.isTTY) throw new Error('Non-interactive signing requires CAGE_ESIGNER_TOTP_SECRET.'); |
| 224 | const args = [command === 'sign' ? 'sign' : 'credential_info', `-username=${auth.username}`, `-password=${auth.password}`, `-credential_id=${auth.credential}`]; |
| 225 | let staged, output, vendor; |
| 226 | try { |
| 227 | if (command === 'sign') { |
| 228 | const path = resolve(input); |
| 229 | await mkdir(resolve(destination), { recursive: true }); |
| 230 | output = join(resolve(destination), basename(path)); |
| 231 | try { await access(output); throw new Error('Signed output already exists; use a fresh output directory.'); } |
| 232 | catch (error) { if (error.code !== 'ENOENT') throw error; } |
| 233 | staged = await mkdtemp(join(resolve(destination), '.sign-')); |
| 234 | vendor = await prepareVendorInput(path, staged); |
| 235 | args.push(`-input_file_path=${vendor.path}`, `-output_dir_path=${vendor.output}`); |
| 236 | if (auth.totp) args.push(`-totp_secret=${auth.totp}`); |
| 237 | } |
| 238 | const invoke = () => invokeJava({ jar: join(directory, pin.jar), config: join(directory, configPath), arguments: args, |
| 239 | otp: signal => prompt('Current six-digit authenticator code', true, signal), secrets: [auth.password, auth.totp] }); |
| 240 | const result = command === 'sign' ? await invokeSigning({ invoke, outputPath: join(vendor.output, basename(vendor.path)) }) : await invoke(); |
| 241 | if (command === 'sign') { |
| 242 | const signed = join(vendor.output, basename(vendor.path)); |
| 243 | const bytes = await readFile(signed); |
| 244 | if (!bytes.length || hash(bytes) === hash(await readFile(resolve(input)))) throw new Error('CodeSignTool did not produce a changed signed file.'); |
| 245 | await copyFile(signed, output, (await import('node:fs')).constants.COPYFILE_EXCL); |
| 246 | console.log(`Signed copy: ${output}\nWindows trust and publisher verification are still required.`); |
| 247 | } else if (command === 'diagnose') console.log(JSON.stringify(credentialDiagnostic())); |
| 248 | else console.log(result.trim()); |
| 249 | } finally { if (staged) await rm(staged, { recursive: true, force: true }); } |
| 250 | } |
| 251 | |
| 252 | if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { |
| 253 | main(process.argv.slice(2)).catch(error => { |
| 254 | if (process.argv[2] === 'diagnose') console.error(JSON.stringify(credentialDiagnostic(error))); |
| 255 | else console.error(redact(error.message, secretNames.map(name => process.env[name]))); |
| 256 | process.exitCode = 1; |
| 257 | }); |
| 258 | } |