repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
verify-downloads.mjsJavaScript128 lines6.8 KiBraw download
// Checks the attachment library before it is deployed.
//
//   node scripts/verify-downloads.mjs [dir] [--require-signed]
//
// `dir` defaults to public/downloads/pentest-workflow; `npm run deploy:workers`
// points it at the copy in dist/, the one that is about to be uploaded.
//
// What it holds the directory to:
//
// * It contains the catalogued files, their checksum sidecars, the manifest
//   and their signatures, and nothing else. A file the catalogue no longer
//   lists is still served at its old URL, so a leftover is an error.
// * Every file matches the SHA-256 in the catalogue
//   (src/data/pentest-workflow-downloads.json), in its sidecar and in
//   SHA256SUMS.
// * Signatures are all-or-nothing. The site calls the library "signed" only
//   when the manifest and every file have a detached signature, so a partial
//   set is refused. When they are present each one must verify, with gpg,
//   as made by the pinned publisher key. A good signature from any other key
//   does not count.
//
// With no signatures at all the check passes and says so: the page tells
// readers the same thing. Pass --require-signed to make that an error once
// signing is part of the release routine.
//
// The pinned key is the primary fingerprint already pinned for the report
// index (src/data/report-index-lock.json, `recipient`). Signing is done by
// hand with that key and never by this script:
//
//   cd public/downloads/pentest-workflow
//   for f in *.sha256 SHA256SUMS; do gpg --armor --detach-sign --output "$f.asc" "$f"; done
import { createHash } from 'node:crypto';
import { createReadStream, existsSync, readFileSync, readdirSync } from 'node:fs';
import { execFile } from 'node:child_process';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const root = fileURLToPath(new URL('../', import.meta.url));

function sha256File(file) {
  return new Promise((resolve, reject) => {
    const hash = createHash('sha256');
    createReadStream(file).on('data', (chunk) => hash.update(chunk)).on('error', reject).on('end', () => resolve(hash.digest('hex')));
  });
}

/** Resolves true when `signature` is a good signature over `file` by the pinned primary key. */
export function gpgVerify(signature, file, fingerprint) {
  return new Promise((resolve) => {
    execFile('gpg', ['--batch', '--no-tty', '--status-fd', '1', '--verify', signature, file], { encoding: 'utf8' }, (error, stdout) => {
      const lines = String(stdout ?? '').split('\n');
      const good = lines.some((line) => line.startsWith('[GNUPG:] GOODSIG '));
      // VALIDSIG's last field is the fingerprint of the primary key.
      const primary = lines.filter((line) => line.startsWith('[GNUPG:] VALIDSIG ')).map((line) => line.trim().split(' ').pop());
      resolve(!error && good && primary.length === 1 && primary[0].toUpperCase() === fingerprint.toUpperCase());
    });
  });
}

/**
 * @param {{ dir: string, records: {name: string, sha256: string}[], fingerprint: string,
 *           requireSigned?: boolean, verify?: typeof gpgVerify }} options
 * @returns {Promise<{ problems: string[], signed: boolean, files: number }>}
 */
export async function verifyDownloads({ dir, records, fingerprint, requireSigned = false, verify = gpgVerify }) {
  const problems = [];
  if (!existsSync(dir)) return { problems: [`${dir} does not exist`], signed: false, files: 0 };
  const present = new Set(readdirSync(dir).filter((name) => name !== '.DS_Store'));
  const names = records.map((r) => r.name);

  const expected = new Set(['SHA256SUMS', 'SHA256SUMS.asc']);
  for (const name of names) for (const suffix of ['', '.sha256', '.sha256.asc']) expected.add(name + suffix);
  for (const name of present) if (!expected.has(name)) problems.push(`${name} is served but is not in the catalogue`);

  const manifestFile = join(dir, 'SHA256SUMS');
  const manifest = new Map();
  if (!present.has('SHA256SUMS')) problems.push('SHA256SUMS is missing');
  else for (const line of readFileSync(manifestFile, 'utf8').split('\n').filter(Boolean)) {
    const [digest, ...rest] = line.split('  ');
    manifest.set(rest.join('  '), digest);
  }
  for (const name of manifest.keys()) if (!names.includes(name)) problems.push(`SHA256SUMS lists ${name}, which is not in the catalogue`);

  for (const { name, sha256 } of records) {
    if (!present.has(name)) { problems.push(`${name} is catalogued but missing`); continue; }
    const actual = await sha256File(join(dir, name));
    if (actual !== sha256) problems.push(`${name} does not match its catalogued SHA-256`);
    if (manifest.get(name) !== actual) problems.push(`${name} does not match SHA256SUMS`);
    const sidecar = `${name}.sha256`;
    if (!present.has(sidecar)) problems.push(`${sidecar} is missing`);
    else if (readFileSync(join(dir, sidecar), 'utf8') !== `${actual}  ${name}\n`) problems.push(`${sidecar} does not match ${name}`);
  }

  const signable = ['SHA256SUMS', ...names.map((n) => `${n}.sha256`)];
  const withSignature = signable.filter((f) => present.has(`${f}.asc`));
  const signed = withSignature.length === signable.length;
  if (withSignature.length && !signed) {
    const missing = signable.filter((f) => !present.has(`${f}.asc`));
    problems.push(`signatures are incomplete: ${missing.length} of ${signable.length} missing (first: ${missing[0]}.asc)`);
  }
  if (!withSignature.length && requireSigned) problems.push('no detached signatures are published, and --require-signed was given');
  for (const file of withSignature) {
    if (!present.has(file)) continue;
    if (!(await verify(join(dir, `${file}.asc`), join(dir, file), fingerprint))) {
      problems.push(`${file}.asc is not a good signature by ${fingerprint}`);
    }
  }
  return { problems, signed, files: names.length };
}

async function main() {
  const args = process.argv.slice(2);
  const requireSigned = args.includes('--require-signed');
  const dir = args.find((a) => !a.startsWith('--')) ?? join(root, 'public', 'downloads', 'pentest-workflow');
  const records = JSON.parse(readFileSync(join(root, 'src', 'data', 'pentest-workflow-downloads.json'), 'utf8'));
  const { recipient } = JSON.parse(readFileSync(join(root, 'src', 'data', 'report-index-lock.json'), 'utf8'));
  const { problems, signed, files } = await verifyDownloads({ dir, records, fingerprint: recipient, requireSigned });
  if (problems.length) {
    console.error(`verify-downloads: ${dir} must not be deployed:`);
    for (const problem of problems) console.error(`  - ${problem}`);
    process.exit(1);
  }
  console.log(signed
    ? `verify-downloads: ${files} files match their checksums and every signature verifies against ${recipient}`
    : `verify-downloads: ${files} files match their checksums. NOT SIGNED: no detached signatures are published, and the site says so.`);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();