xploitscan-shared-rules 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VibeCheck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs CHANGED
@@ -158,6 +158,7 @@ __export(index_exports, {
158
158
  regexDos: () => regexDos,
159
159
  runCustomRules: () => runCustomRules,
160
160
  s3BucketNoEncryption: () => s3BucketNoEncryption,
161
+ scanEntropy: () => scanEntropy,
161
162
  secretInBundleConfig: () => secretInBundleConfig,
162
163
  secretInCLIArgument: () => secretInCLIArgument,
163
164
  secretInErrorResponse: () => secretInErrorResponse,
@@ -471,26 +472,42 @@ var sqlInjection = {
471
472
  description: "String concatenation or template literals in SQL queries allow attackers to execute arbitrary database commands.",
472
473
  check(content, filePath) {
473
474
  const patterns = [
474
- // Template literals in SQL
475
- /(?:query|execute|raw|sql)\s*\(\s*`[^`]*\$\{/gi,
476
- // String concatenation in SQL
477
- /(?:query|execute)\s*\(\s*["'][^"']*["']\s*\+/gi,
478
- // Direct variable interpolation
475
+ // Template literal passed as first arg to query/execute/raw/sql/
476
+ // queryRaw/queryRawUnsafe/execute. Examples that SHOULD fire:
477
+ // db.query(`SELECT ... ${x}`)
478
+ // prisma.$queryRawUnsafe(`... ${x}`)
479
+ // knex.raw(`... ${x}`)
480
+ /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*`[^`]*\$\{/gi,
481
+ // String concatenation in SQL — now includes raw() and sql() and
482
+ // Drizzle's sql.raw() / Prisma's $queryRawUnsafe() variants. Previous
483
+ // version only covered query()/execute() and missed knex.raw("..." + x).
484
+ //
485
+ // The string literal part uses a proper "quoted string" regex that
486
+ // allows the opposite quote type inside (common in SQL — "WHERE x = 'a'").
487
+ // The older `[^"']*` class bailed out at the first inner quote and
488
+ // missed every realistic SQL-containing concat.
489
+ /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\+/gi,
490
+ // Direct variable interpolation in a SQL verb context
479
491
  /(?:SELECT|INSERT|UPDATE|DELETE|WHERE)\s+.*\$\{(?!.*parameterized)/gi
480
492
  ];
481
493
  const matches = [];
482
494
  const usesParams = /\?\s*,|\$\d+|:[\w]+|\bprepare\b|\bplaceholder\b/i.test(content);
483
495
  if (usesParams) return [];
484
496
  for (const pattern of patterns) {
485
- matches.push(
486
- ...findMatches(
487
- content,
488
- pattern,
489
- sqlInjection,
490
- filePath,
491
- () => "Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])"
492
- )
497
+ const raw = findMatches(
498
+ content,
499
+ pattern,
500
+ sqlInjection,
501
+ filePath,
502
+ () => "Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])"
493
503
  );
504
+ for (const m of raw) {
505
+ const lineText = content.split("\n")[m.line - 1] || "";
506
+ if (/\bPrisma\.sql\s*`/.test(lineText)) continue;
507
+ if (/\bsql\s*`/.test(lineText) && !/\bsql\.raw\s*\(/.test(lineText)) continue;
508
+ if (/\$queryRaw\s*\(\s*Prisma\.sql|\$executeRaw\s*\(\s*Prisma\.sql/.test(lineText)) continue;
509
+ matches.push(m);
510
+ }
494
511
  }
495
512
  return matches;
496
513
  }
@@ -3031,13 +3048,22 @@ var commandInjection = {
3031
3048
  // Node.js — require standalone exec/execSync, not db.exec() or conn.exec()
3032
3049
  /(?<![.\w])(?:exec|execSync)\s*\(\s*(?:`[^`]*\$\{|["'][^"']*\+\s*(?:req\.|body\.|input|params|args|user))/gi,
3033
3050
  /child_process.*exec\s*\(\s*(?!["'`])/g,
3051
+ // spawn / execFile / exec with shell: true AND a template literal
3052
+ // first arg. `shell: true` converts the first argument into a string
3053
+ // passed to `/bin/sh -c`, so any ${} interpolation is a shell injection
3054
+ // opportunity. Without shell: true, spawn/execFile are safe because
3055
+ // the command and args are kept separate. Previously this class of
3056
+ // bug was missed — the "hasSafe" skip below assumed any spawn in the
3057
+ // file was fine, which is the opposite of true with shell: true.
3058
+ /(?<![.\w])(?:spawn|spawnSync|execFile|execFileSync|exec|execSync)\s*\(\s*`[^`]*\$\{[\s\S]*?shell\s*:\s*(?:true|["'][^"']+["'])/gi,
3034
3059
  // Python
3035
3060
  /os\.system\s*\(\s*(?!["'`].*["'`]\s*\))/g,
3036
3061
  /subprocess\.(?:call|run|Popen)\s*\([^)]*shell\s*=\s*True/gi,
3037
3062
  // Ruby
3038
3063
  /system\s*\(\s*["'].*#\{/g
3039
3064
  ];
3040
- const hasSafe = /execFile|spawn|escapeshellarg|shlex\.quote|shellEscape/i.test(content);
3065
+ const hasShellTrue = /shell\s*:\s*(?:true|["'][^"']+["'])/i.test(content);
3066
+ const hasSafe = !hasShellTrue && /execFile|spawn|escapeshellarg|shlex\.quote|shellEscape/i.test(content);
3041
3067
  if (hasSafe) return [];
3042
3068
  for (const p of patterns) {
3043
3069
  const raw = findMatches(
@@ -4538,7 +4564,7 @@ var hardcodedSupabaseServiceRole = {
4538
4564
  if (isTestFile(filePath)) return [];
4539
4565
  if (!SECRET_FILE_EXT.test(filePath)) return [];
4540
4566
  if (LOCK_FILE_RE.test(filePath)) return [];
4541
- const pattern = /(?:service[_-]?role[_-]?key|SUPABASE_SERVICE_ROLE_KEY|supabaseServiceRole)\s*[:=]\s*["'`](eyJ[A-Za-z0-9_\-]{50,})["'`]/gi;
4567
+ const pattern = /(?:service[_-]?role[_-]?key|SUPABASE_SERVICE_ROLE_KEY|supabaseServiceRole)\s*[:=]\s*["'`](eyJ[A-Za-z0-9_\-.]{50,})["'`]/gi;
4542
4568
  const findings = [];
4543
4569
  let m;
4544
4570
  while ((m = pattern.exec(content)) !== null) {
@@ -5424,6 +5450,163 @@ async function filterFalsePositives(findings, fileContents) {
5424
5450
  totalBefore
5425
5451
  };
5426
5452
  }
5453
+
5454
+ // src/entropy-scanner.ts
5455
+ function shannonEntropy(str) {
5456
+ const freq = {};
5457
+ for (const ch of str) {
5458
+ freq[ch] = (freq[ch] || 0) + 1;
5459
+ }
5460
+ const len = str.length;
5461
+ let entropy = 0;
5462
+ for (const count of Object.values(freq)) {
5463
+ const p = count / len;
5464
+ entropy -= p * Math.log2(p);
5465
+ }
5466
+ return entropy;
5467
+ }
5468
+ var SAFE_PATTERNS = [
5469
+ // UUIDs (v1-v5)
5470
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
5471
+ // Git commit hashes (long and short)
5472
+ /^[0-9a-f]{40}$/i,
5473
+ /^[0-9a-f]{7,8}$/i,
5474
+ // Hex colors
5475
+ /^#?[0-9a-fA-F]{3,8}$/,
5476
+ // Small base64 (< 20 chars can't be a real key anyway)
5477
+ /^[A-Za-z0-9+/]{1,19}={0,2}$/,
5478
+ // Package versions
5479
+ /^\d+\.\d+\.\d+/,
5480
+ // Integrity-hash prefix (sha256-, sha512-, ...)
5481
+ /^sha\d+-/i,
5482
+ // URLs without credentials in them
5483
+ /^https?:\/\/[^:@]*$/,
5484
+ /^https?:\/\/registry\.npmjs\.org\//,
5485
+ /^https?:\/\/registry\.yarnpkg\.com\//,
5486
+ // Full package integrity hash (sha512-[base64]=)
5487
+ /^sha\d+-[A-Za-z0-9+/=]+$/,
5488
+ // Package tarball URLs
5489
+ /\.tgz$/,
5490
+ /registry.*\/-\/.*\.tgz$/,
5491
+ // ISO dates / times
5492
+ /^\d{4}-\d{2}-\d{2}/,
5493
+ // Locale tags
5494
+ /^[a-z]{2}-[A-Z]{2}$/,
5495
+ // Text encodings
5496
+ /^utf-?8|ascii|latin|iso-8859/i,
5497
+ // MIME types
5498
+ /^(?:application|text|image|audio|video)\//,
5499
+ // CSS keyword values
5500
+ /^(?:inherit|none|auto|block|flex|grid|absolute|relative|fixed|px|em|rem|%)/,
5501
+ // Developer-placeholder tokens
5502
+ /^(?:test|example|sample|demo|placeholder|temp|tmp|foo|bar|baz|lorem|ipsum)/i,
5503
+ // XML / DTD markers
5504
+ /DTD|DOCTYPE|w3\.org|apple\.com\/DTDs/i,
5505
+ /xmlns|schema|xsd|xsi/i,
5506
+ // NEW — added in Wave 3.2 for context-aware FP reduction
5507
+ // ──────────────────────────────────────────────────────
5508
+ // Tailwind JIT / CSS-in-JS class-name fingerprints, e.g. "css-2kx3yr8",
5509
+ // "tw-abc12def", "jss-1a2b3c4d". Typically prefix + 6-12 hex-ish chars.
5510
+ /^(?:css|tw|jss|emotion|styled|mui|chakra)-[a-z0-9]{4,14}$/i,
5511
+ // SVG path data — starts with a path command letter followed by coords.
5512
+ // These can get very long and high-entropy but are never secrets.
5513
+ /^[MmLlHhVvCcSsQqTtAaZz][\d.,\s\-MmLlHhVvCcSsQqTtAaZz]{10,}$/,
5514
+ // Next.js / Vite / webpack content-addressed asset filenames, e.g.
5515
+ // "main.4e5f6a78.js", "chunk-2a3b.js", "_next/static/chunks/pages-xyz".
5516
+ /\.[0-9a-f]{6,16}\.(?:js|css|mjs|woff2?|ttf|png|jpg|svg)(?:\?.*)?$/i,
5517
+ /^_next\//,
5518
+ // Publishable / client-side keys from common vendors. Flagged by their
5519
+ // own service-specific rules if they look wrong, but entropy should NOT
5520
+ // double-flag these. They are designed to ship to the browser.
5521
+ /^pk_(?:live|test|[a-z0-9]+)_/,
5522
+ // Stripe / Clerk publishable
5523
+ /^NEXT_PUBLIC_|^VITE_|^REACT_APP_/,
5524
+ // Build-time public env vars
5525
+ /^pub_/,
5526
+ // Segment etc.
5527
+ /^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\./,
5528
+ // JWT header.payload prefix — don't flag solely on entropy
5529
+ // Content-Security-Policy hashes / nonces in HTML/JSON
5530
+ /^'sha\d+-/,
5531
+ /^nonce-/i,
5532
+ // Embedded data URIs
5533
+ /^data:[a-z]+\//i
5534
+ ];
5535
+ var SKIP_FILES = /\.(css|scss|less|svg|md|txt|html?|xml|yml|yaml|toml|lock|map|woff2?|ttf|eot|ico|png|jpg|gif|webp)$/i;
5536
+ var SKIP_FILENAMES = /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|shrinkwrap\.json)$/i;
5537
+ var SAFE_VAR_NAMES = /(?:description|message|text|label|title|content|template|html|svg|css|style|class(?:Name)?|query|mutation|schema|regex|pattern|format|placeholder|comment|url|path|route|endpoint|href|src|alt|name|type|version|encoding|charset|locale|translation|copy|prose|markdown|slug|handle)/i;
5538
+ var HASH_LIKE_VAR_NAMES = /(?:^|[^a-z])(?:hash|digest|checksum|fingerprint|etag|crc|md5|sha1|sha256|sha512|contenthash|buildid|revision|commit|sri|integrity|cacheKey|fileHash|assetId|versionId)(?:$|[^a-z])/i;
5539
+ var HASH_PREFIX_RE = /^(?:sha\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;
5540
+ var SECRET_VAR_NAMES = /(?:^|[^a-z])(?:key|secret|token|password|passwd|pwd|api[_-]?key|auth|credential|private|signing|bearer|access[_-]?token|refresh[_-]?token|session[_-]?id)(?:$|[^a-z])/i;
5541
+ function getSnippet2(content, line) {
5542
+ const lines = content.split("\n");
5543
+ const start = Math.max(0, line - 2);
5544
+ const end = Math.min(lines.length, line + 2);
5545
+ return lines.slice(start, end).map((l, i) => {
5546
+ const lineNum = start + i + 1;
5547
+ const prefix = lineNum === line ? ">" : " ";
5548
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5549
+ }).join("\n");
5550
+ }
5551
+ function scanEntropy(files) {
5552
+ const findings = [];
5553
+ for (const { path: filePath, content } of files) {
5554
+ if (SKIP_FILES.test(filePath)) continue;
5555
+ if (SKIP_FILENAMES.test(filePath)) continue;
5556
+ const basename = filePath.split("/").pop() || "";
5557
+ if (SKIP_FILENAMES.test(basename)) continue;
5558
+ if (filePath.includes("node_modules")) continue;
5559
+ if (filePath.includes(".min.")) continue;
5560
+ if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
5561
+ if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
5562
+ const lines = content.split("\n");
5563
+ for (let i = 0; i < lines.length; i++) {
5564
+ const line = lines[i];
5565
+ const trimmed = line.trimStart();
5566
+ if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*") || trimmed.startsWith("/*")) continue;
5567
+ const stringPattern = /(?:[:=]\s*)(["'`])([^"'`\n]{20,120})\1/g;
5568
+ let match;
5569
+ while ((match = stringPattern.exec(line)) !== null) {
5570
+ const value = match[2];
5571
+ if (SAFE_PATTERNS.some((p) => p.test(value))) continue;
5572
+ if (HASH_PREFIX_RE.test(value)) continue;
5573
+ const beforeAssign = line.substring(0, match.index);
5574
+ if (SAFE_VAR_NAMES.test(beforeAssign)) continue;
5575
+ if (/^https?:\/\/[^:@]*$/.test(value)) continue;
5576
+ if ((value.match(/\s/g) || []).length > 2) continue;
5577
+ const isHex = /^[0-9a-fA-F]+$/.test(value);
5578
+ const isBase64 = /^[A-Za-z0-9+/]+=*$/.test(value);
5579
+ let threshold = 4;
5580
+ if (isHex) threshold = 3;
5581
+ else if (isBase64) threshold = 4.5;
5582
+ if (value.length < 20) continue;
5583
+ const entropy = shannonEntropy(value);
5584
+ if (entropy < threshold) continue;
5585
+ const varName = beforeAssign.match(/(\w+)\s*[:=]\s*$/)?.[1] || "";
5586
+ if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;
5587
+ const isLikelySecret = SECRET_VAR_NAMES.test(varName);
5588
+ if (entropy < 4.5 && !isLikelySecret) continue;
5589
+ const masked = value.substring(0, 6) + "..." + value.substring(value.length - 4);
5590
+ findings.push({
5591
+ id: `ENTROPY-${filePath}:${i + 1}`,
5592
+ rule: "ENTROPY",
5593
+ severity: isLikelySecret ? "critical" : "high",
5594
+ title: "High-Entropy String Detected (Possible Secret)",
5595
+ description: `Found a high-entropy string (${entropy.toFixed(1)} bits) that may be a hardcoded secret or API key: "${masked}"`,
5596
+ file: filePath,
5597
+ line: i + 1,
5598
+ snippet: getSnippet2(content, i + 1),
5599
+ fix: "If this is a secret, move it to an environment variable. If it's not a secret (e.g., hash, encoded data), add it to .xploitscanignore.",
5600
+ category: "Secrets",
5601
+ source: "custom",
5602
+ owasp: "A02:2021",
5603
+ cwe: "CWE-798"
5604
+ });
5605
+ }
5606
+ }
5607
+ }
5608
+ return findings;
5609
+ }
5427
5610
  // Annotate the CommonJS export names for ESM import in node:
5428
5611
  0 && (module.exports = {
5429
5612
  allCustomRules,
@@ -5554,6 +5737,7 @@ async function filterFalsePositives(findings, fileContents) {
5554
5737
  regexDos,
5555
5738
  runCustomRules,
5556
5739
  s3BucketNoEncryption,
5740
+ scanEntropy,
5557
5741
  secretInBundleConfig,
5558
5742
  secretInCLIArgument,
5559
5743
  secretInErrorResponse,