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
release-checks.test.mjsJavaScript181 lines10.1 KiBraw download
// What a release is allowed to contain: one build's search index, no private
// key in first-party output, a download folder that matches its catalogue and
// signature claims that match the files actually published.
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { gzipSync } from 'node:zlib';
import { checkSearchIndex, findPrivateKeys, hasPrivateKey, htmlToText } from '../scripts/check-release.mjs';
import { verifyDownloads } from '../scripts/verify-downloads.mjs';

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

function temp(t) {
  const dir = mkdtempSync(join(tmpdir(), 'dmn-release-'));
  t.after(() => rmSync(dir, { recursive: true, force: true }));
  return dir;
}
function write(file, data) {
  mkdirSync(dirname(file), { recursive: true });
  writeFileSync(file, data);
}
// Assembled at run time so this file never contains something that looks like a key.
const marker = (edge) => `-----${edge} OPENSSH ${'PRIVATE'} KEY-----`;
const keyLines = [marker('BEGIN'), ...Array.from({ length: 6 }, () => 'b3BlbnNzaC1rZXktdjEA'.repeat(3)), marker('END')];
const fragment = (page) => gzipSync(`pagefind_dcd${JSON.stringify(page)}`);

test('only a complete private-key block counts as a key', () => {
  assert.ok(hasPrivateKey(keyLines.join('\n')));
  assert.ok(hasPrivateKey(keyLines.join(' ')), 'search fragments collapse newlines to spaces');
  assert.ok(!hasPrivateKey(`intext:"${marker('BEGIN')}" filetype:pem`));
  assert.ok(!hasPrivateKey(`${marker('BEGIN')}\n...\n${marker('END')}`));
  const highlighted = keyLines.map((line) => `<span class="line"><span style="color:#E0DEF4">${line.replace(/=/g, '&#x3D;')}</span></span>`).join('\n');
  assert.ok(hasPrivateKey(htmlToText(`<pre><code>${highlighted}</code></pre>`)));
});

test('a published key is found in a sheet, its page and its search fragment, but not in a mirror', (t) => {
  const root = temp(t);
  const dist = join(root, 'dist');
  const sheets = join(root, 'sheets');
  const html = `<article><pre>${keyLines.map((l) => `<span>${l}</span>`).join('\n')}</pre></article>`;
  write(join(sheets, 'pentest-workflow', 'ledger.md'), keyLines.join('\n'));
  write(join(sheets, 'enumeration', 'dorks.md'), `intext:"${marker('BEGIN')}"`);
  write(join(dist, 'sheets', 'pentest-workflow', 'ledger', 'index.html'), html);
  write(join(dist, 'payloads', 'jwt', 'index.html'), html);
  write(join(dist, 'pagefind', 'fragment', 'en_aaaaaaa.pf_fragment'), fragment({ url: '/sheets/pentest-workflow/ledger/', content: keyLines.join(' ') }));
  write(join(dist, 'pagefind', 'fragment', 'en_bbbbbbb.pf_fragment'), fragment({ url: '/payloads/jwt/', content: keyLines.join(' ') }));
  write(join(dist, 'pagefind', 'fragment', 'en_ccccccc.pf_fragment'), fragment({ url: '/sheets/enumeration/dorks/', content: `intext:"${marker('BEGIN')}"` }));

  const hits = findPrivateKeys({ dist, sheets });
  assert.equal(hits.length, 3, hits.join('\n'));
  assert.ok(hits.some((h) => h.startsWith('source sheet') && h.endsWith('ledger.md')));
  assert.ok(hits.some((h) => h.startsWith('page') && h.includes('ledger')));
  assert.ok(hits.some((h) => h.includes('en_aaaaaaa.pf_fragment') && h.includes('/sheets/pentest-workflow/ledger/')));
});

test('search output left over from another build is detected', (t) => {
  const dir = join(temp(t), 'pagefind');
  write(join(dir, 'pagefind-entry.json'), JSON.stringify({ version: '1.5.2', languages: { en: { hash: 'en_new', wasm: 'en', page_count: 2 } } }));
  write(join(dir, 'pagefind.en_new.pf_meta'), 'meta');
  write(join(dir, 'fragment', 'en_1.pf_fragment'), fragment({ url: '/a/', content: 'a' }));
  write(join(dir, 'fragment', 'en_2.pf_fragment'), fragment({ url: '/b/', content: 'b' }));
  assert.deepEqual(checkSearchIndex(dir), []);

  write(join(dir, 'fragment', 'en_old.pf_fragment'), fragment({ url: '/removed/', content: 'text of a page that was deleted' }));
  write(join(dir, 'pagefind.en_old.pf_meta'), 'meta');
  const problems = checkSearchIndex(dir);
  assert.equal(problems.length, 2);
  assert.match(problems[0], /3 search fragments on disk but this build indexed 2 pages/);
  assert.match(problems[1], /metadata file\(s\) from another build: pagefind\.en_old\.pf_meta/);
});

function library(t, files) {
  const dir = temp(t);
  const records = [];
  let manifest = '';
  for (const [name, body] of Object.entries(files)) {
    const sha256 = createHash('sha256').update(body).digest('hex');
    writeFileSync(join(dir, name), body);
    writeFileSync(join(dir, `${name}.sha256`), `${sha256}  ${name}\n`);
    manifest += `${sha256}  ${name}\n`;
    records.push({ name, sha256 });
  }
  writeFileSync(join(dir, 'SHA256SUMS'), manifest);
  return { dir, records };
}
const FPR = 'A'.repeat(40);

