ShtukbaseStandard
package file→ .shtukbase/packages/std-owasp-secrets/checks/secretlib.ts

checks/secretlib.ts

127 lines, 6.7 KB.

  1. // Secret hygiene after the OWASP Secrets Management Cheat Sheet and ASVS 4.0.3 V2.10.4: no secrets in the files of
  2. // the repository. Known token formats (SCR-R01), likely secrets by name and entropy (SCR-R02). A found value is
  3. // never printed: a finding names the file, the line and the kind only.
  4. import { excluder, list, projectFiles, readTextFile, settings } from './lib/std.ts';
  5. export const PKG = 'std-owasp-secrets';
  6. export const DEFAULTS = {
  7. exclude: ['**/*.lock', '**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock', '**/Cargo.lock', '**/go.sum'],
  8. allowMarkers: ['secrets:allow', 'gitleaks:allow'],
  9. minEntropy: 3.5,
  10. minLength: 16,
  11. maxBytes: 1048576,
  12. };
  13. export type Config = typeof DEFAULTS;
  14. export function config(): Config {
  15. const c = settings('owasp-secrets', DEFAULTS);
  16. return { exclude: list(c.exclude), allowMarkers: list(c.allowMarkers), minEntropy: Number(c.minEntropy) || 3.5, minLength: Number(c.minLength) || 16, maxBytes: Number(c.maxBytes) || DEFAULTS.maxBytes };
  17. }
  18. /** Known formats: a match is a secret almost always. */
  19. export const KNOWN: { kind: string; re: RegExp }[] = [
  20. { kind: 'private key (PEM/OpenSSH/PGP)', re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/ },
  21. { kind: 'AWS access key', re: /\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b/ },
  22. { kind: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9]{36,255}\b/ },
  23. { kind: 'GitHub token (fine-grained)', re: /\bgithub_pat_[A-Za-z0-9_]{60,}\b/ },
  24. { kind: 'GitLab token', re: /\bglpat-[A-Za-z0-9_-]{20,}\b/ },
  25. { kind: 'Slack token', re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ },
  26. { kind: 'Slack webhook', re: /https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{20,}/ },
  27. { kind: 'Stripe live key', re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}\b/ },
  28. { kind: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
  29. { kind: 'OpenAI key', re: /\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{16,}T3BlbkFJ[A-Za-z0-9_-]{16,}|\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{40,}/ },
  30. { kind: 'Anthropic key', re: /\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,}/ },
  31. { kind: 'npm token', re: /\bnpm_[A-Za-z0-9]{36}\b/ },
  32. { kind: 'token in .npmrc (_authToken)', re: /_authToken\s*=\s*(?!\$\{)[A-Za-z0-9_\-.]{16,}/ },
  33. { kind: 'SendGrid key', re: /\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/ },
  34. { kind: 'Telegram bot token', re: /\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/ },
  35. { kind: 'Hugging Face token', re: /\bhf_[A-Za-z]{34}\b/ },
  36. { kind: 'DigitalOcean token', re: /\bdo[por]_v1_[a-f0-9]{64}\b/ },
  37. ];
  38. /** Values that only stand in for a secret: documentation examples and templates. */
  39. const PLACEHOLDER = /example|sample|dummy|fake|synthetic|placeholder|password|secret|changeme|change_me|redacted|your[_-]?|xxxx|\*\*\*\*|<[^>]*>|\$\{|\{\{|%\(|process\.env|os\.environ|getenv|env\(|ENV\[/i;
  40. export function placeholder(value: string): boolean {
  41. return PLACEHOLDER.test(value) || /^(.)\1+$/.test(value.replace(/[^A-Za-z0-9]/g, '')) || /0{8,}|1234567890/.test(value);
  42. }
  43. /** Shannon entropy in bits per character. */
  44. export function entropy(s: string): number {
  45. const counts = new Map<string, number>();
  46. for (const c of s) counts.set(c, (counts.get(c) ?? 0) + 1);
  47. let h = 0;
  48. for (const n of counts.values()) h -= (n / s.length) * Math.log2(n / s.length);
  49. return h;
  50. }
  51. // `api_key = "…"`, `"clientSecret": "…"`, `PASSWORD: '…'`: a secret-like name, then a quoted literal.
  52. const NAMED = /([A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|auth[_-]?key|credential)[A-Za-z0-9_.-]*)["']?\s*(?::=|=>|[:=])\s*(["'`])([^"'`\s]{8,})\2/gi;
  53. // scheme://user:password@host
  54. const URL_CRED = /\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'"]+:([^\s@/'"]{3,})@([^\s/:'"]+)/gi;
  55. // Hosts reserved for examples and tests (RFC 2606, RFC 6761): a credential there is no secret.
  56. const SAFE_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$|(^|\.)(example\.(com|org|net)|example|invalid|test|localhost)$/i;
  57. const JWT = /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/;
  58. /** A PEM header counts only with a key body after it (at least 64 base64 characters before the END line), across
  59. * real line breaks or escaped `\\n` in a string: a bare header in a test or a redaction rule is no key. */
  60. export function keyBody(lines: string[], i: number, from: number): boolean {
  61. const rest = [lines[i].slice(from), ...lines.slice(i + 1, i + 60)].join('\n').slice(0, 6000);
  62. let body = 0;
  63. for (const part of rest.split(/\n|\\n|\\r/)) {
  64. const t = part.replace(/^[\s"'`+,]+|[\s"'`+,;)]+$/g, '');
  65. if (t.startsWith('-----END')) break;
  66. if (!t || t.includes(':')) continue;
  67. if (!/^[A-Za-z0-9+/=]+$/.test(t)) break;
  68. body += t.length;
  69. }
  70. return body >= 64;
  71. }
  72. export type Hit = { file: string; line: number; kind: string };
  73. export function scanText(file: string, text: string, cfg: Config, what: 'known' | 'likely'): Hit[] {
  74. const out: Hit[] = [];
  75. const lines = text.split('\n');
  76. for (let i = 0; i < lines.length; i++) {
  77. const l = lines[i];
  78. if (l.length > 4000 && what === 'likely') continue; // minified or data lines
  79. if (cfg.allowMarkers.some((m) => l.includes(m))) continue;
  80. if (what === 'known') {
  81. for (const k of KNOWN) {
  82. const m = k.re.exec(l);
  83. if (!m || placeholder(m[0])) continue;
  84. if (k === KNOWN[0] && !keyBody(lines, i, m.index + m[0].length)) continue;
  85. out.push({ file, line: i + 1, kind: k.kind });
  86. }
  87. continue;
  88. }
  89. for (const m of l.matchAll(NAMED)) {
  90. const v = m[3];
  91. if (/\.[A-Za-z]{1,5}$/.test(m[1])) continue; // the name is a file name, not a variable
  92. if (v.length < cfg.minLength || placeholder(v) || entropy(v) < cfg.minEntropy) continue;
  93. if (!/[0-9]/.test(v) || !/[A-Za-z]/.test(v)) continue;
  94. if (/^[a-z]+([._-][a-z]+)+$/i.test(v) || /^[\w.-]+\/[\w./-]+$/.test(v)) continue; // identifiers and paths
  95. out.push({ file, line: i + 1, kind: `high-entropy string in "${m[1].slice(0, 40)}"` });
  96. }
  97. for (const m of l.matchAll(URL_CRED)) if (!placeholder(m[1]) && !SAFE_HOST.test(m[2]) && !/^(pass(word)?|pwd|secret|\*+|x+)$/i.test(m[1])) out.push({ file, line: i + 1, kind: 'password in an address (scheme://login:password@host)' });
  98. if (JWT.test(l)) out.push({ file, line: i + 1, kind: 'JWT' });
  99. }
  100. return out;
  101. }
  102. export function scanFiles(what: 'known' | 'likely'): Hit[] {
  103. const cfg = config();
  104. const skip = excluder(cfg.exclude);
  105. const out: Hit[] = [];
  106. for (const f of projectFiles()) {
  107. if (skip(f)) continue;
  108. const text = readTextFile(f, cfg.maxBytes);
  109. if (text !== null) out.push(...scanText(f, text, cfg, what));
  110. }
  111. return out;
  112. }
  113. export function lines(hits: Hit[], fix: string): string[] {
  114. return hits.map((h) => `${h.file}:${h.line}: ${h.kind} → ${fix}`);
  115. }