archivo del paquete→ .shtukbase/packages/std-owasp-secrets/checks/secretlib.ts
checks/secretlib.ts
127 líneas, 6.7 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // Secret hygiene after the OWASP Secrets Management Cheat Sheet and ASVS 4.0.3 V2.10.4: no secrets in the files of
- // the repository. Known token formats (SCR-R01), likely secrets by name and entropy (SCR-R02). A found value is
- // never printed: a finding names the file, the line and the kind only.
- import { excluder, list, projectFiles, readTextFile, settings } from './lib/std.ts';
- export const PKG = 'std-owasp-secrets';
- export const DEFAULTS = {
- exclude: ['**/*.lock', '**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock', '**/Cargo.lock', '**/go.sum'],
- allowMarkers: ['secrets:allow', 'gitleaks:allow'],
- minEntropy: 3.5,
- minLength: 16,
- maxBytes: 1048576,
- };
- export type Config = typeof DEFAULTS;
- export function config(): Config {
- const c = settings('owasp-secrets', DEFAULTS);
- 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 };
- }
- /** Known formats: a match is a secret almost always. */
- export const KNOWN: { kind: string; re: RegExp }[] = [
- { kind: 'private key (PEM/OpenSSH/PGP)', re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/ },
- { kind: 'AWS access key', re: /\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b/ },
- { kind: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9]{36,255}\b/ },
- { kind: 'GitHub token (fine-grained)', re: /\bgithub_pat_[A-Za-z0-9_]{60,}\b/ },
- { kind: 'GitLab token', re: /\bglpat-[A-Za-z0-9_-]{20,}\b/ },
- { kind: 'Slack token', re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ },
- { kind: 'Slack webhook', re: /https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{20,}/ },
- { kind: 'Stripe live key', re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}\b/ },
- { kind: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
- { 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,}/ },
- { kind: 'Anthropic key', re: /\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,}/ },
- { kind: 'npm token', re: /\bnpm_[A-Za-z0-9]{36}\b/ },
- { kind: 'token in .npmrc (_authToken)', re: /_authToken\s*=\s*(?!\$\{)[A-Za-z0-9_\-.]{16,}/ },
- { kind: 'SendGrid key', re: /\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/ },
- { kind: 'Telegram bot token', re: /\b\d{8,10}:AA[A-Za-z0-9_-]{33}\b/ },
- { kind: 'Hugging Face token', re: /\bhf_[A-Za-z]{34}\b/ },
- { kind: 'DigitalOcean token', re: /\bdo[por]_v1_[a-f0-9]{64}\b/ },
- ];
- /** Values that only stand in for a secret: documentation examples and templates. */
- const PLACEHOLDER = /example|sample|dummy|fake|synthetic|placeholder|password|secret|changeme|change_me|redacted|your[_-]?|xxxx|\*\*\*\*|<[^>]*>|\$\{|\{\{|%\(|process\.env|os\.environ|getenv|env\(|ENV\[/i;
- export function placeholder(value: string): boolean {
- return PLACEHOLDER.test(value) || /^(.)\1+$/.test(value.replace(/[^A-Za-z0-9]/g, '')) || /0{8,}|1234567890/.test(value);
- }
- /** Shannon entropy in bits per character. */
- export function entropy(s: string): number {
- const counts = new Map<string, number>();
- for (const c of s) counts.set(c, (counts.get(c) ?? 0) + 1);
- let h = 0;
- for (const n of counts.values()) h -= (n / s.length) * Math.log2(n / s.length);
- return h;
- }
- // `api_key = "…"`, `"clientSecret": "…"`, `PASSWORD: '…'`: a secret-like name, then a quoted literal.
- 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;
- // scheme://user:password@host
- const URL_CRED = /\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'"]+:([^\s@/'"]{3,})@([^\s/:'"]+)/gi;
- // Hosts reserved for examples and tests (RFC 2606, RFC 6761): a credential there is no secret.
- const SAFE_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$|(^|\.)(example\.(com|org|net)|example|invalid|test|localhost)$/i;
- const JWT = /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/;
- /** A PEM header counts only with a key body after it (at least 64 base64 characters before the END line), across
- * real line breaks or escaped `\\n` in a string: a bare header in a test or a redaction rule is no key. */
- export function keyBody(lines: string[], i: number, from: number): boolean {
- const rest = [lines[i].slice(from), ...lines.slice(i + 1, i + 60)].join('\n').slice(0, 6000);
- let body = 0;
- for (const part of rest.split(/\n|\\n|\\r/)) {
- const t = part.replace(/^[\s"'`+,]+|[\s"'`+,;)]+$/g, '');
- if (t.startsWith('-----END')) break;
- if (!t || t.includes(':')) continue;
- if (!/^[A-Za-z0-9+/=]+$/.test(t)) break;
- body += t.length;
- }
- return body >= 64;
- }
- export type Hit = { file: string; line: number; kind: string };
- export function scanText(file: string, text: string, cfg: Config, what: 'known' | 'likely'): Hit[] {
- const out: Hit[] = [];
- const lines = text.split('\n');
- for (let i = 0; i < lines.length; i++) {
- const l = lines[i];
- if (l.length > 4000 && what === 'likely') continue; // minified or data lines
- if (cfg.allowMarkers.some((m) => l.includes(m))) continue;
- if (what === 'known') {
- for (const k of KNOWN) {
- const m = k.re.exec(l);
- if (!m || placeholder(m[0])) continue;
- if (k === KNOWN[0] && !keyBody(lines, i, m.index + m[0].length)) continue;
- out.push({ file, line: i + 1, kind: k.kind });
- }
- continue;
- }
- for (const m of l.matchAll(NAMED)) {
- const v = m[3];
- if (/\.[A-Za-z]{1,5}$/.test(m[1])) continue; // the name is a file name, not a variable
- if (v.length < cfg.minLength || placeholder(v) || entropy(v) < cfg.minEntropy) continue;
- if (!/[0-9]/.test(v) || !/[A-Za-z]/.test(v)) continue;
- if (/^[a-z]+([._-][a-z]+)+$/i.test(v) || /^[\w.-]+\/[\w./-]+$/.test(v)) continue; // identifiers and paths
- out.push({ file, line: i + 1, kind: `high-entropy string in "${m[1].slice(0, 40)}"` });
- }
- 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)' });
- if (JWT.test(l)) out.push({ file, line: i + 1, kind: 'JWT' });
- }
- return out;
- }
- export function scanFiles(what: 'known' | 'likely'): Hit[] {
- const cfg = config();
- const skip = excluder(cfg.exclude);
- const out: Hit[] = [];
- for (const f of projectFiles()) {
- if (skip(f)) continue;
- const text = readTextFile(f, cfg.maxBytes);
- if (text !== null) out.push(...scanText(f, text, cfg, what));
- }
- return out;
- }
- export function lines(hits: Hit[], fix: string): string[] {
- return hits.map((h) => `${h.file}:${h.line}: ${h.kind} → ${fix}`);
- }