test('the download check accepts a matching unsigned library and says it is unsigned', async (t) => {
  const { dir, records } = library(t, { 'a.exe': 'a', 'b.zip': 'b' });
  const result = await verifyDownloads({ dir, records, fingerprint: FPR });
  assert.deepEqual(result, { problems: [], signed: false, files: 2 });
  const strict = await verifyDownloads({ dir, records, fingerprint: FPR, requireSigned: true });
  assert.match(strict.problems.join('\n'), /no detached signatures are published/);
});

test('the download check refuses leftovers, altered files and stale checksums', async (t) => {
  const { dir, records } = library(t, { 'a.exe': 'a', 'b.zip': 'b' });
  writeFileSync(join(dir, 'withdrawn.exe'), 'still served');
  writeFileSync(join(dir, 'b.zip'), 'swapped');
  const { problems } = await verifyDownloads({ dir, records, fingerprint: FPR });
  const text = problems.join('\n');
  assert.match(text, /withdrawn\.exe is served but is not in the catalogue/);
  assert.match(text, /b\.zip does not match its catalogued SHA-256/);
  assert.match(text, /b\.zip does not match SHA256SUMS/);
  assert.match(text, /b\.zip\.sha256 does not match b\.zip/);
  assert.doesNotMatch(text, /a\.exe/);
});

test('signatures are all-or-nothing and must come from the pinned key', async (t) => {
  const { dir, records } = library(t, { 'a.exe': 'a', 'b.zip': 'b' });
  writeFileSync(join(dir, 'a.exe.sha256.asc'), 'sig');
  const good = async () => true;
  const partial = await verifyDownloads({ dir, records, fingerprint: FPR, verify: good });
  assert.equal(partial.signed, false);
  assert.match(partial.problems.join('\n'), /signatures are incomplete: 2 of 3 missing/);

  writeFileSync(join(dir, 'b.zip.sha256.asc'), 'sig');
  writeFileSync(join(dir, 'SHA256SUMS.asc'), 'sig');
  const seen = [];
  const complete = await verifyDownloads({ dir, records, fingerprint: FPR, verify: async (sig, file, fpr) => { seen.push([sig, file, fpr]); return true; } });
  assert.deepEqual(complete, { problems: [], signed: true, files: 2 });
  assert.equal(seen.length, 3);
  assert.ok(seen.every(([sig, file, fpr]) => sig === `${file}.asc` && fpr === FPR));

  const wrongKey = await verifyDownloads({ dir, records, fingerprint: FPR, verify: async (sig) => !sig.endsWith('SHA256SUMS.asc') });
  assert.deepEqual(wrongKey.problems, [`SHA256SUMS.asc is not a good signature by ${FPR}`]);

  // Real gpg, no fake: a file that is not a signature must not verify.
  const real = await verifyDownloads({ dir, records, fingerprint: FPR });
  assert.equal(real.problems.length, 3);
});

// ── The built site ──────────────────────────────────────────────────────────
const dist = (path) => new URL(`dist/${path}`, repo);
const downloads = new URL('public/downloads/pentest-workflow/', repo);

test('the lab ledger is not in the source, the build or the publication list', () => {
  assert.ok(!existsSync(new URL('src/content/sheets/pentest-workflow/loot.md', repo)));
  assert.ok(!existsSync(dist('sheets/pentest-workflow/loot/index.html')));
  assert.ok(!existsSync(dist('sheets/pentest-workflow/loot.html')));
  const importer = readFileSync(new URL('scripts/sync-pentest-workflow.py', repo), 'utf8');
  const slugs = importer.slice(importer.indexOf('SLUGS: dict'), importer.indexOf('NEVER_PUBLISH'));
  assert.doesNotMatch(slugs, /loot\.md/);
  assert.match(importer, /NEVER_PUBLISH: frozenset\[str\] = frozenset\(\{"loot\.md"\}\)/);
});

test('the built release passes its own checks', () => {
  assert.deepEqual(checkSearchIndex(new URL('dist/pagefind', repo).pathname), []);
  assert.deepEqual(findPrivateKeys({ dist: new URL('dist', repo).pathname, sheets: new URL('src/content/sheets', repo).pathname }), []);
});

test('the download page claims signatures only for signature files that exist', () => {
  const page = readFileSync(dist('pentest-workflow/index.html'), 'utf8');
  const published = new Set(readdirSync(downloads));
  const linked = [...page.matchAll(/href="\/downloads\/pentest-workflow\/([^"]+\.asc)"/g)].map((m) => decodeURIComponent(m[1]));
  for (const name of linked) assert.ok(published.has(name), `${name} is linked but not published`);
  const catalogue = JSON.parse(readFileSync(new URL('src/data/pentest-workflow-downloads.json', repo), 'utf8'));
  const complete = published.has('SHA256SUMS.asc') && catalogue.every((item) => published.has(`${item.name}.sha256.asc`));
  if (complete) {
    assert.match(page, /Signed attachment library/);
    assert.equal(linked.length, catalogue.length + 1);
  } else {
    assert.doesNotMatch(page, /Signed attachment library/);
    assert.doesNotMatch(page, /\d+ signed files/);
    assert.match(page, /not OpenPGP-signed in this release/);
  }
});

test('no sheet links to a signature file that is not published', () => {
  const published = new Set(readdirSync(downloads));
  const dir = new URL('src/content/sheets/pentest-workflow/', repo);
  for (const name of readdirSync(dir)) {
    const text = readFileSync(new URL(name, dir), 'utf8');
    for (const [, file] of text.matchAll(/\]\(\/downloads\/pentest-workflow\/([^)\s]+\.asc)\)/g)) {
      assert.ok(published.has(decodeURIComponent(file)), `${name} links ${file}, which is not published`);
    }
  }
});