Senior SecOps Engineer Complete toolkit for Security Operations including vulnerability management, compliance verification, secure coding practices, and security automation. --- Table of Contents - Core Capabilities - Workflows - Tool Reference - Security Standards - Compliance Frameworks - Best Practices --- Core Capabilities 1. Security Scanner Scan source code for security vulnerabilities including hardcoded secrets, SQL injection, XSS, command injection, and path traversal. Detects: - Hardcoded secrets (API keys, passwords, AWS credentials, GitHub tokens, private keys) - SQL injection pa…

)\n email: str\n age: Optional[int] = None\n\n @validator('email')\n def validate_email(cls, v):\n # Use proper email validation\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}

Senior SecOps Engineer Complete toolkit for Security Operations including vulnerability management, compliance verification, secure coding practices, and security automation. --- Table of Contents - Core Capabilities - Workflows - Tool Reference - Security Standards - Compliance Frameworks - Best Practices --- Core Capabilities 1. Security Scanner Scan source code for security vulnerabilities including hardcoded secrets, SQL injection, XSS, command injection, and path traversal. Detects: - Hardcoded secrets (API keys, passwords, AWS credentials, GitHub tokens, private keys) - SQL injection pa…

\n if not re.match(pattern, v):\n raise ValueError('Invalid email format')\n return v.lower()\n\n @validator('age')\n def validate_age(cls, v):\n if v is not None and (v \u003c 0 or v > 150):\n raise ValueError('Age must be between 0 and 150')\n return v\n```\n\n### Output Encoding\n\n```python\nimport html\nimport json\nfrom urllib.parse import quote\n\ndef encode_for_html(data: str) -> str:\n \"\"\"Encode data for safe HTML output.\"\"\"\n return html.escape(data)\n\ndef encode_for_javascript(data: str) -> str:\n \"\"\"Encode data for safe JavaScript string.\"\"\"\n return json.dumps(data)\n\ndef encode_for_url(data: str) -> str:\n \"\"\"Encode data for safe URL parameter.\"\"\"\n return quote(data, safe='')\n\ndef encode_for_css(data: str) -> str:\n \"\"\"Encode data for safe CSS value.\"\"\"\n return ''.join(\n c if c.isalnum() else f'\\\\{ord(c):06x}'\n for c in data\n )\n```\n\n### Error Handling\n\n```python\nimport logging\nfrom typing import Dict, Any\n\nlogger = logging.getLogger(__name__)\n\nclass SecurityException(Exception):\n \"\"\"Base exception for security-related errors.\"\"\"\n\n def __init__(self, message: str, internal_details: str = None):\n # User-facing message (safe to display)\n self.message = message\n # Internal details (for logging only)\n self.internal_details = internal_details\n super().__init__(message)\n\ndef handle_request():\n try:\n process_sensitive_data()\n except DatabaseError as e:\n # Log full details internally\n logger.error(f\"Database error: {e}\", exc_info=True)\n # Return generic message to user\n raise SecurityException(\n \"An error occurred processing your request\",\n internal_details=str(e)\n )\n except Exception as e:\n logger.error(f\"Unexpected error: {e}\", exc_info=True)\n raise SecurityException(\"An unexpected error occurred\")\n```\n\n---\n\n## Authentication Standards\n\n### Password Requirements\n\n```python\nimport re\nfrom typing import Tuple\n\ndef validate_password(password: str) -> Tuple[bool, str]:\n \"\"\"\n Validate password against security requirements.\n\n Requirements:\n - Minimum 12 characters\n - At least one uppercase letter\n - At least one lowercase letter\n - At least one digit\n - At least one special character\n - Not in common password list\n \"\"\"\n if len(password) \u003c 12:\n return False, \"Password must be at least 12 characters\"\n\n if not re.search(r'[A-Z]', password):\n return False, \"Password must contain uppercase letter\"\n\n if not re.search(r'[a-z]', password):\n return False, \"Password must contain lowercase letter\"\n\n if not re.search(r'\\d', password):\n return False, \"Password must contain a digit\"\n\n if not re.search(r'[!@#$%^&*(),.?\":{}|\u003c>]', password):\n return False, \"Password must contain special character\"\n\n # Check against common passwords (use haveibeenpwned API in production)\n common_passwords = {'password123', 'qwerty123456', 'admin123456'}\n if password.lower() in common_passwords:\n return False, \"Password is too common\"\n\n return True, \"Password meets requirements\"\n```\n\n### JWT Best Practices\n\n```python\nimport jwt\nfrom datetime import datetime, timedelta\nfrom typing import Dict, Optional\n\nclass JWTManager:\n def __init__(self, secret_key: str, algorithm: str = 'HS256'):\n self.secret_key = secret_key\n self.algorithm = algorithm\n self.access_token_expiry = timedelta(minutes=15)\n self.refresh_token_expiry = timedelta(days=7)\n\n def create_access_token(self, user_id: str, roles: list) -> str:\n payload = {\n 'sub': user_id,\n 'roles': roles,\n 'type': 'access',\n 'iat': datetime.utcnow(),\n 'exp': datetime.utcnow() + self.access_token_expiry,\n 'jti': self._generate_jti() # Unique token ID for revocation\n }\n return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)\n\n def verify_token(self, token: str) -> Optional[Dict]:\n try:\n payload = jwt.decode(\n token,\n self.secret_key,\n algorithms=[self.algorithm],\n options={\n 'require': ['exp', 'iat', 'sub', 'jti'],\n 'verify_exp': True\n }\n )\n\n # Check if token is revoked\n if self._is_token_revoked(payload['jti']):\n return None\n\n return payload\n except jwt.ExpiredSignatureError:\n return None\n except jwt.InvalidTokenError:\n return None\n```\n\n### MFA Implementation\n\n```python\nimport pyotp\nimport qrcode\nfrom io import BytesIO\nimport base64\n\nclass TOTPManager:\n def __init__(self, issuer: str = \"MyApp\"):\n self.issuer = issuer\n\n def generate_secret(self) -> str:\n \"\"\"Generate a new TOTP secret for a user.\"\"\"\n return pyotp.random_base32()\n\n def get_provisioning_uri(self, secret: str, email: str) -> str:\n \"\"\"Generate URI for QR code.\"\"\"\n totp = pyotp.TOTP(secret)\n return totp.provisioning_uri(name=email, issuer_name=self.issuer)\n\n def generate_qr_code(self, provisioning_uri: str) -> str:\n \"\"\"Generate base64-encoded QR code image.\"\"\"\n qr = qrcode.QRCode(version=1, box_size=10, border=5)\n qr.add_data(provisioning_uri)\n qr.make(fit=True)\n\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n buffer = BytesIO()\n img.save(buffer, format='PNG')\n return base64.b64encode(buffer.getvalue()).decode()\n\n def verify_totp(self, secret: str, code: str) -> bool:\n \"\"\"Verify TOTP code with time window tolerance.\"\"\"\n totp = pyotp.TOTP(secret)\n # Allow 1 period before/after for clock skew\n return totp.verify(code, valid_window=1)\n```\n\n---\n\n## API Security\n\n### Rate Limiting\n\n```python\nfrom functools import wraps\nfrom flask import request, jsonify\nimport time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n def __init__(self, requests_per_minute: int = 60):\n self.requests_per_minute = requests_per_minute\n self.requests = defaultdict(list)\n self.lock = threading.Lock()\n\n def is_rate_limited(self, identifier: str) -> bool:\n with self.lock:\n now = time.time()\n minute_ago = now - 60\n\n # Clean old requests\n self.requests[identifier] = [\n req_time for req_time in self.requests[identifier]\n if req_time > minute_ago\n ]\n\n if len(self.requests[identifier]) >= self.requests_per_minute:\n return True\n\n self.requests[identifier].append(now)\n return False\n\nrate_limiter = RateLimiter(requests_per_minute=100)\n\ndef rate_limit(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n identifier = request.remote_addr\n\n if rate_limiter.is_rate_limited(identifier):\n return jsonify({\n 'error': 'Rate limit exceeded',\n 'retry_after': 60\n }), 429\n\n return f(*args, **kwargs)\n return decorated_function\n```\n\n### API Key Validation\n\n```python\nimport hashlib\nimport secrets\nfrom datetime import datetime\nfrom typing import Optional, Dict\n\nclass APIKeyManager:\n def __init__(self, db):\n self.db = db\n\n def generate_api_key(self, user_id: str, name: str, scopes: list) -> Dict:\n \"\"\"Generate a new API key.\"\"\"\n # Generate key with prefix for identification\n raw_key = f\"sk_live_{secrets.token_urlsafe(32)}\"\n\n # Store hash only\n key_hash = hashlib.sha256(raw_key.encode()).hexdigest()\n\n api_key_record = {\n 'id': secrets.token_urlsafe(16),\n 'user_id': user_id,\n 'name': name,\n 'key_hash': key_hash,\n 'key_prefix': raw_key[:12], # Store prefix for identification\n 'scopes': scopes,\n 'created_at': datetime.utcnow(),\n 'last_used_at': None\n }\n\n self.db.api_keys.insert(api_key_record)\n\n # Return raw key only once\n return {\n 'key': raw_key,\n 'id': api_key_record['id'],\n 'scopes': scopes\n }\n\n def validate_api_key(self, raw_key: str) -> Optional[Dict]:\n \"\"\"Validate an API key and return associated data.\"\"\"\n key_hash = hashlib.sha256(raw_key.encode()).hexdigest()\n\n api_key = self.db.api_keys.find_one({'key_hash': key_hash})\n\n if not api_key:\n return None\n\n # Update last used timestamp\n self.db.api_keys.update(\n {'id': api_key['id']},\n {'last_used_at': datetime.utcnow()}\n )\n\n return {\n 'user_id': api_key['user_id'],\n 'scopes': api_key['scopes']\n }\n```\n\n---\n\n## Secrets Management\n\n### Environment Variables\n\n```python\nimport os\nfrom typing import Optional\nfrom dataclasses import dataclass\n\n@dataclass\nclass AppSecrets:\n database_url: str\n jwt_secret: str\n api_key: str\n encryption_key: str\n\ndef load_secrets() -> AppSecrets:\n \"\"\"Load secrets from environment with validation.\"\"\"\n\n def get_required(name: str) -> str:\n value = os.environ.get(name)\n if not value:\n raise ValueError(f\"Required environment variable {name} is not set\")\n return value\n\n return AppSecrets(\n database_url=get_required('DATABASE_URL'),\n jwt_secret=get_required('JWT_SECRET'),\n api_key=get_required('API_KEY'),\n encryption_key=get_required('ENCRYPTION_KEY')\n )\n\n# Never log secrets\nimport logging\n\nclass SecretFilter(logging.Filter):\n \"\"\"Filter to redact secrets from logs.\"\"\"\n\n def __init__(self, secrets: list):\n super().__init__()\n self.secrets = secrets\n\n def filter(self, record):\n message = record.getMessage()\n for secret in self.secrets:\n if secret in message:\n record.msg = record.msg.replace(secret, '[REDACTED]')\n return True\n```\n\n### HashiCorp Vault Integration\n\n```python\nimport hvac\nfrom typing import Dict, Optional\n\nclass VaultClient:\n def __init__(self, url: str, token: str = None, role_id: str = None, secret_id: str = None):\n self.client = hvac.Client(url=url)\n\n if token:\n self.client.token = token\n elif role_id and secret_id:\n # AppRole authentication\n self.client.auth.approle.login(\n role_id=role_id,\n secret_id=secret_id\n )\n\n def get_secret(self, path: str, key: str) -> Optional[str]:\n \"\"\"Retrieve a secret from Vault.\"\"\"\n try:\n response = self.client.secrets.kv.v2.read_secret_version(path=path)\n return response['data']['data'].get(key)\n except hvac.exceptions.InvalidPath:\n return None\n\n def get_database_credentials(self, role: str) -> Dict[str, str]:\n \"\"\"Get dynamic database credentials.\"\"\"\n response = self.client.secrets.database.generate_credentials(name=role)\n return {\n 'username': response['data']['username'],\n 'password': response['data']['password'],\n 'lease_id': response['lease_id'],\n 'lease_duration': response['lease_duration']\n }\n```\n\n---\n\n## Security Headers\n\n### HTTP Security Headers\n\n```python\nfrom flask import Flask, Response\n\ndef add_security_headers(response: Response) -> Response:\n \"\"\"Add security headers to HTTP response.\"\"\"\n\n # Prevent clickjacking\n response.headers['X-Frame-Options'] = 'DENY'\n\n # Enable XSS filter\n response.headers['X-XSS-Protection'] = '1; mode=block'\n\n # Prevent MIME type sniffing\n response.headers['X-Content-Type-Options'] = 'nosniff'\n\n # Referrer policy\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n\n # Content Security Policy\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'unsafe-inline'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"frame-ancestors 'none'; \"\n \"form-action 'self'\"\n )\n\n # HSTS (enable only with valid HTTPS)\n response.headers['Strict-Transport-Security'] = (\n 'max-age=31536000; includeSubDomains; preload'\n )\n\n # Permissions Policy\n response.headers['Permissions-Policy'] = (\n 'geolocation=(), microphone=(), camera=()'\n )\n\n return response\n\napp = Flask(__name__)\napp.after_request(add_security_headers)\n```\n\n---\n\n## Quick Reference\n\n### Security Checklist\n\n| Category | Check | Priority |\n|----------|-------|----------|\n| Authentication | MFA enabled | Critical |\n| Authentication | Password policy enforced | Critical |\n| Authorization | RBAC implemented | Critical |\n| Input | All inputs validated | Critical |\n| Injection | Parameterized queries | Critical |\n| Crypto | TLS 1.2+ enforced | Critical |\n| Secrets | No hardcoded secrets | Critical |\n| Headers | Security headers set | High |\n| Logging | Security events logged | High |\n| Dependencies | No known vulnerabilities | High |\n\n### Tool Recommendations\n\n| Purpose | Tool | Usage |\n|---------|------|-------|\n| SAST | Semgrep | `semgrep --config auto .` |\n| SAST | Bandit (Python) | `bandit -r src/` |\n| Secrets | Gitleaks | `gitleaks detect --source .` |\n| Dependencies | Snyk | `snyk test` |\n| Container | Trivy | `trivy image myapp:latest` |\n| DAST | OWASP ZAP | Dynamic scanning |\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":20401,"content_sha256":"fabad3e5b494140e6954395c23d40a36f3c5f32950ae0409c954efe9229e4175"},{"filename":"references/vulnerability_management_guide.md","content":"# Vulnerability Management Guide\n\nComplete workflow for vulnerability identification, assessment, prioritization, and remediation.\n\n---\n\n## Table of Contents\n\n- [Vulnerability Lifecycle](#vulnerability-lifecycle)\n- [CVE Triage Process](#cve-triage-process)\n- [CVSS Scoring](#cvss-scoring)\n- [Remediation Workflows](#remediation-workflows)\n- [Dependency Scanning](#dependency-scanning)\n- [Security Incident Response](#security-incident-response)\n\n---\n\n## Vulnerability Lifecycle\n\n### Overview\n\n```\n┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐\n│ DISCOVER │ → │ ASSESS │ → │ PRIORITIZE │ → │ REMEDIATE │\n│ │ │ │ │ │ │ │\n│ - Scanning │ │ - CVSS │ │ - Risk │ │ - Patch │\n│ - Reports │ │ - Context │ │ - Business │ │ - Mitigate │\n│ - Audits │ │ - Impact │ │ - SLA │ │ - Accept │\n└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘\n │\n ▼\n ┌─────────────┐\n │ VERIFY │\n │ │\n │ - Retest │\n │ - Close │\n └─────────────┘\n```\n\n### State Definitions\n\n| State | Description | Owner |\n|-------|-------------|-------|\n| New | Vulnerability discovered, not yet triaged | Security Team |\n| Triaging | Under assessment for severity and impact | Security Team |\n| Assigned | Assigned to development team for fix | Dev Team |\n| In Progress | Fix being developed | Dev Team |\n| In Review | Fix in code review | Dev Team |\n| Testing | Fix being tested | QA Team |\n| Deployed | Fix deployed to production | DevOps Team |\n| Verified | Fix confirmed effective | Security Team |\n| Closed | Vulnerability resolved | Security Team |\n| Accepted Risk | Risk accepted with justification | CISO |\n\n---\n\n## CVE Triage Process\n\n### Step 1: Initial Assessment\n\n```python\ndef triage_cve(cve_id: str, affected_systems: list) -> dict:\n \"\"\"\n Perform initial triage of a CVE.\n\n Returns triage assessment with severity and recommended actions.\n \"\"\"\n # Fetch CVE details from NVD\n cve_data = fetch_nvd_data(cve_id)\n\n assessment = {\n 'cve_id': cve_id,\n 'published': cve_data['published'],\n 'base_cvss': cve_data['cvss_v3']['base_score'],\n 'vector': cve_data['cvss_v3']['vector_string'],\n 'description': cve_data['description'],\n 'affected_systems': [],\n 'exploitability': check_exploitability(cve_id),\n 'recommendation': None\n }\n\n # Check which systems are actually affected\n for system in affected_systems:\n if is_system_vulnerable(system, cve_data):\n assessment['affected_systems'].append({\n 'name': system.name,\n 'version': system.version,\n 'exposure': assess_exposure(system)\n })\n\n # Determine recommendation\n assessment['recommendation'] = determine_action(assessment)\n\n return assessment\n```\n\n### Step 2: Severity Classification\n\n| CVSS Score | Severity | Response SLA |\n|------------|----------|--------------|\n| 9.0 - 10.0 | Critical | 24 hours |\n| 7.0 - 8.9 | High | 7 days |\n| 4.0 - 6.9 | Medium | 30 days |\n| 0.1 - 3.9 | Low | 90 days |\n| 0.0 | None | Informational |\n\n### Step 3: Context Analysis\n\n```markdown\n## CVE Context Checklist\n\n### Exposure Assessment\n- [ ] Is the vulnerable component internet-facing?\n- [ ] Is the vulnerable component in a DMZ?\n- [ ] Does the component process sensitive data?\n- [ ] Are there compensating controls in place?\n\n### Exploitability Assessment\n- [ ] Is there a public exploit available?\n- [ ] Is exploitation being observed in the wild?\n- [ ] What privileges are required to exploit?\n- [ ] Does exploit require user interaction?\n\n### Business Impact\n- [ ] What business processes depend on affected systems?\n- [ ] What is the potential data exposure?\n- [ ] What are regulatory implications?\n- [ ] What is the reputational risk?\n```\n\n### Step 4: Triage Decision Matrix\n\n| Exposure | Exploitability | Business Impact | Priority |\n|----------|----------------|-----------------|----------|\n| Internet | Active Exploit | High | P0 - Immediate |\n| Internet | PoC Available | High | P1 - Critical |\n| Internet | Theoretical | Medium | P2 - High |\n| Internal | Active Exploit | High | P1 - Critical |\n| Internal | PoC Available | Medium | P2 - High |\n| Internal | Theoretical | Low | P3 - Medium |\n| Isolated | Any | Low | P4 - Low |\n\n---\n\n## CVSS Scoring\n\n### CVSS v3.1 Vector Components\n\n```\nCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ └── Availability Impact (H/L/N)\n │ │ │ │ │ │ └────── Integrity Impact (H/L/N)\n │ │ │ │ │ └────────── Confidentiality Impact (H/L/N)\n │ │ │ │ └────────────── Scope (C/U)\n │ │ │ └─────────────────── User Interaction (R/N)\n │ │ └──────────────────────── Privileges Required (H/L/N)\n │ └───────────────────────────── Attack Complexity (H/L)\n └─────────────────────────────────── Attack Vector (N/A/L/P)\n```\n\n### Environmental Score Adjustments\n\n```python\ndef calculate_environmental_score(base_cvss: float, environment: dict) -> float:\n \"\"\"\n Adjust CVSS base score based on environmental factors.\n\n Args:\n base_cvss: Base CVSS score from NVD\n environment: Dictionary with environmental modifiers\n\n Returns:\n Adjusted CVSS score for this environment\n \"\"\"\n # Confidentiality Requirement (CR)\n cr_modifier = {\n 'high': 1.5,\n 'medium': 1.0,\n 'low': 0.5\n }.get(environment.get('confidentiality_requirement', 'medium'))\n\n # Integrity Requirement (IR)\n ir_modifier = {\n 'high': 1.5,\n 'medium': 1.0,\n 'low': 0.5\n }.get(environment.get('integrity_requirement', 'medium'))\n\n # Availability Requirement (AR)\n ar_modifier = {\n 'high': 1.5,\n 'medium': 1.0,\n 'low': 0.5\n }.get(environment.get('availability_requirement', 'medium'))\n\n # Modified Attack Vector (reduce if not internet-facing)\n if not environment.get('internet_facing', True):\n base_cvss = max(0, base_cvss - 1.5)\n\n # Compensating controls reduce score\n if environment.get('waf_protected', False):\n base_cvss = max(0, base_cvss - 0.5)\n\n if environment.get('network_segmented', False):\n base_cvss = max(0, base_cvss - 0.5)\n\n return round(min(10.0, base_cvss), 1)\n```\n\n---\n\n## Remediation Workflows\n\n### Workflow 1: Emergency Patch (P0/Critical)\n\n```\nTimeline: 24 hours\nStakeholders: Security, DevOps, Engineering Lead, CISO\n\nHour 0-2: ASSESS\n├── Confirm vulnerability affects production\n├── Identify all affected systems\n├── Assess active exploitation\n└── Notify stakeholders\n\nHour 2-8: MITIGATE\n├── Apply temporary mitigations (WAF rules, network blocks)\n├── Enable enhanced monitoring\n├── Prepare rollback plan\n└── Begin patch development/testing\n\nHour 8-20: REMEDIATE\n├── Test patch in staging\n├── Security team validates fix\n├── Change approval (emergency CAB)\n└── Deploy to production (rolling)\n\nHour 20-24: VERIFY\n├── Confirm vulnerability resolved\n├── Monitor for issues\n├── Update vulnerability tracker\n└── Post-incident review scheduled\n```\n\n### Workflow 2: Standard Patch (P1-P2)\n\n```python\n# Remediation ticket template\nREMEDIATION_TICKET = \"\"\"\n## Vulnerability Remediation\n\n**CVE:** {cve_id}\n**Severity:** {severity}\n**CVSS:** {cvss_score}\n**SLA:** {sla_date}\n\n### Affected Components\n{affected_components}\n\n### Root Cause\n{root_cause}\n\n### Remediation Steps\n1. Update {package} from {current_version} to {fixed_version}\n2. Run security regression tests\n3. Deploy to staging for validation\n4. Security team approval required before production\n\n### Testing Requirements\n- [ ] Unit tests pass\n- [ ] Integration tests pass\n- [ ] Security scan shows vulnerability resolved\n- [ ] No new vulnerabilities introduced\n\n### Rollback Plan\n{rollback_steps}\n\n### Acceptance Criteria\n- Vulnerability scan shows CVE resolved\n- No functional regression\n- Performance baseline maintained\n\"\"\"\n```\n\n### Workflow 3: Risk Acceptance\n\n```markdown\n## Risk Acceptance Request\n\n**Vulnerability:** CVE-XXXX-XXXXX\n**Affected System:** [System Name]\n**Requested By:** [Name]\n**Date:** [Date]\n\n### Business Justification\n[Explain why the vulnerability cannot be remediated]\n\n### Compensating Controls\n- [ ] Control 1: [Description]\n- [ ] Control 2: [Description]\n- [ ] Control 3: [Description]\n\n### Residual Risk Assessment\n- **Likelihood:** [High/Medium/Low]\n- **Impact:** [High/Medium/Low]\n- **Residual Risk:** [Critical/High/Medium/Low]\n\n### Review Schedule\n- Next review date: [Date]\n- Review frequency: [Monthly/Quarterly]\n\n### Approvals\n- [ ] Security Team Lead\n- [ ] Engineering Manager\n- [ ] CISO\n- [ ] Business Owner\n```\n\n---\n\n## Dependency Scanning\n\n### Automated Scanning Pipeline\n\n```yaml\n# .github/workflows/security-scan.yml\nname: Security Scan\n\non:\n push:\n branches: [main, develop]\n pull_request:\n branches: [main]\n schedule:\n - cron: '0 6 * * *' # Daily at 6 AM\n\njobs:\n dependency-scan:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: Run Snyk vulnerability scan\n uses: snyk/actions/node@master\n env:\n SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}\n with:\n args: --severity-threshold=high\n\n - name: Run npm audit\n run: npm audit --audit-level=high\n\n - name: Run Trivy filesystem scan\n uses: aquasecurity/trivy-action@master\n with:\n scan-type: 'fs'\n scan-ref: '.'\n severity: 'CRITICAL,HIGH'\n exit-code: '1'\n\n sast-scan:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: Run Semgrep\n uses: returntocorp/semgrep-action@v1\n with:\n config: >-\n p/security-audit\n p/secrets\n p/owasp-top-ten\n```\n\n### Manual Dependency Review\n\n```bash\n# Node.js - Check for vulnerabilities\nnpm audit\nnpm audit --json > audit-report.json\n\n# Python - Check for vulnerabilities\npip-audit\nsafety check -r requirements.txt\n\n# Go - Check for vulnerabilities\ngovulncheck ./...\n\n# Container images\ntrivy image myapp:latest\ngrype myapp:latest\n```\n\n### Dependency Update Strategy\n\n| Update Type | Automation | Review Required |\n|-------------|------------|-----------------|\n| Security patch (same minor) | Auto-merge | No |\n| Minor version | Auto-PR | Yes |\n| Major version | Manual PR | Yes + Testing |\n| Breaking change | Manual | Yes + Migration plan |\n\n---\n\n## Security Incident Response\n\n### Incident Severity Levels\n\n| Level | Description | Response Time | Escalation |\n|-------|-------------|---------------|------------|\n| SEV-1 | Active breach, data exfiltration | Immediate | CISO, Legal, Exec |\n| SEV-2 | Confirmed intrusion, no data loss | 1 hour | Security Lead, Engineering |\n| SEV-3 | Suspicious activity, potential breach | 4 hours | Security Team |\n| SEV-4 | Policy violation, no immediate risk | 24 hours | Security Team |\n\n### Incident Response Checklist\n\n```markdown\n## Incident Response Checklist\n\n### 1. DETECT & IDENTIFY (0-15 min)\n- [ ] Alert received and acknowledged\n- [ ] Initial severity assessment\n- [ ] Incident commander assigned\n- [ ] Communication channel established\n\n### 2. CONTAIN (15-60 min)\n- [ ] Affected systems identified\n- [ ] Network isolation if needed\n- [ ] Credentials rotated if compromised\n- [ ] Preserve evidence (logs, memory dumps)\n\n### 3. ERADICATE (1-4 hours)\n- [ ] Root cause identified\n- [ ] Malware/backdoors removed\n- [ ] Vulnerabilities patched\n- [ ] Systems hardened\n\n### 4. RECOVER (4-24 hours)\n- [ ] Systems restored from clean backup\n- [ ] Services brought back online\n- [ ] Enhanced monitoring enabled\n- [ ] User access restored\n\n### 5. POST-INCIDENT (24-72 hours)\n- [ ] Incident timeline documented\n- [ ] Root cause analysis complete\n- [ ] Lessons learned documented\n- [ ] Preventive measures implemented\n- [ ] Report to stakeholders\n```\n\n---\n\n## Quick Reference\n\n### Vulnerability Response SLAs\n\n| Severity | Detection to Triage | Triage to Remediation |\n|----------|--------------------|-----------------------|\n| Critical | 4 hours | 24 hours |\n| High | 24 hours | 7 days |\n| Medium | 3 days | 30 days |\n| Low | 7 days | 90 days |\n\n### Common Vulnerability Databases\n\n| Database | URL | Use Case |\n|----------|-----|----------|\n| NVD | nvd.nist.gov | CVE details, CVSS |\n| MITRE CVE | cve.mitre.org | CVE registry |\n| OSV | osv.dev | Open source vulns |\n| GitHub Advisory | github.com/advisories | Package vulns |\n| Snyk DB | snyk.io/vuln | Package vulns |\n\n### Remediation Priority Formula\n\n```\nPriority Score = (CVSS × Exposure × Business_Impact) / Compensating_Controls\n\nWhere:\n- CVSS: 0-10 (from NVD)\n- Exposure: 1.0 (internal) to 2.0 (internet-facing)\n- Business_Impact: 1.0 (low) to 2.0 (critical)\n- Compensating_Controls: 1.0 (none) to 0.5 (multiple controls)\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":14297,"content_sha256":"095f7a2a705f82ed5d912897a3a285856fffab173c68085c2a9ccc2faa9901dd"},{"filename":"scripts/compliance_checker.py","content":"#!/usr/bin/env python3\n\"\"\"\nCompliance Checker - Verify security compliance against SOC 2, PCI-DSS, HIPAA, GDPR.\n\nTable of Contents:\n ComplianceChecker - Main class for compliance verification\n __init__ - Initialize with target path and framework\n check() - Run compliance checks for selected framework\n check_soc2() - Check SOC 2 Type II controls\n check_pci_dss() - Check PCI-DSS v4.0 requirements\n check_hipaa() - Check HIPAA security rule requirements\n check_gdpr() - Check GDPR data protection requirements\n _check_encryption_at_rest() - Verify data encryption\n _check_access_controls() - Verify access control implementation\n _check_logging() - Verify audit logging\n _check_secrets_management() - Verify secrets handling\n _calculate_compliance_score() - Calculate overall compliance score\n main() - CLI entry point\n\nUsage:\n python compliance_checker.py /path/to/project\n python compliance_checker.py /path/to/project --framework soc2\n python compliance_checker.py /path/to/project --framework pci-dss --output report.json\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\n\n\n@dataclass\nclass ComplianceControl:\n \"\"\"Represents a compliance control check result.\"\"\"\n control_id: str\n framework: str\n category: str\n title: str\n description: str\n status: str # passed, failed, warning, not_applicable\n evidence: List[str]\n recommendation: str\n severity: str # critical, high, medium, low\n\n\nclass ComplianceChecker:\n \"\"\"Verify security compliance against industry frameworks.\"\"\"\n\n FRAMEWORKS = ['soc2', 'pci-dss', 'hipaa', 'gdpr', 'all']\n\n def __init__(\n self,\n target_path: str,\n framework: str = \"all\",\n verbose: bool = False\n ):\n \"\"\"\n Initialize the compliance checker.\n\n Args:\n target_path: Directory to scan\n framework: Compliance framework to check (soc2, pci-dss, hipaa, gdpr, all)\n verbose: Enable verbose output\n \"\"\"\n self.target_path = Path(target_path)\n self.framework = framework.lower()\n self.verbose = verbose\n self.controls: List[ComplianceControl] = []\n self.files_scanned = 0\n\n def check(self) -> Dict:\n \"\"\"\n Run compliance checks for selected framework.\n\n Returns:\n Dict with compliance results\n \"\"\"\n print(f\"Compliance Checker - Scanning: {self.target_path}\")\n print(f\"Framework: {self.framework.upper()}\")\n print()\n\n if not self.target_path.exists():\n return {\"status\": \"error\", \"message\": f\"Path not found: {self.target_path}\"}\n\n start_time = datetime.now()\n\n # Run framework-specific checks\n if self.framework in ('soc2', 'all'):\n self.check_soc2()\n if self.framework in ('pci-dss', 'all'):\n self.check_pci_dss()\n if self.framework in ('hipaa', 'all'):\n self.check_hipaa()\n if self.framework in ('gdpr', 'all'):\n self.check_gdpr()\n\n end_time = datetime.now()\n scan_duration = (end_time - start_time).total_seconds()\n\n # Calculate statistics\n passed = len([c for c in self.controls if c.status == 'passed'])\n failed = len([c for c in self.controls if c.status == 'failed'])\n warnings = len([c for c in self.controls if c.status == 'warning'])\n na = len([c for c in self.controls if c.status == 'not_applicable'])\n\n compliance_score = self._calculate_compliance_score()\n\n result = {\n \"status\": \"completed\",\n \"target\": str(self.target_path),\n \"framework\": self.framework,\n \"scan_duration_seconds\": round(scan_duration, 2),\n \"compliance_score\": compliance_score,\n \"compliance_level\": self._get_compliance_level(compliance_score),\n \"summary\": {\n \"passed\": passed,\n \"failed\": failed,\n \"warnings\": warnings,\n \"not_applicable\": na,\n \"total\": len(self.controls)\n },\n \"controls\": [asdict(c) for c in self.controls]\n }\n\n self._print_summary(result)\n\n return result\n\n def check_soc2(self):\n \"\"\"Check SOC 2 Type II controls.\"\"\"\n if self.verbose:\n print(\" Checking SOC 2 Type II controls...\")\n\n # CC1: Control Environment - Access Controls\n self._check_access_controls_soc2()\n\n # CC2: Communication and Information\n self._check_documentation()\n\n # CC3: Risk Assessment\n self._check_risk_assessment()\n\n # CC6: Logical and Physical Access Controls\n self._check_authentication()\n\n # CC7: System Operations\n self._check_logging()\n\n # CC8: Change Management\n self._check_change_management()\n\n def check_pci_dss(self):\n \"\"\"Check PCI-DSS v4.0 requirements.\"\"\"\n if self.verbose:\n print(\" Checking PCI-DSS v4.0 requirements...\")\n\n # Requirement 3: Protect stored cardholder data\n self._check_data_encryption()\n\n # Requirement 4: Encrypt transmission of cardholder data\n self._check_transmission_encryption()\n\n # Requirement 6: Develop and maintain secure systems\n self._check_secure_development()\n\n # Requirement 8: Identify users and authenticate access\n self._check_strong_authentication()\n\n # Requirement 10: Log and monitor all access\n self._check_audit_logging()\n\n # Requirement 11: Test security of systems regularly\n self._check_security_testing()\n\n def check_hipaa(self):\n \"\"\"Check HIPAA security rule requirements.\"\"\"\n if self.verbose:\n print(\" Checking HIPAA Security Rule requirements...\")\n\n # 164.312(a)(1): Access Control\n self._check_hipaa_access_control()\n\n # 164.312(b): Audit Controls\n self._check_hipaa_audit()\n\n # 164.312(c)(1): Integrity Controls\n self._check_hipaa_integrity()\n\n # 164.312(d): Person or Entity Authentication\n self._check_hipaa_authentication()\n\n # 164.312(e)(1): Transmission Security\n self._check_hipaa_transmission()\n\n def check_gdpr(self):\n \"\"\"Check GDPR data protection requirements.\"\"\"\n if self.verbose:\n print(\" Checking GDPR requirements...\")\n\n # Article 25: Data protection by design\n self._check_privacy_by_design()\n\n # Article 32: Security of processing\n self._check_gdpr_security()\n\n # Article 33/34: Breach notification\n self._check_breach_notification()\n\n # Article 17: Right to erasure\n self._check_data_deletion()\n\n # Article 20: Data portability\n self._check_data_export()\n\n def _check_access_controls_soc2(self):\n \"\"\"SOC 2 CC1/CC6: Check access control implementation.\"\"\"\n evidence = []\n status = 'failed'\n\n # Look for authentication middleware\n auth_patterns = [\n r'authMiddleware',\n r'requireAuth',\n r'isAuthenticated',\n r'@login_required',\n r'@authenticated',\n r'passport\\.authenticate',\n r'jwt\\.verify',\n r'verifyToken'\n ]\n\n for pattern in auth_patterns:\n files = self._search_files(pattern)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n # Check for RBAC implementation\n rbac_patterns = [r'role', r'permission', r'authorize', r'can\\(', r'hasRole']\n for pattern in rbac_patterns:\n files = self._search_files(pattern)\n if files:\n evidence.extend(files[:2])\n if status == 'failed':\n status = 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC6.1',\n framework='SOC 2',\n category='Logical Access Controls',\n title='Access Control Implementation',\n description='Verify authentication and authorization controls are implemented',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement authentication middleware and role-based access control (RBAC)',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_documentation(self):\n \"\"\"SOC 2 CC2: Check security documentation.\"\"\"\n evidence = []\n status = 'failed'\n\n doc_files = [\n 'SECURITY.md',\n 'docs/security.md',\n 'CONTRIBUTING.md',\n 'docs/security-policy.md',\n '.github/SECURITY.md'\n ]\n\n for doc in doc_files:\n doc_path = self.target_path / doc\n if doc_path.exists():\n evidence.append(str(doc))\n status = 'passed' if 'security' in doc.lower() else 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC2.1',\n framework='SOC 2',\n category='Communication and Information',\n title='Security Documentation',\n description='Verify security policies and procedures are documented',\n status=status,\n evidence=evidence,\n recommendation='Create SECURITY.md documenting security policies, incident response, and vulnerability reporting',\n severity='medium' if status == 'failed' else 'low'\n ))\n\n def _check_risk_assessment(self):\n \"\"\"SOC 2 CC3: Check risk assessment artifacts.\"\"\"\n evidence = []\n status = 'failed'\n\n # Look for security scanning configuration\n scan_configs = [\n '.snyk',\n '.github/workflows/security.yml',\n '.github/workflows/codeql.yml',\n 'trivy.yaml',\n '.semgrep.yml',\n 'sonar-project.properties'\n ]\n\n for config in scan_configs:\n config_path = self.target_path / config\n if config_path.exists():\n evidence.append(str(config))\n status = 'passed'\n break\n\n # Check for dependabot/renovate\n dep_configs = [\n '.github/dependabot.yml',\n 'renovate.json',\n '.github/renovate.json'\n ]\n\n for config in dep_configs:\n config_path = self.target_path / config\n if config_path.exists():\n evidence.append(str(config))\n if status == 'failed':\n status = 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC3.1',\n framework='SOC 2',\n category='Risk Assessment',\n title='Automated Security Scanning',\n description='Verify automated vulnerability scanning is configured',\n status=status,\n evidence=evidence,\n recommendation='Configure automated security scanning (Snyk, CodeQL, Trivy) and dependency updates (Dependabot)',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_authentication(self):\n \"\"\"SOC 2 CC6: Check authentication strength.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for MFA/2FA\n mfa_patterns = [r'mfa', r'2fa', r'totp', r'authenticator', r'twoFactor']\n for pattern in mfa_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:2])\n status = 'passed'\n break\n\n # Check for password hashing\n hash_patterns = [r'bcrypt', r'argon2', r'scrypt', r'pbkdf2']\n for pattern in hash_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:2])\n if status == 'failed':\n status = 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC6.2',\n framework='SOC 2',\n category='Authentication',\n title='Strong Authentication',\n description='Verify multi-factor authentication and secure password storage',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement MFA/2FA and use bcrypt/argon2 for password hashing',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_logging(self):\n \"\"\"SOC 2 CC7: Check audit logging implementation.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for logging configuration\n log_patterns = [\n r'winston',\n r'pino',\n r'bunyan',\n r'logging\\.getLogger',\n r'log\\.info',\n r'logger\\.',\n r'audit.*log'\n ]\n\n for pattern in log_patterns:\n files = self._search_files(pattern)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n # Check for structured logging\n struct_patterns = [r'json.*log', r'structured.*log', r'log.*format']\n for pattern in struct_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:2])\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC7.1',\n framework='SOC 2',\n category='System Operations',\n title='Audit Logging',\n description='Verify comprehensive audit logging is implemented',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement structured audit logging with security events (auth, access, changes)',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_change_management(self):\n \"\"\"SOC 2 CC8: Check change management controls.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for CI/CD configuration\n ci_configs = [\n '.github/workflows',\n '.gitlab-ci.yml',\n 'Jenkinsfile',\n '.circleci/config.yml',\n 'azure-pipelines.yml'\n ]\n\n for config in ci_configs:\n config_path = self.target_path / config\n if config_path.exists():\n evidence.append(str(config))\n status = 'passed'\n break\n\n # Check for branch protection indicators\n branch_patterns = [r'protected.*branch', r'require.*review', r'pull.*request']\n for pattern in branch_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:2])\n break\n\n self.controls.append(ComplianceControl(\n control_id='SOC2-CC8.1',\n framework='SOC 2',\n category='Change Management',\n title='CI/CD and Code Review',\n description='Verify automated deployment pipeline and code review process',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement CI/CD pipeline with required code reviews and branch protection',\n severity='medium' if status == 'failed' else 'low'\n ))\n\n def _check_data_encryption(self):\n \"\"\"PCI-DSS Req 3: Check encryption at rest.\"\"\"\n evidence = []\n status = 'failed'\n\n encryption_patterns = [\n r'AES',\n r'encrypt',\n r'crypto\\.createCipher',\n r'Fernet',\n r'KMS',\n r'encryptedField'\n ]\n\n for pattern in encryption_patterns:\n files = self._search_files(pattern)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-3.5',\n framework='PCI-DSS',\n category='Protect Stored Data',\n title='Encryption at Rest',\n description='Verify sensitive data is encrypted at rest',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement AES-256 encryption for sensitive data storage using approved libraries',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_transmission_encryption(self):\n \"\"\"PCI-DSS Req 4: Check encryption in transit.\"\"\"\n evidence = []\n status = 'failed'\n\n tls_patterns = [\n r'https://',\n r'TLS',\n r'SSL',\n r'secure.*cookie',\n r'HSTS'\n ]\n\n for pattern in tls_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-4.1',\n framework='PCI-DSS',\n category='Encrypt Transmissions',\n title='TLS/HTTPS Enforcement',\n description='Verify TLS 1.2+ is enforced for all transmissions',\n status=status,\n evidence=evidence[:5],\n recommendation='Enforce HTTPS with TLS 1.2+, enable HSTS, use secure cookies',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_secure_development(self):\n \"\"\"PCI-DSS Req 6: Check secure development practices.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for input validation\n validation_patterns = [\n r'validator',\n r'sanitize',\n r'escape',\n r'zod',\n r'yup',\n r'joi'\n ]\n\n for pattern in validation_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-6.5',\n framework='PCI-DSS',\n category='Secure Development',\n title='Input Validation',\n description='Verify input validation and sanitization is implemented',\n status=status,\n evidence=evidence[:5],\n recommendation='Use validation libraries (Joi, Zod, validator.js) for all user input',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_strong_authentication(self):\n \"\"\"PCI-DSS Req 8: Check authentication requirements.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for session management\n session_patterns = [\n r'session.*timeout',\n r'maxAge',\n r'expiresIn',\n r'session.*expire'\n ]\n\n for pattern in session_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-8.6',\n framework='PCI-DSS',\n category='Authentication',\n title='Session Management',\n description='Verify session timeout and management controls',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement 15-minute session timeout, secure session tokens, and session invalidation on logout',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_audit_logging(self):\n \"\"\"PCI-DSS Req 10: Check audit logging.\"\"\"\n # Reuse SOC 2 logging check logic\n evidence = []\n status = 'failed'\n\n log_patterns = [r'audit', r'log.*event', r'security.*log']\n for pattern in log_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-10.2',\n framework='PCI-DSS',\n category='Logging and Monitoring',\n title='Security Event Logging',\n description='Verify security events are logged with sufficient detail',\n status=status,\n evidence=evidence[:5],\n recommendation='Log all authentication events, access to cardholder data, and administrative actions',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_security_testing(self):\n \"\"\"PCI-DSS Req 11: Check security testing.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for test configuration\n test_patterns = [\n r'security.*test',\n r'penetration.*test',\n r'vulnerability.*scan'\n ]\n\n for pattern in test_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n # Check for SAST/DAST configuration\n sast_configs = ['.snyk', '.semgrep.yml', 'sonar-project.properties']\n for config in sast_configs:\n if (self.target_path / config).exists():\n evidence.append(config)\n if status == 'failed':\n status = 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='PCI-DSS-11.3',\n framework='PCI-DSS',\n category='Security Testing',\n title='Vulnerability Assessment',\n description='Verify regular security testing is performed',\n status=status,\n evidence=evidence[:5],\n recommendation='Configure SAST/DAST scanning and schedule quarterly penetration tests',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_hipaa_access_control(self):\n \"\"\"HIPAA 164.312(a)(1): Access Control.\"\"\"\n evidence = []\n status = 'failed'\n\n # Check for user identification\n auth_patterns = [r'user.*id', r'authentication', r'identity']\n for pattern in auth_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='HIPAA-164.312(a)(1)',\n framework='HIPAA',\n category='Access Control',\n title='Unique User Identification',\n description='Verify unique user identification for accessing PHI',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement unique user accounts with individual credentials for all PHI access',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_hipaa_audit(self):\n \"\"\"HIPAA 164.312(b): Audit Controls.\"\"\"\n evidence = []\n status = 'failed'\n\n audit_patterns = [r'audit.*trail', r'access.*log', r'phi.*log']\n for pattern in audit_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='HIPAA-164.312(b)',\n framework='HIPAA',\n category='Audit Controls',\n title='PHI Access Audit Trail',\n description='Verify audit trails for PHI access are maintained',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement comprehensive audit logging for all PHI access with who/what/when/where',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_hipaa_integrity(self):\n \"\"\"HIPAA 164.312(c)(1): Integrity Controls.\"\"\"\n evidence = []\n status = 'failed'\n\n integrity_patterns = [r'checksum', r'hash', r'signature', r'integrity']\n for pattern in integrity_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='HIPAA-164.312(c)(1)',\n framework='HIPAA',\n category='Integrity',\n title='Data Integrity Controls',\n description='Verify mechanisms to protect PHI from improper alteration',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement checksums, digital signatures, or hashing for PHI integrity verification',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_hipaa_authentication(self):\n \"\"\"HIPAA 164.312(d): Authentication.\"\"\"\n evidence = []\n status = 'failed'\n\n auth_patterns = [r'mfa', r'two.*factor', r'biometric', r'token.*auth']\n for pattern in auth_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='HIPAA-164.312(d)',\n framework='HIPAA',\n category='Authentication',\n title='Person Authentication',\n description='Verify mechanisms to authenticate person or entity accessing PHI',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement multi-factor authentication for all PHI access',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_hipaa_transmission(self):\n \"\"\"HIPAA 164.312(e)(1): Transmission Security.\"\"\"\n evidence = []\n status = 'failed'\n\n transmission_patterns = [r'tls', r'ssl', r'https', r'encrypt.*transit']\n for pattern in transmission_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='HIPAA-164.312(e)(1)',\n framework='HIPAA',\n category='Transmission Security',\n title='PHI Transmission Encryption',\n description='Verify PHI is encrypted during transmission',\n status=status,\n evidence=evidence[:5],\n recommendation='Enforce TLS 1.2+ for all PHI transmissions, implement end-to-end encryption',\n severity='critical' if status == 'failed' else 'low'\n ))\n\n def _check_privacy_by_design(self):\n \"\"\"GDPR Article 25: Privacy by design.\"\"\"\n evidence = []\n status = 'failed'\n\n privacy_patterns = [\n r'data.*minimization',\n r'privacy.*config',\n r'consent',\n r'gdpr'\n ]\n\n for pattern in privacy_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='GDPR-25',\n framework='GDPR',\n category='Privacy by Design',\n title='Data Minimization',\n description='Verify data collection is limited to necessary purposes',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement data minimization, purpose limitation, and privacy-by-default configurations',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_gdpr_security(self):\n \"\"\"GDPR Article 32: Security of processing.\"\"\"\n evidence = []\n status = 'failed'\n\n security_patterns = [r'encrypt', r'pseudonymization', r'anonymization']\n for pattern in security_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='GDPR-32',\n framework='GDPR',\n category='Security',\n title='Pseudonymization and Encryption',\n description='Verify appropriate security measures for personal data',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement encryption and pseudonymization for personal data processing',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_breach_notification(self):\n \"\"\"GDPR Article 33/34: Breach notification.\"\"\"\n evidence = []\n status = 'failed'\n\n breach_patterns = [\n r'breach.*notification',\n r'incident.*response',\n r'security.*incident'\n ]\n\n for pattern in breach_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n # Check for incident response documentation\n incident_docs = ['SECURITY.md', 'docs/incident-response.md', '.github/SECURITY.md']\n for doc in incident_docs:\n if (self.target_path / doc).exists():\n evidence.append(doc)\n if status == 'failed':\n status = 'warning'\n break\n\n self.controls.append(ComplianceControl(\n control_id='GDPR-33',\n framework='GDPR',\n category='Breach Notification',\n title='Incident Response Procedure',\n description='Verify breach notification procedures are documented',\n status=status,\n evidence=evidence[:5],\n recommendation='Document incident response procedures with 72-hour notification capability',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_data_deletion(self):\n \"\"\"GDPR Article 17: Right to erasure.\"\"\"\n evidence = []\n status = 'failed'\n\n deletion_patterns = [\n r'delete.*user',\n r'erasure',\n r'right.*forgotten',\n r'data.*deletion',\n r'gdpr.*delete'\n ]\n\n for pattern in deletion_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='GDPR-17',\n framework='GDPR',\n category='Data Subject Rights',\n title='Right to Erasure',\n description='Verify data deletion capability is implemented',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement complete user data deletion including all backups and third-party systems',\n severity='high' if status == 'failed' else 'low'\n ))\n\n def _check_data_export(self):\n \"\"\"GDPR Article 20: Data portability.\"\"\"\n evidence = []\n status = 'failed'\n\n export_patterns = [\n r'export.*data',\n r'data.*portability',\n r'download.*data',\n r'gdpr.*export'\n ]\n\n for pattern in export_patterns:\n files = self._search_files(pattern, case_sensitive=False)\n if files:\n evidence.extend(files[:3])\n status = 'passed'\n break\n\n self.controls.append(ComplianceControl(\n control_id='GDPR-20',\n framework='GDPR',\n category='Data Subject Rights',\n title='Data Portability',\n description='Verify data export capability is implemented',\n status=status,\n evidence=evidence[:5],\n recommendation='Implement data export in machine-readable format (JSON, CSV)',\n severity='medium' if status == 'failed' else 'low'\n ))\n\n def _search_files(self, pattern: str, case_sensitive: bool = True) -> List[str]:\n \"\"\"Search files for pattern matches.\"\"\"\n matches = []\n flags = 0 if case_sensitive else re.IGNORECASE\n\n try:\n for root, dirs, files in os.walk(self.target_path):\n # Skip common non-relevant directories\n dirs[:] = [d for d in dirs if d not in {\n 'node_modules', '.git', '__pycache__', 'venv', '.venv',\n 'dist', 'build', 'coverage', '.next'\n }]\n\n for filename in files:\n if filename.endswith(('.js', '.ts', '.py', '.go', '.java', '.md', '.yml', '.yaml', '.json')):\n file_path = Path(root) / filename\n try:\n content = file_path.read_text(encoding='utf-8', errors='ignore')\n if re.search(pattern, content, flags):\n rel_path = str(file_path.relative_to(self.target_path))\n matches.append(rel_path)\n self.files_scanned += 1\n except Exception:\n pass\n except Exception:\n pass\n\n return matches[:10] # Limit results\n\n def _calculate_compliance_score(self) -> float:\n \"\"\"Calculate overall compliance score (0-100).\"\"\"\n if not self.controls:\n return 0.0\n\n # Weight by severity\n severity_weights = {'critical': 4.0, 'high': 3.0, 'medium': 2.0, 'low': 1.0}\n status_scores = {'passed': 1.0, 'warning': 0.5, 'failed': 0.0, 'not_applicable': None}\n\n total_weight = 0.0\n total_score = 0.0\n\n for control in self.controls:\n score = status_scores.get(control.status)\n if score is not None: # Skip N/A\n weight = severity_weights.get(control.severity, 1.0)\n total_weight += weight\n total_score += score * weight\n\n return round((total_score / total_weight) * 100, 1) if total_weight > 0 else 0.0\n\n def _get_compliance_level(self, score: float) -> str:\n \"\"\"Get compliance level from score.\"\"\"\n if score >= 90:\n return \"COMPLIANT\"\n elif score >= 70:\n return \"PARTIALLY_COMPLIANT\"\n elif score >= 50:\n return \"NON_COMPLIANT\"\n return \"CRITICAL_GAPS\"\n\n def _print_summary(self, result: Dict):\n \"\"\"Print compliance summary.\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(\"COMPLIANCE CHECK SUMMARY\")\n print(\"=\" * 60)\n print(f\"Target: {result['target']}\")\n print(f\"Framework: {result['framework'].upper()}\")\n print(f\"Scan duration: {result['scan_duration_seconds']}s\")\n print(f\"Compliance score: {result['compliance_score']}% ({result['compliance_level']})\")\n print()\n\n summary = result['summary']\n print(f\"Controls checked: {summary['total']}\")\n print(f\" Passed: {summary['passed']}\")\n print(f\" Failed: {summary['failed']}\")\n print(f\" Warning: {summary['warnings']}\")\n print(f\" N/A: {summary['not_applicable']}\")\n print(\"=\" * 60)\n\n # Show failed controls\n failed = [c for c in result['controls'] if c['status'] == 'failed']\n if failed:\n print(\"\\nFailed controls requiring remediation:\")\n for control in failed[:5]:\n print(f\"\\n [{control['severity'].upper()}] {control['control_id']}\")\n print(f\" {control['title']}\")\n print(f\" Recommendation: {control['recommendation']}\")\n\n\ndef main():\n \"\"\"Main entry point for CLI.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Check compliance against SOC 2, PCI-DSS, HIPAA, GDPR\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s /path/to/project\n %(prog)s /path/to/project --framework soc2\n %(prog)s /path/to/project --framework pci-dss --output report.json\n %(prog)s . --framework all --verbose\n \"\"\"\n )\n\n parser.add_argument(\n \"target\",\n help=\"Directory to check for compliance\"\n )\n parser.add_argument(\n \"--framework\", \"-f\",\n choices=[\"soc2\", \"pci-dss\", \"hipaa\", \"gdpr\", \"all\"],\n default=\"all\",\n help=\"Compliance framework to check (default: all)\"\n )\n parser.add_argument(\n \"--verbose\", \"-v\",\n action=\"store_true\",\n help=\"Enable verbose output\"\n )\n parser.add_argument(\n \"--json\",\n action=\"store_true\",\n help=\"Output results as JSON\"\n )\n parser.add_argument(\n \"--output\", \"-o\",\n help=\"Output file path\"\n )\n\n args = parser.parse_args()\n\n checker = ComplianceChecker(\n target_path=args.target,\n framework=args.framework,\n verbose=args.verbose\n )\n\n result = checker.check()\n\n if args.json:\n output = json.dumps(result, indent=2)\n if args.output:\n with open(args.output, 'w') as f:\n f.write(output)\n print(f\"\\nResults written to {args.output}\")\n else:\n print(output)\n elif args.output:\n with open(args.output, 'w') as f:\n json.dump(result, f, indent=2)\n print(f\"\\nResults written to {args.output}\")\n\n # Exit with error code based on compliance level\n if result.get('compliance_level') == 'CRITICAL_GAPS':\n sys.exit(2)\n if result.get('compliance_level') == 'NON_COMPLIANT':\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":38622,"content_sha256":"1992ca50b0b94677b085c8e453392d3066243f458d03819b8009282a54866abb"},{"filename":"scripts/security_scanner.py","content":"#!/usr/bin/env python3\n\"\"\"\nSecurity Scanner - Scan source code for security vulnerabilities.\n\nTable of Contents:\n SecurityScanner - Main class for security scanning\n __init__ - Initialize with target path and options\n scan() - Run all security scans\n scan_secrets() - Detect hardcoded secrets\n scan_sql_injection() - Detect SQL injection patterns\n scan_xss() - Detect XSS vulnerabilities\n scan_command_injection() - Detect command injection\n scan_path_traversal() - Detect path traversal\n _scan_file() - Scan individual file for patterns\n _calculate_severity() - Calculate finding severity\n main() - CLI entry point\n\nUsage:\n python security_scanner.py /path/to/project\n python security_scanner.py /path/to/project --severity high\n python security_scanner.py /path/to/project --output report.json --json\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\n\n\n@dataclass\nclass SecurityFinding:\n \"\"\"Represents a security finding.\"\"\"\n rule_id: str\n severity: str # critical, high, medium, low, info\n category: str\n title: str\n description: str\n file_path: str\n line_number: int\n code_snippet: str\n recommendation: str\n\n\nclass SecurityScanner:\n \"\"\"Scan source code for security vulnerabilities.\"\"\"\n\n # File extensions to scan\n SCAN_EXTENSIONS = {\n '.py', '.js', '.ts', '.jsx', '.tsx', '.java', '.go',\n '.rb', '.php', '.cs', '.rs', '.swift', '.kt',\n '.yml', '.yaml', '.json', '.xml', '.env', '.conf', '.config'\n }\n\n # Directories to skip\n SKIP_DIRS = {\n 'node_modules', '.git', '__pycache__', '.venv', 'venv',\n 'vendor', 'dist', 'build', '.next', 'coverage'\n }\n\n # Secret patterns\n SECRET_PATTERNS = [\n (r'(?i)(api[_-]?key|apikey)\\s*[:=]\\s*[\"\\']?([a-zA-Z0-9_\\-]{20,})[\"\\']?',\n 'API Key', 'Hardcoded API key detected'),\n (r'(?i)(secret[_-]?key|secretkey)\\s*[:=]\\s*[\"\\']?([a-zA-Z0-9_\\-]{16,})[\"\\']?',\n 'Secret Key', 'Hardcoded secret key detected'),\n (r'(?i)(password|passwd|pwd)\\s*[:=]\\s*[\"\\']([^\"\\']{4,})[\"\\']',\n 'Password', 'Hardcoded password detected'),\n (r'(?i)(aws[_-]?access[_-]?key[_-]?id)\\s*[:=]\\s*[\"\\']?(AKIA[A-Z0-9]{16})[\"\\']?',\n 'AWS Access Key', 'Hardcoded AWS access key detected'),\n (r'(?i)(aws[_-]?secret[_-]?access[_-]?key)\\s*[:=]\\s*[\"\\']?([a-zA-Z0-9/+=]{40})[\"\\']?',\n 'AWS Secret Key', 'Hardcoded AWS secret access key detected'),\n (r'ghp_[a-zA-Z0-9]{36}',\n 'GitHub Token', 'GitHub personal access token detected'),\n (r'sk-[a-zA-Z0-9]{48}',\n 'OpenAI API Key', 'OpenAI API key detected'),\n (r'-----BEGIN\\s+(RSA|DSA|EC|OPENSSH)?\\s*PRIVATE KEY-----',\n 'Private Key', 'Private key detected in source code'),\n ]\n\n # SQL injection patterns\n SQL_INJECTION_PATTERNS = [\n (r'execute\\s*\\(\\s*[\"\\']?\\s*SELECT.*\\+.*\\+',\n 'Dynamic SQL query with string concatenation'),\n (r'execute\\s*\\(\\s*f[\"\\']SELECT',\n 'F-string SQL query (Python)'),\n (r'cursor\\.execute\\s*\\(\\s*[\"\\'].*%s.*%\\s*\\(',\n 'Unsafe string formatting in SQL'),\n (r'query\\s*\\(\\s*[`\"\\']SELECT.*\\$\\{',\n 'Template literal SQL injection (JavaScript)'),\n (r'\\.query\\s*\\(\\s*[\"\\'].*\\+.*\\+',\n 'String concatenation in SQL query'),\n ]\n\n # XSS patterns\n XSS_PATTERNS = [\n (r'innerHTML\\s*=\\s*[^;]+(?:user|input|param|query)',\n 'User input assigned to innerHTML'),\n (r'document\\.write\\s*\\([^;]*(?:user|input|param|query)',\n 'User input in document.write'),\n (r'\\.html\\s*\\(\\s*[^)]*(?:user|input|param|query)',\n 'User input in jQuery .html()'),\n (r'dangerouslySetInnerHTML',\n 'React dangerouslySetInnerHTML usage'),\n (r'\\|safe\\s*}}',\n 'Django safe filter may disable escaping'),\n ]\n\n # Command injection patterns (detection rules for finding unsafe patterns)\n COMMAND_INJECTION_PATTERNS = [\n (r'subprocess\\.(?:call|run|Popen)\\s*\\([^)]*shell\\s*=\\s*True',\n 'Subprocess with shell=True'),\n (r'exec\\s*\\(\\s*[^)]*(?:user|input|param|request)',\n 'exec() with potential user input'), # noqa: SEC-AUDITOR (detection-rule label text; nothing runs)\n (r'eval\\s*\\(\\s*[^)]*(?:user|input|param|request)',\n 'eval() with potential user input'), # noqa: SEC-AUDITOR (detection-rule label text; nothing runs)\n ]\n\n # Path traversal patterns\n PATH_TRAVERSAL_PATTERNS = [\n (r'open\\s*\\(\\s*[^)]*(?:user|input|param|request)',\n 'File open with potential user input'),\n (r'readFile\\s*\\(\\s*[^)]*(?:user|input|param|req\\.|query)',\n 'File read with potential user input'),\n (r'path\\.join\\s*\\([^)]*(?:user|input|param|req\\.|query)',\n 'Path.join with user input without validation'),\n ]\n\n def __init__(\n self,\n target_path: str,\n severity_threshold: str = \"low\",\n verbose: bool = False\n ):\n \"\"\"\n Initialize the security scanner.\n\n Args:\n target_path: Directory or file to scan\n severity_threshold: Minimum severity to report (critical, high, medium, low)\n verbose: Enable verbose output\n \"\"\"\n self.target_path = Path(target_path)\n self.severity_threshold = severity_threshold\n self.verbose = verbose\n self.findings: List[SecurityFinding] = []\n self.files_scanned = 0\n self.severity_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3, 'info': 4}\n\n def scan(self) -> Dict:\n \"\"\"\n Run all security scans.\n\n Returns:\n Dict with scan results and findings\n \"\"\"\n print(f\"Security Scanner - Scanning: {self.target_path}\")\n print(f\"Severity threshold: {self.severity_threshold}\")\n print()\n\n if not self.target_path.exists():\n return {\"status\": \"error\", \"message\": f\"Path not found: {self.target_path}\"}\n\n start_time = datetime.now()\n\n # Collect files to scan\n files_to_scan = self._collect_files()\n print(f\"Files to scan: {len(files_to_scan)}\")\n\n # Run scans\n for file_path in files_to_scan:\n self._scan_file(file_path)\n self.files_scanned += 1\n\n # Filter by severity threshold\n threshold_level = self.severity_order.get(self.severity_threshold, 3)\n filtered_findings = [\n f for f in self.findings\n if self.severity_order.get(f.severity, 3) \u003c= threshold_level\n ]\n\n end_time = datetime.now()\n scan_duration = (end_time - start_time).total_seconds()\n\n # Group findings by severity\n severity_counts = {}\n for finding in filtered_findings:\n severity_counts[finding.severity] = severity_counts.get(finding.severity, 0) + 1\n\n result = {\n \"status\": \"completed\",\n \"target\": str(self.target_path),\n \"files_scanned\": self.files_scanned,\n \"scan_duration_seconds\": round(scan_duration, 2),\n \"total_findings\": len(filtered_findings),\n \"severity_counts\": severity_counts,\n \"findings\": [asdict(f) for f in filtered_findings]\n }\n\n self._print_summary(result)\n\n return result\n\n def _collect_files(self) -> List[Path]:\n \"\"\"Collect files to scan.\"\"\"\n files = []\n\n if self.target_path.is_file():\n return [self.target_path]\n\n for root, dirs, filenames in os.walk(self.target_path):\n # Skip directories\n dirs[:] = [d for d in dirs if d not in self.SKIP_DIRS]\n\n for filename in filenames:\n file_path = Path(root) / filename\n if file_path.suffix.lower() in self.SCAN_EXTENSIONS:\n files.append(file_path)\n\n return files\n\n def _scan_file(self, file_path: Path):\n \"\"\"Scan a single file for security issues.\"\"\"\n try:\n content = file_path.read_text(encoding='utf-8', errors='ignore')\n lines = content.split('\\n')\n\n relative_path = str(file_path.relative_to(self.target_path) if self.target_path.is_dir() else file_path.name)\n\n # Scan for secrets\n self._scan_patterns(\n lines, relative_path,\n self.SECRET_PATTERNS,\n 'secrets',\n 'Hardcoded Secret',\n 'critical'\n )\n\n # Scan for SQL injection\n self._scan_patterns(\n lines, relative_path,\n [(p[0], p[1]) for p in self.SQL_INJECTION_PATTERNS],\n 'injection',\n 'SQL Injection',\n 'high'\n )\n\n # Scan for XSS\n self._scan_patterns(\n lines, relative_path,\n [(p[0], p[1]) for p in self.XSS_PATTERNS],\n 'xss',\n 'Cross-Site Scripting (XSS)',\n 'high'\n )\n\n # Scan for command injection\n self._scan_patterns(\n lines, relative_path,\n [(p[0], p[1]) for p in self.COMMAND_INJECTION_PATTERNS],\n 'injection',\n 'Command Injection',\n 'critical'\n )\n\n # Scan for path traversal\n self._scan_patterns(\n lines, relative_path,\n [(p[0], p[1]) for p in self.PATH_TRAVERSAL_PATTERNS],\n 'path-traversal',\n 'Path Traversal',\n 'medium'\n )\n\n if self.verbose:\n print(f\" Scanned: {relative_path}\")\n\n except Exception as e:\n if self.verbose:\n print(f\" Error scanning {file_path}: {e}\")\n\n def _scan_patterns(\n self,\n lines: List[str],\n file_path: str,\n patterns: List[Tuple],\n category: str,\n title: str,\n default_severity: str\n ):\n \"\"\"Scan lines for patterns.\"\"\"\n for line_num, line in enumerate(lines, 1):\n for pattern_tuple in patterns:\n pattern = pattern_tuple[0]\n description = pattern_tuple[1] if len(pattern_tuple) > 1 else title\n\n match = re.search(pattern, line, re.IGNORECASE)\n if match:\n # Check for false positives (comments, test files)\n if self._is_false_positive(line, file_path):\n continue\n\n # Determine severity based on context\n severity = self._calculate_severity(\n default_severity,\n file_path,\n category\n )\n\n finding = SecurityFinding(\n rule_id=f\"{category}-{len(self.findings) + 1:04d}\",\n severity=severity,\n category=category,\n title=title,\n description=description,\n file_path=file_path,\n line_number=line_num,\n code_snippet=line.strip()[:100],\n recommendation=self._get_recommendation(category)\n )\n\n self.findings.append(finding)\n\n def _is_false_positive(self, line: str, file_path: str) -> bool:\n \"\"\"Check if finding is likely a false positive.\"\"\"\n # Skip comments\n stripped = line.strip()\n if stripped.startswith('#') or stripped.startswith('//') or stripped.startswith('*'):\n return True\n\n # Skip test files for some patterns\n if 'test' in file_path.lower() or 'spec' in file_path.lower():\n return True\n\n # Skip example/sample values\n lower_line = line.lower()\n if any(skip in lower_line for skip in ['example', 'sample', 'placeholder', 'xxx', 'your_']):\n return True\n\n return False\n\n def _calculate_severity(self, default: str, file_path: str, category: str) -> str:\n \"\"\"Calculate severity based on context.\"\"\"\n # Increase severity for production-related files\n if any(prod in file_path.lower() for prod in ['prod', 'production', 'deploy']):\n if default == 'high':\n return 'critical'\n if default == 'medium':\n return 'high'\n\n # Decrease severity for config examples\n if 'example' in file_path.lower() or 'sample' in file_path.lower():\n if default == 'critical':\n return 'high'\n if default == 'high':\n return 'medium'\n\n return default\n\n def _get_recommendation(self, category: str) -> str:\n \"\"\"Get remediation recommendation for category.\"\"\"\n recommendations = {\n 'secrets': 'Remove hardcoded secrets. Use environment variables or a secrets manager (HashiCorp Vault, AWS Secrets Manager).',\n 'injection': 'Use parameterized queries or prepared statements. Never concatenate user input into queries.',\n 'xss': 'Always escape or sanitize user input before rendering. Use framework-provided escaping functions.',\n 'path-traversal': 'Validate and sanitize file paths. Use allowlists for permitted directories.',\n }\n return recommendations.get(category, 'Review and remediate the security issue.')\n\n def _print_summary(self, result: Dict):\n \"\"\"Print scan summary.\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(\"SECURITY SCAN SUMMARY\")\n print(\"=\" * 60)\n print(f\"Target: {result['target']}\")\n print(f\"Files scanned: {result['files_scanned']}\")\n print(f\"Scan duration: {result['scan_duration_seconds']}s\")\n print(f\"Total findings: {result['total_findings']}\")\n print()\n\n if result['severity_counts']:\n print(\"Findings by severity:\")\n for severity in ['critical', 'high', 'medium', 'low', 'info']:\n count = result['severity_counts'].get(severity, 0)\n if count > 0:\n print(f\" {severity.upper()}: {count}\")\n print(\"=\" * 60)\n\n if result['total_findings'] > 0:\n print(\"\\nTop findings:\")\n for finding in result['findings'][:5]:\n print(f\"\\n [{finding['severity'].upper()}] {finding['title']}\")\n print(f\" File: {finding['file_path']}:{finding['line_number']}\")\n print(f\" {finding['description']}\")\n\n\ndef main():\n \"\"\"Main entry point for CLI.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Scan source code for security vulnerabilities\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s /path/to/project\n %(prog)s /path/to/project --severity high\n %(prog)s /path/to/project --output report.json --json\n %(prog)s /path/to/file.py --verbose\n \"\"\"\n )\n\n parser.add_argument(\n \"target\",\n help=\"Directory or file to scan\"\n )\n parser.add_argument(\n \"--severity\", \"-s\",\n choices=[\"critical\", \"high\", \"medium\", \"low\", \"info\"],\n default=\"low\",\n help=\"Minimum severity to report (default: low)\"\n )\n parser.add_argument(\n \"--verbose\", \"-v\",\n action=\"store_true\",\n help=\"Enable verbose output\"\n )\n parser.add_argument(\n \"--json\",\n action=\"store_true\",\n help=\"Output results as JSON\"\n )\n parser.add_argument(\n \"--output\", \"-o\",\n help=\"Output file path\"\n )\n\n args = parser.parse_args()\n\n scanner = SecurityScanner(\n target_path=args.target,\n severity_threshold=args.severity,\n verbose=args.verbose\n )\n\n result = scanner.scan()\n\n if args.json:\n output = json.dumps(result, indent=2)\n if args.output:\n with open(args.output, 'w') as f:\n f.write(output)\n print(f\"\\nResults written to {args.output}\")\n else:\n print(output)\n elif args.output:\n with open(args.output, 'w') as f:\n json.dump(result, f, indent=2)\n print(f\"\\nResults written to {args.output}\")\n\n # Exit with error code if critical/high findings\n if result.get('severity_counts', {}).get('critical', 0) > 0:\n sys.exit(2)\n if result.get('severity_counts', {}).get('high', 0) > 0:\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":16696,"content_sha256":"4f633845ad1f56ffe0fe3173c8be0d1ab989b7444e06e07ae9defc9c957732f8"},{"filename":"scripts/vulnerability_assessor.py","content":"#!/usr/bin/env python3\n\"\"\"\nVulnerability Assessor - Scan dependencies for known CVEs and security issues.\n\nTable of Contents:\n VulnerabilityAssessor - Main class for dependency vulnerability assessment\n __init__ - Initialize with target path and options\n assess() - Run complete vulnerability assessment\n scan_npm() - Scan package.json for npm vulnerabilities\n scan_python() - Scan requirements.txt for Python vulnerabilities\n scan_go() - Scan go.mod for Go vulnerabilities\n _parse_package_json() - Parse npm package.json\n _parse_requirements() - Parse Python requirements.txt\n _parse_go_mod() - Parse Go go.mod\n _check_vulnerability() - Check package against CVE database\n _calculate_risk_score() - Calculate overall risk score\n main() - CLI entry point\n\nUsage:\n python vulnerability_assessor.py /path/to/project\n python vulnerability_assessor.py /path/to/project --severity high\n python vulnerability_assessor.py /path/to/project --output report.json --json\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\n\n\n@dataclass\nclass Vulnerability:\n \"\"\"Represents a dependency vulnerability.\"\"\"\n cve_id: str\n package: str\n installed_version: str\n fixed_version: str\n severity: str # critical, high, medium, low\n cvss_score: float\n description: str\n ecosystem: str # npm, pypi, go\n recommendation: str\n\n\nclass VulnerabilityAssessor:\n \"\"\"Assess project dependencies for known vulnerabilities.\"\"\"\n\n # Known CVE database (simplified - real implementation would query NVD/OSV)\n KNOWN_CVES = {\n # npm packages\n 'lodash': [\n {'version_lt': '4.17.21', 'cve': 'CVE-2021-23337', 'cvss': 7.2,\n 'severity': 'high', 'desc': 'Command injection in lodash',\n 'fixed': '4.17.21'},\n {'version_lt': '4.17.19', 'cve': 'CVE-2020-8203', 'cvss': 7.4,\n 'severity': 'high', 'desc': 'Prototype pollution in lodash',\n 'fixed': '4.17.19'},\n ],\n 'axios': [\n {'version_lt': '1.6.0', 'cve': 'CVE-2023-45857', 'cvss': 6.5,\n 'severity': 'medium', 'desc': 'CSRF token exposure in axios',\n 'fixed': '1.6.0'},\n ],\n 'express': [\n {'version_lt': '4.17.3', 'cve': 'CVE-2022-24999', 'cvss': 7.5,\n 'severity': 'high', 'desc': 'Open redirect in express',\n 'fixed': '4.17.3'},\n ],\n 'jsonwebtoken': [\n {'version_lt': '9.0.0', 'cve': 'CVE-2022-23529', 'cvss': 9.8,\n 'severity': 'critical', 'desc': 'JWT algorithm confusion attack',\n 'fixed': '9.0.0'},\n ],\n 'minimist': [\n {'version_lt': '1.2.6', 'cve': 'CVE-2021-44906', 'cvss': 9.8,\n 'severity': 'critical', 'desc': 'Prototype pollution in minimist',\n 'fixed': '1.2.6'},\n ],\n 'node-fetch': [\n {'version_lt': '2.6.7', 'cve': 'CVE-2022-0235', 'cvss': 8.8,\n 'severity': 'high', 'desc': 'Information exposure in node-fetch',\n 'fixed': '2.6.7'},\n ],\n # Python packages\n 'django': [\n {'version_lt': '4.2.8', 'cve': 'CVE-2023-46695', 'cvss': 7.5,\n 'severity': 'high', 'desc': 'DoS via file uploads in Django',\n 'fixed': '4.2.8'},\n ],\n 'requests': [\n {'version_lt': '2.31.0', 'cve': 'CVE-2023-32681', 'cvss': 6.1,\n 'severity': 'medium', 'desc': 'Proxy-Auth header leak in requests',\n 'fixed': '2.31.0'},\n ],\n 'pillow': [\n {'version_lt': '10.0.1', 'cve': 'CVE-2023-44271', 'cvss': 7.5,\n 'severity': 'high', 'desc': 'DoS via crafted image in Pillow',\n 'fixed': '10.0.1'},\n ],\n 'cryptography': [\n {'version_lt': '41.0.4', 'cve': 'CVE-2023-38325', 'cvss': 7.5,\n 'severity': 'high', 'desc': 'NULL pointer dereference in cryptography',\n 'fixed': '41.0.4'},\n ],\n 'pyyaml': [\n {'version_lt': '6.0.1', 'cve': 'CVE-2020-14343', 'cvss': 9.8,\n 'severity': 'critical', 'desc': 'Arbitrary code execution in PyYAML',\n 'fixed': '6.0.1'},\n ],\n 'urllib3': [\n {'version_lt': '2.0.6', 'cve': 'CVE-2023-43804', 'cvss': 8.1,\n 'severity': 'high', 'desc': 'Cookie header leak in urllib3',\n 'fixed': '2.0.6'},\n ],\n # Go packages\n 'golang.org/x/crypto': [\n {'version_lt': 'v0.17.0', 'cve': 'CVE-2023-48795', 'cvss': 5.9,\n 'severity': 'medium', 'desc': 'SSH prefix truncation attack',\n 'fixed': 'v0.17.0'},\n ],\n 'golang.org/x/net': [\n {'version_lt': 'v0.17.0', 'cve': 'CVE-2023-44487', 'cvss': 7.5,\n 'severity': 'high', 'desc': 'HTTP/2 rapid reset attack',\n 'fixed': 'v0.17.0'},\n ],\n }\n\n SEVERITY_ORDER = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}\n\n def __init__(\n self,\n target_path: str,\n severity_threshold: str = \"low\",\n verbose: bool = False\n ):\n \"\"\"\n Initialize the vulnerability assessor.\n\n Args:\n target_path: Directory to scan for dependency files\n severity_threshold: Minimum severity to report\n verbose: Enable verbose output\n \"\"\"\n self.target_path = Path(target_path)\n self.severity_threshold = severity_threshold\n self.verbose = verbose\n self.vulnerabilities: List[Vulnerability] = []\n self.packages_scanned = 0\n self.files_scanned = 0\n\n def assess(self) -> Dict:\n \"\"\"\n Run complete vulnerability assessment.\n\n Returns:\n Dict with assessment results\n \"\"\"\n print(f\"Vulnerability Assessor - Scanning: {self.target_path}\")\n print(f\"Severity threshold: {self.severity_threshold}\")\n print()\n\n if not self.target_path.exists():\n return {\"status\": \"error\", \"message\": f\"Path not found: {self.target_path}\"}\n\n start_time = datetime.now()\n\n # Scan npm dependencies\n package_json = self.target_path / \"package.json\"\n if package_json.exists():\n self.scan_npm(package_json)\n self.files_scanned += 1\n\n # Scan Python dependencies\n requirements_files = [\n \"requirements.txt\",\n \"requirements-dev.txt\",\n \"requirements-prod.txt\",\n \"pyproject.toml\"\n ]\n for req_file in requirements_files:\n req_path = self.target_path / req_file\n if req_path.exists():\n self.scan_python(req_path)\n self.files_scanned += 1\n\n # Scan Go dependencies\n go_mod = self.target_path / \"go.mod\"\n if go_mod.exists():\n self.scan_go(go_mod)\n self.files_scanned += 1\n\n # Scan package-lock.json for transitive dependencies\n package_lock = self.target_path / \"package-lock.json\"\n if package_lock.exists():\n self.scan_npm_lock(package_lock)\n self.files_scanned += 1\n\n # Filter by severity\n threshold_level = self.SEVERITY_ORDER.get(self.severity_threshold, 3)\n filtered_vulns = [\n v for v in self.vulnerabilities\n if self.SEVERITY_ORDER.get(v.severity, 3) \u003c= threshold_level\n ]\n\n end_time = datetime.now()\n scan_duration = (end_time - start_time).total_seconds()\n\n # Group by severity\n severity_counts = {}\n for vuln in filtered_vulns:\n severity_counts[vuln.severity] = severity_counts.get(vuln.severity, 0) + 1\n\n # Calculate risk score\n risk_score = self._calculate_risk_score(filtered_vulns)\n\n result = {\n \"status\": \"completed\",\n \"target\": str(self.target_path),\n \"files_scanned\": self.files_scanned,\n \"packages_scanned\": self.packages_scanned,\n \"scan_duration_seconds\": round(scan_duration, 2),\n \"total_vulnerabilities\": len(filtered_vulns),\n \"risk_score\": risk_score,\n \"risk_level\": self._get_risk_level(risk_score),\n \"severity_counts\": severity_counts,\n \"vulnerabilities\": [asdict(v) for v in filtered_vulns]\n }\n\n self._print_summary(result)\n\n return result\n\n def scan_npm(self, package_json_path: Path):\n \"\"\"Scan package.json for npm vulnerabilities.\"\"\"\n if self.verbose:\n print(f\" Scanning: {package_json_path}\")\n\n try:\n with open(package_json_path, 'r') as f:\n data = json.load(f)\n\n deps = {}\n deps.update(data.get('dependencies', {}))\n deps.update(data.get('devDependencies', {}))\n\n for package, version_spec in deps.items():\n self.packages_scanned += 1\n version = self._normalize_version(version_spec)\n self._check_vulnerability(package.lower(), version, 'npm')\n\n except Exception as e:\n if self.verbose:\n print(f\" Error scanning {package_json_path}: {e}\")\n\n def scan_npm_lock(self, package_lock_path: Path):\n \"\"\"Scan package-lock.json for transitive dependencies.\"\"\"\n if self.verbose:\n print(f\" Scanning: {package_lock_path}\")\n\n try:\n with open(package_lock_path, 'r') as f:\n data = json.load(f)\n\n # Handle npm v2/v3 lockfile format\n packages = data.get('packages', {})\n if not packages:\n # npm v1 format\n packages = data.get('dependencies', {})\n\n for pkg_path, pkg_info in packages.items():\n if not pkg_path: # Skip root\n continue\n\n # Extract package name from path\n package = pkg_path.split('node_modules/')[-1]\n version = pkg_info.get('version', '')\n\n if package and version:\n self.packages_scanned += 1\n self._check_vulnerability(package.lower(), version, 'npm')\n\n except Exception as e:\n if self.verbose:\n print(f\" Error scanning {package_lock_path}: {e}\")\n\n def scan_python(self, requirements_path: Path):\n \"\"\"Scan requirements.txt for Python vulnerabilities.\"\"\"\n if self.verbose:\n print(f\" Scanning: {requirements_path}\")\n\n try:\n content = requirements_path.read_text()\n\n # Handle pyproject.toml\n if requirements_path.name == 'pyproject.toml':\n self._scan_pyproject(content)\n return\n\n # Parse requirements.txt\n for line in content.split('\\n'):\n line = line.strip()\n if not line or line.startswith('#') or line.startswith('-'):\n continue\n\n # Parse package==version or package>=version\n match = re.match(r'^([a-zA-Z0-9_-]+)\\s*([=\u003c>!~]+)\\s*([0-9.]+)', line)\n if match:\n package = match.group(1).lower()\n version = match.group(3)\n self.packages_scanned += 1\n self._check_vulnerability(package, version, 'pypi')\n\n except Exception as e:\n if self.verbose:\n print(f\" Error scanning {requirements_path}: {e}\")\n\n def _scan_pyproject(self, content: str):\n \"\"\"Parse pyproject.toml for dependencies.\"\"\"\n # Simple parsing - real implementation would use toml library\n in_deps = False\n for line in content.split('\\n'):\n line = line.strip()\n if '[project.dependencies]' in line or '[tool.poetry.dependencies]' in line:\n in_deps = True\n continue\n if line.startswith('[') and in_deps:\n in_deps = False\n continue\n if in_deps and '=' in line:\n match = re.match(r'\"?([a-zA-Z0-9_-]+)\"?\\s*[=:]\\s*\"?([^\"]+)\"?', line)\n if match:\n package = match.group(1).lower()\n version_spec = match.group(2)\n version = self._normalize_version(version_spec)\n self.packages_scanned += 1\n self._check_vulnerability(package, version, 'pypi')\n\n def scan_go(self, go_mod_path: Path):\n \"\"\"Scan go.mod for Go vulnerabilities.\"\"\"\n if self.verbose:\n print(f\" Scanning: {go_mod_path}\")\n\n try:\n content = go_mod_path.read_text()\n\n # Parse require blocks\n in_require = False\n for line in content.split('\\n'):\n line = line.strip()\n\n if line.startswith('require ('):\n in_require = True\n continue\n if in_require and line == ')':\n in_require = False\n continue\n\n # Parse single require or block require\n if line.startswith('require ') or in_require:\n parts = line.replace('require ', '').split()\n if len(parts) >= 2:\n package = parts[0]\n version = parts[1]\n self.packages_scanned += 1\n self._check_vulnerability(package, version, 'go')\n\n except Exception as e:\n if self.verbose:\n print(f\" Error scanning {go_mod_path}: {e}\")\n\n def _normalize_version(self, version_spec: str) -> str:\n \"\"\"Extract version number from version specification.\"\"\"\n # Remove prefixes like ^, ~, >=, etc.\n version = re.sub(r'^[\\^~>=\u003c]+', '', version_spec)\n # Remove suffixes like -alpha, -beta, etc.\n version = re.split(r'[-+]', version)[0]\n return version.strip()\n\n def _check_vulnerability(self, package: str, version: str, ecosystem: str):\n \"\"\"Check if package version has known vulnerabilities.\"\"\"\n cves = self.KNOWN_CVES.get(package, [])\n\n for cve_info in cves:\n if self._version_lt(version, cve_info['version_lt']):\n vuln = Vulnerability(\n cve_id=cve_info['cve'],\n package=package,\n installed_version=version,\n fixed_version=cve_info['fixed'],\n severity=cve_info['severity'],\n cvss_score=cve_info['cvss'],\n description=cve_info['desc'],\n ecosystem=ecosystem,\n recommendation=f\"Upgrade {package} to {cve_info['fixed']} or later\"\n )\n # Avoid duplicates\n if not any(v.cve_id == vuln.cve_id and v.package == vuln.package\n for v in self.vulnerabilities):\n self.vulnerabilities.append(vuln)\n\n def _version_lt(self, version: str, threshold: str) -> bool:\n \"\"\"Compare version strings (simplified).\"\"\"\n try:\n # Remove 'v' prefix for Go versions\n v1 = version.lstrip('v')\n v2 = threshold.lstrip('v')\n\n parts1 = [int(x) for x in re.split(r'[.\\-]', v1) if x.isdigit()]\n parts2 = [int(x) for x in re.split(r'[.\\-]', v2) if x.isdigit()]\n\n # Pad shorter version\n while len(parts1) \u003c len(parts2):\n parts1.append(0)\n while len(parts2) \u003c len(parts1):\n parts2.append(0)\n\n return parts1 \u003c parts2\n except (ValueError, AttributeError):\n return False\n\n def _calculate_risk_score(self, vulnerabilities: List[Vulnerability]) -> float:\n \"\"\"Calculate overall risk score (0-100).\"\"\"\n if not vulnerabilities:\n return 0.0\n\n # Weight by severity and CVSS\n severity_weights = {'critical': 4.0, 'high': 3.0, 'medium': 2.0, 'low': 1.0}\n total_weight = 0.0\n\n for vuln in vulnerabilities:\n weight = severity_weights.get(vuln.severity, 1.0)\n total_weight += (vuln.cvss_score * weight)\n\n # Normalize to 0-100\n max_possible = len(vulnerabilities) * 10.0 * 4.0\n score = (total_weight / max_possible) * 100 if max_possible > 0 else 0\n\n return min(100.0, round(score, 1))\n\n def _get_risk_level(self, score: float) -> str:\n \"\"\"Get risk level from score.\"\"\"\n if score >= 70:\n return \"CRITICAL\"\n elif score >= 50:\n return \"HIGH\"\n elif score >= 25:\n return \"MEDIUM\"\n elif score > 0:\n return \"LOW\"\n return \"NONE\"\n\n def _print_summary(self, result: Dict):\n \"\"\"Print assessment summary.\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(\"VULNERABILITY ASSESSMENT SUMMARY\")\n print(\"=\" * 60)\n print(f\"Target: {result['target']}\")\n print(f\"Files scanned: {result['files_scanned']}\")\n print(f\"Packages scanned: {result['packages_scanned']}\")\n print(f\"Scan duration: {result['scan_duration_seconds']}s\")\n print(f\"Total vulnerabilities: {result['total_vulnerabilities']}\")\n print(f\"Risk score: {result['risk_score']}/100 ({result['risk_level']})\")\n print()\n\n if result['severity_counts']:\n print(\"Vulnerabilities by severity:\")\n for severity in ['critical', 'high', 'medium', 'low']:\n count = result['severity_counts'].get(severity, 0)\n if count > 0:\n print(f\" {severity.upper()}: {count}\")\n print(\"=\" * 60)\n\n if result['total_vulnerabilities'] > 0:\n print(\"\\nTop vulnerabilities:\")\n # Sort by CVSS score\n sorted_vulns = sorted(\n result['vulnerabilities'],\n key=lambda x: x['cvss_score'],\n reverse=True\n )\n for vuln in sorted_vulns[:5]:\n print(f\"\\n [{vuln['severity'].upper()}] {vuln['cve_id']}\")\n print(f\" Package: {vuln['package']}@{vuln['installed_version']}\")\n print(f\" CVSS: {vuln['cvss_score']}\")\n print(f\" Fix: Upgrade to {vuln['fixed_version']}\")\n\n\ndef main():\n \"\"\"Main entry point for CLI.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Scan dependencies for known vulnerabilities\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s /path/to/project\n %(prog)s /path/to/project --severity high\n %(prog)s /path/to/project --output report.json --json\n %(prog)s . --verbose\n \"\"\"\n )\n\n parser.add_argument(\n \"target\",\n help=\"Directory containing dependency files\"\n )\n parser.add_argument(\n \"--severity\", \"-s\",\n choices=[\"critical\", \"high\", \"medium\", \"low\"],\n default=\"low\",\n help=\"Minimum severity to report (default: low)\"\n )\n parser.add_argument(\n \"--verbose\", \"-v\",\n action=\"store_true\",\n help=\"Enable verbose output\"\n )\n parser.add_argument(\n \"--json\",\n action=\"store_true\",\n help=\"Output results as JSON\"\n )\n parser.add_argument(\n \"--output\", \"-o\",\n help=\"Output file path\"\n )\n\n args = parser.parse_args()\n\n assessor = VulnerabilityAssessor(\n target_path=args.target,\n severity_threshold=args.severity,\n verbose=args.verbose\n )\n\n result = assessor.assess()\n\n if args.json:\n output = json.dumps(result, indent=2)\n if args.output:\n with open(args.output, 'w') as f:\n f.write(output)\n print(f\"\\nResults written to {args.output}\")\n else:\n print(output)\n elif args.output:\n with open(args.output, 'w') as f:\n json.dump(result, f, indent=2)\n print(f\"\\nResults written to {args.output}\")\n\n # Exit with error code if critical/high vulnerabilities\n if result.get('severity_counts', {}).get('critical', 0) > 0:\n sys.exit(2)\n if result.get('severity_counts', {}).get('high', 0) > 0:\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":20415,"content_sha256":"93e17821b26dec7852dedafeb00c6b2448ee342c4593ed92b76b9b20078e9eda"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Senior SecOps Engineer","type":"text"}]},{"type":"paragraph","content":[{"text":"Complete toolkit for Security Operations including vulnerability management, compliance verification, secure coding practices, and security automation.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Table of Contents","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Core Capabilities","type":"text","marks":[{"type":"link","attrs":{"href":"#core-capabilities","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Workflows","type":"text","marks":[{"type":"link","attrs":{"href":"#workflows","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool Reference","type":"text","marks":[{"type":"link","attrs":{"href":"#tool-reference","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Standards","type":"text","marks":[{"type":"link","attrs":{"href":"#security-standards","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance Frameworks","type":"text","marks":[{"type":"link","attrs":{"href":"#compliance-frameworks","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Best Practices","type":"text","marks":[{"type":"link","attrs":{"href":"#best-practices","title":null}}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Capabilities","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Security Scanner","type":"text"}]},{"type":"paragraph","content":[{"text":"Scan source code for security vulnerabilities including hardcoded secrets, SQL injection, XSS, command injection, and path traversal.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Scan project for security issues\npython scripts/security_scanner.py /path/to/project\n\n# Filter by severity\npython scripts/security_scanner.py /path/to/project --severity high\n\n# JSON output for CI/CD\npython scripts/security_scanner.py /path/to/project --json --output report.json","type":"text"}]},{"type":"paragraph","content":[{"text":"Detects:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Hardcoded secrets (API keys, passwords, AWS credentials, GitHub tokens, private keys)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SQL injection patterns (string concatenation, f-strings, template literals)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"XSS vulnerabilities (innerHTML assignment, unsafe DOM manipulation, React unsafe patterns)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Command injection (shell=True, exec, eval with user input)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Path traversal (file operations with user input)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Vulnerability Assessor","type":"text"}]},{"type":"paragraph","content":[{"text":"Scan dependencies for known CVEs across npm, Python, and Go ecosystems.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Assess project dependencies\npython scripts/vulnerability_assessor.py /path/to/project\n\n# Critical/high only\npython scripts/vulnerability_assessor.py /path/to/project --severity high\n\n# Export vulnerability report\npython scripts/vulnerability_assessor.py /path/to/project --json --output vulns.json","type":"text"}]},{"type":"paragraph","content":[{"text":"Scans:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"package.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"package-lock.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" (npm)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"requirements.txt","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"pyproject.toml","type":"text","marks":[{"type":"code_inline"}]},{"text":" (Python)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"go.mod","type":"text","marks":[{"type":"code_inline"}]},{"text":" (Go)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Output:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CVE IDs with CVSS scores","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Affected package versions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Fixed versions for remediation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Overall risk score (0-100)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Compliance Checker","type":"text"}]},{"type":"paragraph","content":[{"text":"Verify security compliance against SOC 2, PCI-DSS, HIPAA, and GDPR frameworks.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Check all frameworks\npython scripts/compliance_checker.py /path/to/project\n\n# Specific framework\npython scripts/compliance_checker.py /path/to/project --framework soc2\npython scripts/compliance_checker.py /path/to/project --framework pci-dss\npython scripts/compliance_checker.py /path/to/project --framework hipaa\npython scripts/compliance_checker.py /path/to/project --framework gdpr\n\n# Export compliance report\npython scripts/compliance_checker.py /path/to/project --json --output compliance.json","type":"text"}]},{"type":"paragraph","content":[{"text":"Verifies:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Access control implementation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Encryption at rest and in transit","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit logging","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Authentication strength (MFA, password hashing)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security documentation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CI/CD security controls","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Workflows","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Workflow 1: Security Audit","type":"text"}]},{"type":"paragraph","content":[{"text":"Complete security assessment of a codebase.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Step 1: Scan for code vulnerabilities\npython scripts/security_scanner.py . --severity medium\n# STOP if exit code 2 — resolve critical findings before continuing","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Step 2: Check dependency vulnerabilities\npython scripts/vulnerability_assessor.py . --severity high\n# STOP if exit code 2 — patch critical CVEs before continuing","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Step 3: Verify compliance controls\npython scripts/compliance_checker.py . --framework all\n# STOP if exit code 2 — address critical gaps before proceeding","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Step 4: Generate combined reports\npython scripts/security_scanner.py . --json --output security.json\npython scripts/vulnerability_assessor.py . --json --output vulns.json\npython scripts/compliance_checker.py . --json --output compliance.json","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Workflow 2: CI/CD Security Gate","type":"text"}]},{"type":"paragraph","content":[{"text":"Integrate security checks into deployment pipeline.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"yaml"},"content":[{"text":"# .github/workflows/security.yml\nname: \"security-scan\"\n\non:\n pull_request:\n branches: [main, develop]\n\njobs:\n security-scan:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: \"set-up-python\"\n uses: actions/setup-python@v5\n with:\n python-version: '3.11'\n\n - name: \"security-scanner\"\n run: python scripts/security_scanner.py . --severity high\n\n - name: \"vulnerability-assessment\"\n run: python scripts/vulnerability_assessor.py . --severity critical\n\n - name: \"compliance-check\"\n run: python scripts/compliance_checker.py . --framework soc2","type":"text"}]},{"type":"paragraph","content":[{"text":"Each step fails the pipeline on its respective exit code — no deployment proceeds past a critical finding.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Workflow 3: CVE Triage","type":"text"}]},{"type":"paragraph","content":[{"text":"Respond to a new CVE affecting your application.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"1. ASSESS (0-2 hours)\n - Identify affected systems using vulnerability_assessor.py\n - Check if CVE is being actively exploited\n - Determine CVSS environmental score for your context\n - STOP if CVSS 9.0+ on internet-facing system — escalate immediately\n\n2. PRIORITIZE\n - Critical (CVSS 9.0+, internet-facing): 24 hours\n - High (CVSS 7.0-8.9): 7 days\n - Medium (CVSS 4.0-6.9): 30 days\n - Low (CVSS \u003c 4.0): 90 days\n\n3. REMEDIATE\n - Update affected dependency to fixed version\n - Run security_scanner.py to verify fix (must return exit code 0)\n - STOP if scanner still flags the CVE — do not deploy\n - Test for regressions\n - Deploy with enhanced monitoring\n\n4. VERIFY\n - Re-run vulnerability_assessor.py\n - Confirm CVE no longer reported\n - Document remediation actions","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Workflow 4: Incident Response","type":"text"}]},{"type":"paragraph","content":[{"text":"Security incident handling procedure.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"PHASE 1: DETECT & IDENTIFY (0-15 min)\n- Alert received and acknowledged\n- Initial severity assessment (SEV-1 to SEV-4)\n- Incident commander assigned\n- Communication channel established\n\nPHASE 2: CONTAIN (15-60 min)\n- Affected systems identified\n- Network isolation if needed\n- Credentials rotated if compromised\n- Preserve evidence (logs, memory dumps)\n\nPHASE 3: ERADICATE (1-4 hours)\n- Root cause identified\n- Malware/backdoors removed\n- Vulnerabilities patched (run security_scanner.py; must return exit code 0)\n- Systems hardened\n\nPHASE 4: RECOVER (4-24 hours)\n- Systems restored from clean backup\n- Services brought back online\n- Enhanced monitoring enabled\n- User access restored\n\nPHASE 5: POST-INCIDENT (24-72 hours)\n- Incident timeline documented\n- Root cause analysis complete\n- Lessons learned documented\n- Preventive measures implemented\n- Stakeholder report delivered","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Tool Reference","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"security_scanner.py","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Option","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"target","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Directory or file to scan","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--severity, -s","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Minimum severity: critical, high, medium, low","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--verbose, -v","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Show files as they're scanned","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--json","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output results as JSON","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--output, -o","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Write results to file","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Exit Codes:","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"0","type":"text","marks":[{"type":"code_inline"}]},{"text":" = no critical/high findings · ","type":"text"},{"text":"1","type":"text","marks":[{"type":"code_inline"}]},{"text":" = high severity findings · ","type":"text"},{"text":"2","type":"text","marks":[{"type":"code_inline"}]},{"text":" = critical severity findings","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"vulnerability_assessor.py","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Option","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"target","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Directory containing dependency files","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--severity, -s","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Minimum severity: critical, high, medium, low","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--verbose, -v","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Show files as they're scanned","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--json","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output results as JSON","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--output, -o","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Write results to file","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Exit Codes:","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"0","type":"text","marks":[{"type":"code_inline"}]},{"text":" = no critical/high vulnerabilities · ","type":"text"},{"text":"1","type":"text","marks":[{"type":"code_inline"}]},{"text":" = high severity vulnerabilities · ","type":"text"},{"text":"2","type":"text","marks":[{"type":"code_inline"}]},{"text":" = critical severity vulnerabilities","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"compliance_checker.py","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Option","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"target","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Directory to check","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--framework, -f","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Framework: soc2, pci-dss, hipaa, gdpr, all","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--verbose, -v","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Show checks as they run","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--json","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output results as JSON","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"--output, -o","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Write results to file","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Exit Codes:","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"0","type":"text","marks":[{"type":"code_inline"}]},{"text":" = compliant (90%+ score) · ","type":"text"},{"text":"1","type":"text","marks":[{"type":"code_inline"}]},{"text":" = non-compliant (50-69% score) · ","type":"text"},{"text":"2","type":"text","marks":[{"type":"code_inline"}]},{"text":" = critical gaps (\u003c50% score)","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Security Standards","type":"text"}]},{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"references/security_standards.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" for OWASP Top 10 full guidance, secure coding standards, authentication requirements, and API security controls.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Secure Coding Checklist","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"markdown"},"content":[{"text":"## Input Validation\n- [ ] Validate all input on server side\n- [ ] Use allowlists over denylists\n- [ ] Sanitize for specific context (HTML, SQL, shell)\n\n## Output Encoding\n- [ ] HTML encode for browser output\n- [ ] URL encode for URLs\n- [ ] JavaScript encode for script contexts\n\n## Authentication\n- [ ] Use bcrypt/argon2 for passwords\n- [ ] Implement MFA for sensitive operations\n- [ ] Enforce strong password policy\n\n## Session Management\n- [ ] Generate secure random session IDs\n- [ ] Set HttpOnly, Secure, SameSite flags\n- [ ] Implement session timeout (15 min idle)\n\n## Error Handling\n- [ ] Log errors with context (no secrets)\n- [ ] Return generic messages to users\n- [ ] Never expose stack traces in production\n\n## Secrets Management\n- [ ] Use environment variables or secrets manager\n- [ ] Never commit secrets to version control\n- [ ] Rotate credentials regularly","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Compliance Frameworks","type":"text"}]},{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"references/compliance_requirements.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" for full control mappings. Run ","type":"text"},{"text":"compliance_checker.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" to verify the controls below:","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"SOC 2 Type II","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CC6","type":"text","marks":[{"type":"strong"}]},{"text":" Logical Access: authentication, authorization, MFA","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CC7","type":"text","marks":[{"type":"strong"}]},{"text":" System Operations: monitoring, logging, incident response","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CC8","type":"text","marks":[{"type":"strong"}]},{"text":" Change Management: CI/CD, code review, deployment controls","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"PCI-DSS v4.0","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Req 3/4","type":"text","marks":[{"type":"strong"}]},{"text":": Encryption at rest and in transit (TLS 1.2+)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Req 6","type":"text","marks":[{"type":"strong"}]},{"text":": Secure development (input validation, secure coding)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Req 8","type":"text","marks":[{"type":"strong"}]},{"text":": Strong authentication (MFA, password policy)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Req 10/11","type":"text","marks":[{"type":"strong"}]},{"text":": Audit logging, SAST/DAST/penetration testing","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"HIPAA Security Rule","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Unique user IDs and audit trails for PHI access (164.312(a)(1), 164.312(b))","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MFA for person/entity authentication (164.312(d))","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Transmission encryption via TLS (164.312(e)(1))","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"GDPR","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Art 25/32","type":"text","marks":[{"type":"strong"}]},{"text":": Privacy by design, encryption, pseudonymization","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Art 33","type":"text","marks":[{"type":"strong"}]},{"text":": Breach notification within 72 hours","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Art 17/20","type":"text","marks":[{"type":"strong"}]},{"text":": Right to erasure and data portability","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Best Practices","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Secrets Management","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Hardcoded secret\nAPI_KEY = \"sk-1234567890abcdef\"\n\n# GOOD: Environment variable\nimport os\nAPI_KEY = os.environ.get(\"API_KEY\")\n\n# BETTER: Secrets manager\nfrom your_vault_client import get_secret\nAPI_KEY = get_secret(\"api/key\")","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"SQL Injection Prevention","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: String concatenation\nquery = f\"SELECT * FROM users WHERE id = {user_id}\"\n\n# GOOD: Parameterized query\ncursor.execute(\"SELECT * FROM users WHERE id = %s\", (user_id,))","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"XSS Prevention","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"javascript"},"content":[{"text":"// BAD: Direct innerHTML assignment is vulnerable\n// GOOD: Use textContent (auto-escaped)\nelement.textContent = userInput;\n\n// GOOD: Use sanitization library for HTML\nimport DOMPurify from 'dompurify';\nconst safeHTML = DOMPurify.sanitize(userInput);","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Authentication","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"javascript"},"content":[{"text":"// Password hashing\nconst bcrypt = require('bcrypt');\nconst SALT_ROUNDS = 12;\n\n// Hash password\nconst hash = await bcrypt.hash(password, SALT_ROUNDS);\n\n// Verify password\nconst match = await bcrypt.compare(password, hash);","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Headers","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"javascript"},"content":[{"text":"// Express.js security headers\nconst helmet = require('helmet');\napp.use(helmet());\n\n// Or manually set headers:\napp.use((req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'DENY');\n res.setHeader('X-XSS-Protection', '1; mode=block');\n res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');\n res.setHeader('Content-Security-Policy', \"default-src 'self'\");\n next();\n});","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"OWASP Top 10 Quick-Check","type":"text"}]},{"type":"paragraph","content":[{"text":"Categories follow the ","type":"text"},{"text":"OWASP Top 10:2025","type":"text","marks":[{"type":"link","attrs":{"href":"https://owasp.org/Top10/2025/","title":null}}]},{"text":". Rapid 15-minute assessment — run through each category and note pass/fail. For deep-dive testing, hand off to the ","type":"text"},{"text":"security-pen-testing","type":"text","marks":[{"type":"strong"}]},{"text":" skill.","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"#","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Category","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"One-Line Check","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A01","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Broken Access Control","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Verify role checks on every endpoint; test horizontal privilege escalation; block SSRF to internal and metadata endpoints (169.254.169.254)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A02","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Misconfiguration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Check default credentials removed; error pages generic","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A03","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Software Supply Chain Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Run ","type":"text"},{"text":"vulnerability_assessor.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" (zero critical/high CVEs); lockfiles committed; CI actions pinned","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A04","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Cryptographic Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Confirm TLS 1.2+ everywhere; no secrets in logs or source","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A05","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Injection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Run parameterized query audit; check ORM raw-query usage","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A06","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Insecure Design","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Review threat model exists for critical flows","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A07","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Authentication Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Verify MFA on admin; brute-force protection active","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A08","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Software or Data Integrity Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Confirm CI/CD pipeline signs artifacts; no unsigned deps","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A09","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Logging and Alerting Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Validate audit logs capture auth events; alerts configured","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A10","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Mishandling of Exceptional Conditions","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security checks fail closed on errors and timeouts; no stack traces in responses","type":"text"}]}]}]}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Deep dive needed?","type":"text","marks":[{"type":"strong"}]},{"text":" Hand off to ","type":"text"},{"text":"security-pen-testing","type":"text","marks":[{"type":"code_inline"}]},{"text":" for full OWASP Testing Guide coverage.","type":"text"}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Secret Scanning Tools","type":"text"}]},{"type":"paragraph","content":[{"text":"Choose the right scanner for each stage of your workflow:","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Best For","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Language","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Pre-commit","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"CI/CD","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Custom Rules","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"gitleaks","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CI pipelines, full-repo scans","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Go","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Yes","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Yes","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"TOML regexes","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"detect-secrets","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Pre-commit hooks, incremental","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Python","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Yes","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Partial","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Plugin-based","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"truffleHog","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Deep history scans, entropy","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Go","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"No","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Yes","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":"center"},"content":[{"type":"paragraph","content":[{"text":"Regex + entropy","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Recommended setup:","type":"text","marks":[{"type":"strong"}]},{"text":" Use ","type":"text"},{"text":"detect-secrets","type":"text","marks":[{"type":"code_inline"}]},{"text":" as a pre-commit hook (catches secrets before they enter history) and ","type":"text"},{"text":"gitleaks","type":"text","marks":[{"type":"code_inline"}]},{"text":" in CI (catches anything that slips through).","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# detect-secrets pre-commit hook (.pre-commit-config.yaml)\n- repo: https://github.com/Yelp/detect-secrets\n rev: v1.4.0\n hooks:\n - id: detect-secrets\n args: ['--baseline', '.secrets.baseline']\n\n# gitleaks in GitHub Actions\n- name: gitleaks\n uses: gitleaks/gitleaks-action@v2\n env:\n GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Supply Chain Security","type":"text"}]},{"type":"paragraph","content":[{"text":"Protect against dependency and artifact tampering with SBOM generation, artifact signing, and SLSA compliance.","type":"text"}]},{"type":"paragraph","content":[{"text":"SBOM Generation:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"syft","type":"text","marks":[{"type":"strong"}]},{"text":" — generates SBOMs from container images or source dirs (SPDX, CycloneDX formats)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"cyclonedx-cli","type":"text","marks":[{"type":"strong"}]},{"text":" — CycloneDX-native tooling; merge multiple SBOMs for mono-repos","type":"text"}]}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Generate SBOM from container image\nsyft packages ghcr.io/org/app:latest -o cyclonedx-json > sbom.json","type":"text"}]},{"type":"paragraph","content":[{"text":"Artifact Signing (Sigstore/cosign):","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Sign a container image (keyless via OIDC)\ncosign sign ghcr.io/org/app:latest\n# Verify signature\ncosign verify ghcr.io/org/app:latest [email protected] --certificate-oidc-issuer=https://token.actions.githubusercontent.com","type":"text"}]},{"type":"paragraph","content":[{"text":"SLSA Levels Overview:","type":"text","marks":[{"type":"strong"}]}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Level","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Requirement","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"What It Proves","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"1","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Build process documented","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Provenance exists","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"2","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Hosted build service, signed provenance","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tamper-resistant provenance","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"3","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Hardened build platform, non-falsifiable provenance","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tamper-proof build","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"4","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Two-party review, hermetic builds","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Maximum supply-chain assurance","type":"text"}]}]}]}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Cross-references:","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"security-pen-testing","type":"text","marks":[{"type":"code_inline"}]},{"text":" (vulnerability exploitation testing), ","type":"text"},{"text":"dependency-auditor","type":"text","marks":[{"type":"code_inline"}]},{"text":" (license and CVE audit for dependencies).","type":"text"}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reference Documentation","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Document","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/security_standards.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"OWASP Top 10, secure coding, authentication, API security","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/vulnerability_management_guide.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CVE triage, CVSS scoring, remediation workflows","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/compliance_requirements.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SOC 2, PCI-DSS, HIPAA, GDPR full control mappings","type":"text"}]}]}]}]}]},"metadata":{"date":"2026-11-02","name":"senior-secops","author":"@skillopedia","source":{"stars":29164,"repo_name":"claude-skills","origin_url":"https://github.com/alirezarezvani/claude-skills/blob/HEAD/engineering-team/skills/senior-secops/SKILL.md","repo_owner":"alirezarezvani","body_sha256":"dc3697ebab8dd6f04be7ceece58d54aa8b6489470a7f8456afd464f163f21a19","cluster_key":"b55501ff739b4a9e2f9af578fe53bc258f696528ab418fa14735e303e6e22000","clean_bundle":{"format":"clean-skill-bundle-v1","source":"alirezarezvani/claude-skills/engineering-team/skills/senior-secops/SKILL.md","text_bytes":134238,"source_commit":"9ef0c3c213932e645cc5cbeeb3c35c3a762a2437","skills_sh_rank":13801,"attachment_count":6,"text_attachments":6,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"engineering-team/skills/senior-secops/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"security","category_label":"Security"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"security","import_tag":"skills-sh-top20k-2026-11","description":"Use for application security operations: security reviews, CVE remediation, hardening, secrets and auth, or SOC 2, PCI-DSS, HIPAA and GDPR checks. Scans with security_scanner.py, assesses CVEs with vulnerability_assessor.py and checks controls with compliance_checker.py."}},"renderedAt":1793666456376}

Senior SecOps Engineer Complete toolkit for Security Operations including vulnerability management, compliance verification, secure coding practices, and security automation. --- Table of Contents - Core Capabilities - Workflows - Tool Reference - Security Standards - Compliance Frameworks - Best Practices --- Core Capabilities 1. Security Scanner Scan source code for security vulnerabilities including hardcoded secrets, SQL injection, XSS, command injection, and path traversal. Detects: - Hardcoded secrets (API keys, passwords, AWS credentials, GitHub tokens, private keys) - SQL injection pa…