All files VulnerabilityScanner.ts

100% Statements 21/21
66.66% Branches 2/3
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338  1x                       1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1x   8x 8x   8x 256x     256x 8x 8x   8x                                 8x   8x                 8x 7x     7x 8x 8x      
import { CodeFinding, SeverityLevel, VulnerabilityResult } from '../core/interfaces';
import { uuid } from './utils';
 
interface VulnPattern {
  id: string;
  title: string;
  pattern: RegExp;
  severity: SeverityLevel;
  description: string;
  recommendation: string;
  cveId?: string;
}
 
const VULNERABILITY_PATTERNS: VulnPattern[] = [
  // Injection
  {
    id: 'SQL-001', title: 'SQL Injection Risk',
    pattern: /(\bquery\b|\bexec\b|\bexecute\b)\s*\(\s*[`'"]\s*(SELECT|INSERT|UPDATE|DELETE|DROP)/gi,
    severity: 'critical',
    description: 'Direct string concatenation in SQL queries allows injection attacks.',
    recommendation: 'Use parameterized queries or prepared statements.',
    cveId: 'CWE-89',
  },
  {
    id: 'CMD-001', title: 'Command Injection Risk',
    pattern: /\b(exec|execSync|spawn|spawnSync|system|popen|shell_exec)\s*\(\s*[`'"].*\$\{/g,
    severity: 'critical',
    description: 'User-controlled input passed to shell command execution.',
    recommendation: 'Sanitize inputs and use parameterized command APIs.',
    cveId: 'CWE-78',
  },
  // XSS
  {
    id: 'XSS-001', title: 'Cross-Site Scripting (innerHTML)',
    pattern: /\.innerHTML\s*=\s*(?!['"`]\s*['"`])/g,
    severity: 'high',
    description: 'Setting innerHTML with dynamic content enables XSS attacks.',
    recommendation: 'Use textContent or a sanitization library like DOMPurify.',
    cveId: 'CWE-79',
  },
  {
    id: 'XSS-002', title: 'React dangerouslySetInnerHTML',
    pattern: /dangerouslySetInnerHTML\s*=\s*\{\s*\{/g,
    severity: 'high',
    description: 'dangerouslySetInnerHTML bypasses React XSS protections.',
    recommendation: 'Sanitize HTML with DOMPurify before setting dangerouslySetInnerHTML.',
    cveId: 'CWE-79',
  },
  {
    id: 'XSS-003', title: 'document.write Usage',
    pattern: /document\.write\s*\(/g,
    severity: 'high',
    description: 'document.write can introduce XSS vulnerabilities.',
    recommendation: 'Use DOM manipulation methods (createElement, appendChild) instead.',
    cveId: 'CWE-79',
  },
  // Eval
  {
    id: 'EVAL-001', title: 'eval() Usage',
    pattern: /\beval\s*\(/g,
    severity: 'critical',
    description: 'eval() executes arbitrary code and is a severe security risk.',
    recommendation: 'Replace eval() with JSON.parse() for data or safer alternatives.',
    cveId: 'CWE-95',
  },
  {
    id: 'EVAL-002', title: 'Function Constructor',
    pattern: /new\s+Function\s*\(/g,
    severity: 'high',
    description: 'Function constructor executes arbitrary code like eval().',
    recommendation: 'Avoid dynamic code execution.',
    cveId: 'CWE-95',
  },
  // Hardcoded secrets
  {
    id: 'SEC-001', title: 'Hardcoded API Key',
    pattern: /(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token)\s*[:=]\s*['"`][A-Za-z0-9_\-]{20,}['"`]/gi,
    severity: 'critical',
    description: 'API key or token hardcoded in source code.',
    recommendation: 'Move secrets to environment variables or a vault service.',
    cveId: 'CWE-798',
  },
  {
    id: 'SEC-002', title: 'Hardcoded Password',
    pattern: /(?:password|passwd|pwd|secret)\s*[:=]\s*['"`][^'"`\s]{6,}['"`]/gi,
    severity: 'critical',
    description: 'Password hardcoded in source code.',
    recommendation: 'Use environment variables, secrets manager, or prompt at runtime.',
    cveId: 'CWE-798',
  },
  {
    id: 'SEC-003', title: 'AWS Access Key Pattern',
    pattern: /AKIA[0-9A-Z]{16}/g,
    severity: 'critical',
    description: 'AWS Access Key ID detected in code.',
    recommendation: 'Rotate the key immediately and use IAM roles or environment variables.',
    cveId: 'CWE-798',
  },
  // Insecure protocols
  {
    id: 'NET-001', title: 'Insecure HTTP Protocol',
    pattern: /['"`]http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0)/g,
    severity: 'medium',
    description: 'Using HTTP instead of HTTPS for external communication.',
    recommendation: 'Use HTTPS to encrypt data in transit.',
    cveId: 'CWE-319',
  },
  // Path traversal
  {
    id: 'PATH-001', title: 'Path Traversal Risk',
    pattern: /readFile(?:Sync)?\s*\([^)]*\.\.[/\\]/g,
    severity: 'high',
    description: 'Path traversal using ../ may expose files outside intended directory.',
    recommendation: 'Use path.resolve() and validate paths against a whitelist.',
    cveId: 'CWE-22',
  },
  // Prototype pollution
  {
    id: 'PROTO-001', title: 'Prototype Pollution Risk',
    pattern: /\.__proto__\s*=/g,
    severity: 'high',
    description: 'Assigning to __proto__ can corrupt object prototype chain.',
    recommendation: 'Use Object.create(null) for maps or Object.assign for merging.',
    cveId: 'CWE-1321',
  },
  // Insecure random
  {
    id: 'RAND-001', title: 'Insecure Random for Security',
    pattern: /Math\.random\(\)/g,
    severity: 'medium',
    description: 'Math.random() is not cryptographically secure.',
    recommendation: 'Use crypto.randomBytes() or crypto.getRandomValues() for security tokens.',
    cveId: 'CWE-338',
  },
  // Open redirect
  {
    id: 'REDIR-001', title: 'Open Redirect Risk',
    pattern: /(?:res\.redirect|window\.location\.href|location\.replace)\s*\([^)]*req\.(query|params|body)/g,
    severity: 'high',
    description: 'Redirect URL derived from user input enables open redirect attacks.',
    recommendation: 'Validate redirect URLs against an allowlist.',
    cveId: 'CWE-601',
  },
 
  // ─── Terraform / HCL ──────────────────────────────────────────────────────
  {
    id: 'TF-001', title: 'Terraform: Wildcard IAM Permission',
    pattern: /"Action"\s*:\s*"\*"/g,
    severity: 'critical',
    description: 'IAM policy grants all actions ("Action": "*"). Violates least-privilege principle.',
    recommendation: 'Restrict IAM actions to the minimum required (e.g., "s3:GetObject").',
    cveId: 'CWE-732',
  },
  {
    id: 'TF-002', title: 'Terraform: Open Ingress (0.0.0.0/0)',
    pattern: /cidr_blocks\s*=\s*\["0\.0\.0\.0\/0"\]/g,
    severity: 'high',
    description: 'Security group allows inbound traffic from any IP address.',
    recommendation: 'Restrict cidr_blocks to known IP ranges. Use VPC endpoints where possible.',
    cveId: 'CWE-284',
  },
  {
    id: 'TF-003', title: 'Terraform: Public S3 Bucket ACL',
    pattern: /acl\s*=\s*"public-read(?:-write)?"/g,
    severity: 'critical',
    description: 'S3 bucket ACL set to public-read or public-read-write exposes all objects.',
    recommendation: 'Set acl to "private" and use bucket policies for controlled access.',
    cveId: 'CWE-732',
  },
  {
    id: 'TF-004', title: 'Terraform: Unencrypted RDS Storage',
    pattern: /storage_encrypted\s*=\s*false/g,
    severity: 'high',
    description: 'RDS instance storage encryption is disabled.',
    recommendation: 'Set storage_encrypted = true. Required for PCI DSS and HIPAA compliance.',
    cveId: 'CWE-312',
  },
  {
    id: 'TF-005', title: 'Terraform: Hardcoded Secret in Provider',
    pattern: /(?:access_key|secret_key|password|token)\s*=\s*"[A-Za-z0-9+/=_\-]{8,}"/g,
    severity: 'critical',
    description: 'Credentials hardcoded in Terraform provider or resource block.',
    recommendation: 'Use environment variables (AWS_ACCESS_KEY_ID) or a secrets manager like HashiCorp Vault.',
    cveId: 'CWE-798',
  },
  {
    id: 'TF-006', title: 'Terraform: Skip TLS Verification',
    pattern: /skip_tls_verify\s*=\s*true/g,
    severity: 'high',
    description: 'TLS certificate verification is disabled, enabling man-in-the-middle attacks.',
    recommendation: 'Remove skip_tls_verify or set to false. Use trusted CA certificates.',
    cveId: 'CWE-295',
  },
 
  // ─── Dockerfile ───────────────────────────────────────────────────────────
  {
    id: 'DOCKER-001', title: 'Dockerfile: Running as Root',
    pattern: /^USER\s+root\s*$/gm,
    severity: 'high',
    description: 'Container runs as root user, expanding attack surface if compromised.',
    recommendation: 'Add a non-root USER directive: RUN adduser -D appuser && USER appuser',
    cveId: 'CWE-250',
  },
  {
    id: 'DOCKER-002', title: 'Dockerfile: Unpinned Image Tag (latest)',
    pattern: /FROM\s+\S+:latest\b/gi,
    severity: 'medium',
    description: 'Using :latest tag means the image changes on every pull — non-deterministic builds.',
    recommendation: 'Pin to a specific digest or version tag: FROM node:20.11.1-alpine3.19',
  },
  {
    id: 'DOCKER-003', title: 'Dockerfile: ADD Instead of COPY',
    pattern: /^ADD\s+(?!http)/gm,
    severity: 'medium',
    description: 'ADD can auto-extract archives and fetch from URLs. COPY is explicit and safer.',
    recommendation: 'Replace ADD with COPY for local files. Use RUN curl/wget for remote resources.',
  },
  {
    id: 'DOCKER-004', title: 'Dockerfile: Hardcoded Secret in ENV',
    pattern: /^ENV\s+\S*(?:PASSWORD|SECRET|TOKEN|KEY|API_KEY)\S*\s+\S+/gim,
    severity: 'critical',
    description: 'Secret hardcoded in ENV directive is visible in image layers and docker inspect.',
    recommendation: 'Use Docker secrets, --secret mount, or pass via environment at runtime.',
    cveId: 'CWE-798',
  },
 
  // ─── Kubernetes YAML ──────────────────────────────────────────────────────
  {
    id: 'K8S-001', title: 'Kubernetes: Privileged Container',
    pattern: /privileged\s*:\s*true/g,
    severity: 'critical',
    description: 'Privileged containers have root access to the host kernel. Full host compromise if exploited.',
    recommendation: 'Remove privileged: true. Use specific capabilities instead (securityContext.capabilities.add).',
    cveId: 'CWE-250',
  },
  {
    id: 'K8S-002', title: 'Kubernetes: Host Network Access',
    pattern: /hostNetwork\s*:\s*true/g,
    severity: 'high',
    description: 'Pod shares the host network namespace, bypassing network isolation.',
    recommendation: 'Remove hostNetwork: true. Use Kubernetes Services for pod communication.',
    cveId: 'CWE-284',
  },
  {
    id: 'K8S-003', title: 'Kubernetes: Allow Privilege Escalation',
    pattern: /allowPrivilegeEscalation\s*:\s*true/g,
    severity: 'high',
    description: 'Container process can gain more privileges than its parent.',
    recommendation: 'Set allowPrivilegeEscalation: false in securityContext.',
    cveId: 'CWE-269',
  },
  {
    id: 'K8S-004', title: 'Kubernetes: No Resource Limits',
    pattern: /containers:[\s\S]{0,500}image:\s*\S+(?![\s\S]{0,300}resources:)/g,
    severity: 'medium',
    description: 'Container defined without resource limits can cause node resource exhaustion (DoS).',
    recommendation: 'Add resources.limits (cpu, memory) to all container specs.',
    cveId: 'CWE-400',
  },
 
  // ─── CI/CD Pipelines ──────────────────────────────────────────────────────
  {
    id: 'CICD-001', title: 'CI/CD: Hardcoded Secret in Pipeline',
    pattern: /(?:password|token|secret|api_key|apikey)\s*:\s*(?!"\$\{\{)["'][A-Za-z0-9+/=_\-]{8,}["']/gi,
    severity: 'critical',
    description: 'Secret hardcoded in CI/CD pipeline file rather than using repository secrets.',
    recommendation: 'Use ${{ secrets.MY_SECRET }} (GitHub Actions) or $CI_VARIABLE (GitLab CI).',
    cveId: 'CWE-798',
  },
  {
    id: 'CICD-002', title: 'CI/CD: pull_request_target Without Permissions',
    pattern: /on:\s*[\s\S]*pull_request_target/g,
    severity: 'high',
    description: 'pull_request_target runs with write permissions in the base repo context. Allows secrets exfiltration from forked PRs.',
    recommendation: 'Add explicit permissions block with minimum required scopes, or use pull_request instead.',
    cveId: 'CWE-284',
  },
  {
    id: 'CICD-003', title: 'CI/CD: Unverified Script Piped to Shell',
    pattern: /curl\s+[^|]*\|\s*(?:bash|sh|python|ruby)/g,
    severity: 'critical',
    description: 'Downloading and executing scripts without verification allows supply-chain attacks.',
    recommendation: 'Download the script, verify its checksum (sha256sum), then execute separately.',
    cveId: 'CWE-494',
  },
];
 
export class VulnerabilityScanner {
  scanCode(code: string, filePath: string): VulnerabilityResult {
    const lines = code.split('\n');
    const findings: CodeFinding[] = [];
 
    for (const vuln of VULNERABILITY_PATTERNS) {
      const pattern = new RegExp(vuln.pattern.source, vuln.pattern.flags);
      let match: RegExpExecArray | null;
 
      while ((match = pattern.exec(code)) !== null) {
        const lineIndex = code.substring(0, match.index).split('\n').length;
        const line = lines[lineIndex - 1] ?? '';
 
        findings.push({
          id: uuid(),
          category: 'vulnerability',
          severity: vuln.severity,
          title: vuln.title,
          description: vuln.description,
          filePath,
          startLine: lineIndex,
          endLine: lineIndex,
          snippet: line.trim(),
          confidence: 0.85,
          recommendation: vuln.recommendation,
          cveId: vuln.cveId,
        });
      }
    }
 
    const riskScore = this._computeRiskScore(findings);
 
    return {
      filePath,
      findings,
      riskScore,
      analyzedAt: new Date().toISOString(),
    };
  }
 
  private _computeRiskScore(findings: CodeFinding[]): number {
    if (!findings.length) return 0;
    const weights: Record<SeverityLevel, number> = {
      critical: 10, high: 7, medium: 4, low: 1, info: 0
    };
    const maxPossible = findings.length * 10;
    const actual = findings.reduce((s, f) => s + weights[f.severity], 0);
    return Math.min(10, (actual / maxPossible) * 10 + findings.filter(f => f.severity === 'critical').length * 2);
  }
}