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
csp-hashes.mjsJavaScript120 lines5.1 KiBraw download
// Fills the inline-script hashes into dist/_headers after a build.
//
// The Content-Security-Policy in public/_headers allows no 'unsafe-inline'
// for scripts. The inline scripts the site does carry (the theme and page
// iris bootstraps in Base.astro) are allowed by SHA-256 hash instead, which a
// browser accepts only for the exact text. Astro rewrites them on every
// build, so the hashes are computed from the built HTML rather than written
// by hand.
//
// Which scripts get a hash
// ------------------------
// Not "whatever is in dist". Most pages here render Markdown, three whole
// collections of it are mirrored from other people's repositories, and
// Markdown can carry raw HTML. Hashing every inline script found in the
// output would mean a `<script>` committed upstream authorises itself.
//
// So the allowlist is taken from TRUSTED_PAGES only: pages rendered wholly
// from this repository's own templates, with no Markdown body. Every other
// page is then held to that list. An inline script anywhere in dist that is
// not on it fails the build and names the page, which also stops the
// scheduled mirror sync from landing it (scripts/sync-mirrors.sh builds
// before it commits).
//
// If a first-party page genuinely needs its own inline script, add a page
// that renders it, and no Markdown, to TRUSTED_PAGES. src/lib/
// rehype-sanitize-mirror.mjs is the first line of defence and removes
// scripts from mirrored content before it gets here; this is the second.
//
// Runs near the end of `npm run build`.
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'node:fs';
import { join, relative } from 'node:path';
import { pathToFileURL } from 'node:url';

const TOKEN = '__INLINE_SCRIPT_HASHES__';

/** Pages built only from first-party templates. Paths are relative to dist. */
export const TRUSTED_PAGES = ['404.html'];

function* htmlFiles(dir) {
  for (const name of readdirSync(dir)) {
    const p = join(dir, name);
    if (statSync(p).isDirectory()) yield* htmlFiles(p);
    else if (name.endsWith('.html')) yield p;
  }
}

// A <script> with no src and a JavaScript type. JSON blocks (JSON-LD) are
// data the browser never executes, so they need no hash.
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
const isData = (attrs) => /\btype\s*=\s*["']?(application\/(ld\+)?json|text\/(template|x-|plain))/i.test(attrs);
const hashOf = (body) => `'sha256-${createHash('sha256').update(body).digest('base64')}'`;

/** Every inline, executable script in a page as { hash, body }. */
export function inlineScripts(html) {
  const found = [];
  for (const [, attrs, body] of html.matchAll(SCRIPT)) {
    if (/\bsrc\s*=/i.test(attrs) || isData(attrs)) continue;
    found.push({ hash: hashOf(body), body });
  }
  return found;
}

/**
 * Hashes of the trusted pages' inline scripts, plus every script elsewhere in
 * `dist` that is not among them.
 */
export function collect(dist, trustedPages = TRUSTED_PAGES) {
  const allowed = new Set();
  for (const page of trustedPages) {
    const file = join(dist, page);
    if (!existsSync(file)) throw new Error(`trusted page ${page} is missing from ${dist}`);
    for (const { hash } of inlineScripts(readFileSync(file, 'utf8'))) allowed.add(hash);
  }
  const unknown = [];
  let files = 0;
  for (const file of htmlFiles(dist)) {
    files++;
    for (const { hash, body } of inlineScripts(readFileSync(file, 'utf8'))) {
      if (!allowed.has(hash)) unknown.push({ page: relative(dist, file), hash, preview: body.trim().replace(/\s+/g, ' ').slice(0, 100) });
    }
  }
  return { allowed, unknown, files };
}

function main() {
  const DIST = 'dist';
  const HEADERS = join(DIST, '_headers');
  let result;
  try {
    result = collect(DIST);
  } catch (error) {
    console.error(`csp-hashes: ${error.message}`);
    process.exit(1);
  }
  const { allowed, unknown, files } = result;
  if (unknown.length) {
    console.error(`csp-hashes: ${unknown.length} inline script(s) are not part of the site's own templates and will not be allowed:`);
    for (const { page, hash, preview } of unknown.slice(0, 20)) console.error(`  ${page}  ${hash}\n    ${preview}`);
    if (unknown.length > 20) console.error(`  ... and ${unknown.length - 20} more`);
    console.error('If this is imported content, it must not ship a script. If it is a new first-party script, see TRUSTED_PAGES in scripts/csp-hashes.mjs.');
    process.exit(1);
  }

  const headers = readFileSync(HEADERS, 'utf8');
  if (!headers.includes(TOKEN)) {
    console.error(`csp-hashes: ${HEADERS} has no ${TOKEN} placeholder`);
    process.exit(1);
  }
  const out = headers.replace(TOKEN, [...allowed].join(' '));
  const longest = Math.max(...out.split('\n').map((l) => l.length));
  if (longest > 2000) {
    console.error(`csp-hashes: a _headers line is ${longest} chars; Cloudflare's limit is 2000`);
    process.exit(1);
  }
  writeFileSync(HEADERS, out);
  console.log(`csp-hashes: ${allowed.size} first-party inline script hash(es), ${files} pages checked -> ${HEADERS} (longest line ${longest})`);
}

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